Find Kth Bit in Nth Binary String Problem
Description
LeetCode Problem 1545.
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)))fori > 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= "0**1**1"S_3= "011**1**001"S_4 = "0111001**1**0110001"
Return the k^th bit in S_n. It is guaranteed that k is valid for the given n.
Example 1:
Input: n = 3, k = 1
Output: "0"
Explanation: S_3 is "0111001".
The 1^st bit is "0".
Example 2:
Input: n = 4, k = 11
Output: "1"
Explanation: S_4 is "011100110110001".
The 11^th bit is "1".
Constraints:
1 <= n <= 201 <= k <= 2^n - 1
Solution
Approach: Walk Down Through the Halves
S_n has length 2^n - 1 and is made of three parts: S_(n-1) on the left, a "1" in the middle at position mid = 2^(n-1), and reverse(invert(S_(n-1))) on the right. With n = 20 the string has about a million bits, so instead of building it we follow position k down.
- If
k == mid, the bit is1. - If
k < mid, the bit is bitkofS_(n-1). - If
k > mid, the right half isS_(n-1)reversed, so positionkmirrors to position2^n - kofS_(n-1), with the bit inverted.
Repeat with n - 1, counting how many times we went through an inversion (only its parity matters). When we reach S_1 = "0", or hit a middle "1" earlier, the answer is that bit, inverted once for every inversion we passed.
For example, n = 4, k = 11: mid = 8, so k mirrors to 16 - 11 = 5 with one inversion. In S_3, mid = 4, so 5 mirrors to 8 - 5 = 3 with a second inversion. In S_2, mid = 2, so 3 mirrors to 4 - 3 = 1 with a third. That is bit 1 of S_1, a 0, inverted three times: "1".
Complexity: O(n) time and O(1) extra space.
class Solution:
def findKthBit(self, n: int, k: int) -> str:
flipped = 0 # how many times we passed through invert(), mod 2
# S_n = S_(n-1) + "1" + reverse(invert(S_(n-1))), with the "1" at position 2^(n-1).
while n > 1:
mid = 1 << (n - 1)
if k == mid:
return str(1 ^ flipped)
if k > mid:
k = 2 * mid - k # mirror into the left half, and invert
flipped ^= 1
n -= 1
return str(flipped) # S_1 = "0"