mirror of
https://github.com/Manoj-HV30/dsa-competitive-programming.git
synced 2026-05-16 19:35:22 +00:00
49 lines
1.2 KiB
C++
49 lines
1.2 KiB
C++
class Solution{
|
|
public:
|
|
char findKthBit(int n, int k){
|
|
if(n==1) return '0';
|
|
int len = 1<<n;
|
|
if(k<len/2) {
|
|
return findKthBit(n-1,k);
|
|
|
|
}
|
|
else if(k == len/2){
|
|
return '1';
|
|
}
|
|
else{
|
|
char correspondingBit = findKthBit(n-1, len-k);
|
|
return ((correspondingBit == '0')? '1':'0');
|
|
}
|
|
}
|
|
}
|
|
/*
|
|
Recursive Idea:
|
|
|
|
The string is defined as:
|
|
Sn = S(n-1) + "1" + reverse(invert(S(n-1)))
|
|
|
|
Instead of building the full string (which grows exponentially),
|
|
we determine where the k-th position lies:
|
|
|
|
1) If k is in the left half:
|
|
→ It directly corresponds to the same position in S(n-1).
|
|
→ So recurse: findKthBit(n-1, k)
|
|
|
|
2) If k is exactly the middle:
|
|
→ The middle element is always '1'.
|
|
|
|
3) If k is in the right half:
|
|
→ The right half is reverse(invert(S(n-1))).
|
|
→ Mirror the index using (len - k).
|
|
→ Recursively find that bit in S(n-1).
|
|
→ Invert the result.
|
|
|
|
Each recursive call reduces n by 1,
|
|
tracing the origin of the bit back to the base case S1 = "0".
|
|
|
|
Time Complexity: O(n)
|
|
Space Complexity: O(n) (recursion stack)
|
|
*/
|
|
|
|
// TC: o(n) and SC : o(n)
|