Sponsored
Sponsored
This approach involves directly simulating the sequence construction up to the desired nth binary string and retrieving the k-th bit from it. Since the problem ensures n and k are constrained, this method remains efficient enough.
Time Complexity: O(2^n), as each step fully constructs the sequence of size approximately 2^n.
Space Complexity: O(2^n), owing to storing the full sequence.
1#include <iostream>
2#include <string>
3
4char invertChar(char c) {
5 return c == '0' ? '1' : '0';
6}
7
8std::string invertAndReverse(const std::string& str) {
9 std::string inverted = str;
10 for (char& c : inverted) {
11 c = invertChar(c);
12 }
13 std::reverse(inverted.begin(), inverted.end());
14 return inverted;
15}
16
17char findKthBit(int n, int k) {
18 std::string S = "0";
19 for (int i = 2; i <= n; i++) {
20 S = S + "1" + invertAndReverse(S);
21 }
22 return S[k - 1];
23}
24
25int main() {
26 int n = 4, k = 11;
27 std::cout << "Output: " << findKthBit(n, k) << std::endl;
28 return 0;
29}
This C++ solution builds the sequence iteratively. It constructs each subsequent sequence by concatenating Si-1
, '1', and the inverted and reversed Si-1
. For each sequence, we append the required transformed part and continue until Sn
is fully formed.
This approach leverages the recursive nature and mathematical properties of the sequence to find the k-th bit without constructing the entire string. By recognizing the symmetry and structure, we use recursive calculations to directly determine the desired bit.
Time Complexity: O(n), limited by the recursion depth of n
.
Space Complexity: O(n), due to recursive call stack.
1
The Java approach leverages the recursive transformation and symmetry of sequences to find the requested bit. Avoids full sequence builds thus reducing complexity with strategic recursions shifting through the defined k value pathways.