K-th Symbol in Grammar
Determine the k-th symbol of row n in an expanding grammar sequence by recursively tracing back to its parent symbol in the previous row.
01The problem
We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.
- Row 1:
0 - Row 2:
01 - Row 3:
0110 - Row 4:
01101001
Given two integers n and k, return the k-th (1-indexed) symbol in the n-th row of a table of n rows.
| Input | Output | Why |
|---|---|---|
n = 1, k = 1 | 0 | Row 1 is "0" |
n = 2, k = 1 | 0 | Row 2 is "01", 1st symbol is 0 |
n = 2, k = 2 | 1 | Row 2 is "01", 2nd symbol is 1 |
n = 4, k = 5 | 1 | Row 4 is "01101001", 5th symbol is 1 |
Constraints: 1 <= n <= 30, 1 <= k <= 2^(n - 1).
Loading the rest of the lesson…