Find Kth Bit in Nth Binary String (LeetCode 1545): Solution and Explanation

Medium
String
Recursion
Simulation

The strings are built as S1 = "0" and Si = S(i-1) + "1" + reverse(invert(S(i-1))). Return the kth bit of Sn without writing out all 2^n - 1 bits.

Intuition

Building Sn is possible for n = 20 (about a million characters), but the structure gives the answer directly. Every Sn has three parts: a copy of S(n-1), a middle "1", and S(n-1) reversed with every bit flipped.

If k is in the left part, the bit is the same as the kth bit of S(n-1), so the problem shrinks by one level with k unchanged.

If k is exactly in the middle, the bit is 1.

If k is in the right part, reversing means position k corresponds to position length + 1 - k of S(n-1), and inverting means that bit is flipped. So mirror k into the left half and remember one inversion. Repeat until k hits a middle or reaches position 1, which is always 0, then apply the collected inversions.

Approach: Iterative mirroring with a flip flag

  1. Set length = 2^n - 1 and flip = false.
  2. While k > 1, compute mid = length // 2 + 1.
  3. If k == mid, return '0' if flip else '1'.
  4. If k > mid, set k = length + 1 - k and toggle flip.
  5. Halve length (moving to S(i-1)) and continue.
  6. When k reaches 1 the bit is 0, so return '1' if flip else '0'.

Step-by-step example

n = 4, k = 11
  1. S4 has length 15 and its middle is position 8. k = 11 is in the right half.
  2. Mirror: k = 15 + 1 - 11 = 5, flip = true. Move to S3 (length 7).
  3. S3's middle is 4. k = 5 is in the right half: k = 7 + 1 - 5 = 3, flip = false. Move to S2 (length 3).
  4. S2's middle is 2. k = 3 is in the right half: k = 3 + 1 - 3 = 1, flip = true. Move to S1.
  5. k = 1 is the first bit, 0. flip is true, so the answer is "1".

Code: Python, Java, C++

1class Solution:
2    def findKthBit(self, n: int, k: int) -> str:
3        flip = False
4        length = (1 << n) - 1
5        while k > 1:
6            mid = length // 2 + 1
7            if k == mid:
8                return '0' if flip else '1'
9            if k > mid:
10                k = length + 1 - k
11                flip = not flip
12            length //= 2
13        return '1' if flip else '0'
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Iterative mirroring with a flip flag O(n)
Recursion O(n)
Build the string O(2^n)
Time

O(n)

Each loop iteration drops one level, and there are at most n levels.

Space

O(1)

Only k, length and the flip flag are stored.

Other approaches

Build the string (time O(2^n), space O(2^n))

Construct S1 through Sn and index into Sn. Easy to write and fine for n = 20, but it allocates about a million characters.

Recursion (time O(n), space O(n))

Write the three cases as a recursive function: left half recurses with the same k, right half recurses on the mirrored position and inverts the result. Same logic as the loop, with O(n) stack depth.

Common mistakes

  • Mirroring without inverting. The right half is both reversed and inverted, so every mirror toggles the bit.
  • Off-by-one in the mirror. With 1-based positions in a string of length L, position k pairs with L + 1 - k.
  • Returning a number or a boolean. The function returns a character, '0' or '1'.

Frequently asked questions

Why is the middle bit always 1?

The definition inserts a literal "1" between the two halves at every level, and the middle of Sn is exactly that inserted character.

Does the left half ever change between levels?

No. Sn starts with S(n-1) unchanged, so a position in the left half has the same bit in every larger string.

Why can flip be a single boolean?

Inverting twice restores the bit, so only the parity of the number of mirrors matters.