LeetCode 1545, Medium. Topics: String, Recursion, Simulation. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 18 parametrized pytest cases, and a playground notebook:
Problem
Given two positive integers n and k, the binary string S_n is formed as follows:
S_1 = "0"
S_i = S_i - 1 + "1" + reverse(invert(S_i - 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:
S_1 = "0"
S_2 = "011"
S_3 = "0111001"
S_4 = "011100110110001"
Return the k^th bit in S_n. It is guaranteed that k is valid for the given n.
Examples
Constraints
1 <= n <= 20
1 <= k <= 2^n - 1
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026