mirror of
https://github.com/Manoj-HV30/dsa-competitive-programming.git
synced 2026-05-16 19:35:22 +00:00
53 lines
1.3 KiB
C++
53 lines
1.3 KiB
C++
class Solution{
|
|
public:
|
|
char findKthBit(int n, int k){
|
|
int invertCount = 0;
|
|
int len = (1<<n)-1;
|
|
while(k>1){
|
|
if(k==len/2+1){
|
|
return invertCount % 2==0? '1' : '0';
|
|
|
|
}
|
|
if(k>len/2){
|
|
k = len-k+1;
|
|
invertCount++;
|
|
}
|
|
len/=2;
|
|
}
|
|
return invertCount%2==0?'0':'1';
|
|
|
|
}
|
|
};
|
|
|
|
//TC: o(n) , SC : o(1)
|
|
|
|
/*
|
|
Approach:
|
|
|
|
We do NOT build the full string Sn because its length grows exponentially (2^n - 1).
|
|
Instead, we use the recursive structure:
|
|
|
|
Sn = S(n-1) + "1" + reverse(invert(S(n-1)))
|
|
|
|
For any position k:
|
|
1) If k lies in the left half:
|
|
→ It directly corresponds to the same position in S(n-1).
|
|
|
|
2) If k is the middle element:
|
|
→ The value is always '1'.
|
|
|
|
3) If k lies in the right half:
|
|
→ The right half is reverse(invert(S(n-1))).
|
|
→ Mirror the index into the left half.
|
|
→ Remember that the value must be inverted.
|
|
|
|
We keep reducing the problem from Sn → S(n-1) until we reach
|
|
the base case S1 = "0".
|
|
|
|
The final answer depends on how many times we entered
|
|
the right half (i.e., how many inversions occurred).
|
|
|
|
Time Complexity: O(n)
|
|
Space Complexity: O(1) (iterative version)
|
|
*/
|