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
K-th Symbol in Grammar: Find Symbol at Position k in Row nRow 1:0Row 2:01Row 3:0110Row 4:01101001k=5Transformation Rules:0 → 011 → 10For n=4, k=5:Answer = 1Each row doubles in length: Row n has 2^(n-1) symbolsGoal: Find k-th symbol efficiently without building entire row
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)
Asked in
Google 15 Facebook 12 Amazon 8
32.0K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen