Find Kth Bit in Nth Binary String - Problem
Find Kth Bit in Nth Binary 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 string

Example 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
Binary String Fractal PatternS₁:0S₂:011PreviousMidInv+RevS₃:0111001S₂1~Rev(S₂)Optimal Algorithm1. Calculate string length: 2ⁿ - 12. Find middle position: length/2 + 13. If k == middle: return '1'4. If k < middle: recurse in left part5. If k > middle: recurse in right part → Map position: length - k + 1 → Invert the result🎯 Key InsightThe recursive structure allows us to navigateto any position without building the entire string!Time: O(n) | Space: O(1) iterative
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

n
2n
Linear Growth
Space Complexity
O(n)

Recursion depth is n, or O(1) if implemented iteratively

n
2n
Linearithmic Space

Constraints

  • 1 ≤ n ≤ 20
  • 1 ≤ k ≤ 2n - 1
  • k is guaranteed to be valid for the given n
Asked in
Google 12 Microsoft 8 Amazon 6 Meta 4
29.0K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen