Leetcode #1545: Find Kth Bit in Nth Binary String
In this guide, we solve Leetcode #1545 Find Kth Bit in Nth Binary String in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given two positive integers n and k, the binary string Sn is formed as follows: S1 = "0" Si = Si - 1 + "1" + reverse(invert(Si - 1)) for i > 1 Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0). For example, the first four strings in the above sequence are: S1 = "0" S2 = "011" S3 = "0111001" S4 = "011100110110001" Return the kth bit in Sn.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Recursion, String, Simulation
Intuition
We need to scan characters while tracking positions or counts.
A simple state machine keeps the logic precise.
Approach
Iterate through the string once and update the state for each character.
Use a map or array if you need fast lookups.
Steps:
- Iterate through characters.
- Maintain necessary state.
- Build or validate the output.
Example
Input: n = 3, k = 1
Output: "0"
Explanation: S3 is "0111001".
The 1st bit is "0".
Python Solution
class Solution:
def findKthBit(self, n: int, k: int) -> str:
def dfs(n: int, k: int) -> int:
if k == 1:
return 0
if (k & (k - 1)) == 0:
return 1
m = 1 << n
if k * 2 < m - 1:
return dfs(n - 1, k)
return dfs(n - 1, m - k) ^ 1
return str(dfs(n, k))
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.