Find Kth Bit in Nth Binary String - Problem
Find Kth Bit in Nth Binary String
You're given two positive integers
The sequence follows a fascinating recursive pattern:
• S₁ = "0" (base case)
• Sᵢ = Sᵢ₋₁ + "1" + reverse(invert(Sᵢ₋₁)) for i > 1
Where:
•
•
•
Example sequence:
• S₁ =
• S₂ =
• S₃ =
• S₄ =
Goal: Return the kth bit (1-indexed) in Sₙ efficiently without building the entire string.
You're given two positive integers
n and k, and need to find the kth bit in a special binary string sequence.The sequence follows a fascinating recursive pattern:
• S₁ = "0" (base case)
• Sᵢ = Sᵢ₋₁ + "1" + reverse(invert(Sᵢ₋₁)) for i > 1
Where:
•
+ denotes string concatenation•
invert(x) flips all bits (0→1, 1→0)•
reverse(x) reverses the stringExample sequence:
• S₁ =
"0"• S₂ =
"0" + "1" + reverse(invert("0")) = "0" + "1" + "1" = "011"• S₃ =
"011" + "1" + reverse(invert("011")) = "011" + "1" + "001" = "0111001"• S₄ =
"0111001" + "1" + "0110001" = "011100110110001"Goal: Return the kth bit (1-indexed) in Sₙ efficiently without building the entire string.
Input & Output
example_1.py — Basic Case
$
Input:
n = 3, k = 1
›
Output:
"0"
💡 Note:
S₃ = "0111001". The 1st bit is '0'.
example_2.py — Middle Position
$
Input:
n = 4, k = 11
›
Output:
"1"
💡 Note:
S₄ = "011100110110001". The 11th bit is '1'. This demonstrates finding a bit in the right (inverted-reversed) section.
example_3.py — Edge Case
$
Input:
n = 1, k = 1
›
Output:
"0"
💡 Note:
S₁ = "0". The only bit is '0'. This is the base case.
Visualization
Tap to expand
Understanding the Visualization
1
Base Pattern
Start with S₁ = '0' as the foundation
2
Growth Rule
Each new generation: Previous + '1' + InvertedReversedPrevious
3
Structure Recognition
Every string has predictable left-middle-right sections
4
Smart Navigation
Find target without building entire string using recursive position mapping
Key Takeaway
🎯 Key Insight: The binary string follows a fractal pattern where each generation has a predictable three-part structure. By recognizing this pattern, we can navigate directly to any position using recursive divide-and-conquer without the exponential space and time costs of string building.
Time & Space Complexity
Time Complexity
O(n)
We make at most n recursive calls, each doing constant work
✓ Linear Growth
Space Complexity
O(n)
Recursion depth is n, or O(1) if implemented iteratively
⚡ Linearithmic Space
Constraints
- 1 ≤ n ≤ 20
- 1 ≤ k ≤ 2n - 1
- k is guaranteed to be valid for the given n
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code