Find Kth Bit in Nth Binary String

Binary strings are built as S1 = "0" and Si = S(i-1) + "1" + reverse(invert(S(i-1))) for i > 1, where invert flips every bit. Given n and k, return the kth bit (1-indexed) of Sn. For example S2 = "011", S3 = "0111001", S4 = "011100110110001".

30:00

Find Kth Bit in Nth Binary String
medium
Free written solution
Topics
Companies

Binary strings are built as S1 = "0" and Si = S(i-1) + "1" + reverse(invert(S(i-1))) for i > 1, where invert flips every bit. Given n and k, return the kth bit (1-indexed) of Sn. For example S2 = "011", S3 = "0111001", S4 = "011100110110001".

Example 1:
Input: {"n":3,"k":1}
Output: 0
Constraints:
  • 1≤n≤201 \leq n \leq 20

  • 1≤k≤2n−11 \leq k \leq 2^n - 1

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":3,"k":1}

S3 has 2^3 - 1 = 7 bits. Instead of building it, walk k down through smaller strings, remembering whether the bit got inverted.

S3, length 7

0111001S2reverse(invert(S2))k=1
flip = false

no net inversion so far

descent from S3

S3

k=1

Variables
VariableValue
length7
k1
flipfalse
DepthFunction Call
Stack empty
0/3