K-th Symbol in Grammar - 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.
For example, for n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110.
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
Example 1 — Basic Case
$
Input:
n = 1, k = 1
›
Output:
0
💡 Note:
Row 1 contains only "0", so the 1st symbol is 0
Example 2 — Second Row
$
Input:
n = 2, k = 1
›
Output:
0
💡 Note:
Row 2 is "01" (from "0" → "01"), so the 1st symbol is 0
Example 3 — Fourth Row
$
Input:
n = 4, k = 5
›
Output:
1
💡 Note:
Row 4 is "01101001" (0→01, 1→10, 1→10, 0→01), so the 5th symbol is 1
Constraints
- 1 ≤ n ≤ 30
- 1 ≤ k ≤ 2n-1
Visualization
Tap to expand
Understanding the Visualization
1
Input
Given row number n and position k
2
Process
Build grammar table using 0→01, 1→10 rule
3
Output
Return the k-th symbol in row n
Key Takeaway
🎯 Key Insight: The grammar forms a binary tree where each node's children follow the pattern 0→(0,1) and 1→(1,0)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code