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 INPUT Grammar Table Build-up: Row 1: 0 Row 2: 0 1 Row 3: 0 1 1 0 Transformation Rules: 0 --> 01 1 --> 10 Input Values: n = 1 k = 1 Target: Row 1, Position 1 ALGORITHM STEPS 1 Base Case Check If n=1, return 0 n=1 --> return 0 [OK] 2 Recursive Approach Find parent in row n-1 parent_k = (k+1)/2 3 Position Analysis k odd: same as parent k even: flip parent 4 Compute Result For n=1, k=1: Direct base case! Pattern: Binary Tree 0 Root = Row 1 FINAL RESULT Row n=1 of Grammar Table: 0 Position k=1 OUTPUT 0 Verification: Row 1 starts with 0 Position 1 = First element Status: OK Key Insight: Each row forms a binary tree pattern. The k-th symbol in row n depends on its "parent" at position (k+1)/2 in row n-1. If k is odd, the symbol equals its parent. If k is even, the symbol is the flip (0-->1 or 1-->0) of its parent. This recursive relationship reduces the problem to O(n) time complexity without building the entire table. TutorialsPoint - K-th Symbol in Grammar | Optimal Solution
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