K-th Symbol in Grammar

We build a table of n rows (1-indexed). Row 1 is "0". To build each next row, look at the previous row and replace every 0 with "01" and every 1 with "10". Given n and k, return the k-th (1-indexed) symbol in row n.

30:00

K-th Symbol in Grammar
medium
Free written solution
Topics
Companies

We build a table of n rows (1-indexed). Row 1 is "0". To build each next row, look at the previous row and replace every 0 with "01" and every 1 with "10". Given n and k, return the k-th (1-indexed) symbol in row n.

Example 1:
Input: {"n":5,"k":12}
Output: 1
Constraints:
  • 1≤n≤301 \leq n \leq 30

  • 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":5,"k":12}

Row 1 is "0", and each row replaces 0 with "01" and 1 with "10". So every symbol is the parent of two children: the left child copies it, the right child flips it. We want position 12 of row 5.

■ path to targetleft child copiesright child flipsflips = 0
01212341234567812345678910111213141516

row 5

11
12

n = 5, k = 12 · now at row 5, position 12
Variables
VariableValue
n5
k12
flips0
DepthFunction Call
Stack empty
0/14