K-th Symbol in Grammar - Problem
The K-th Symbol in Grammar is a fascinating recursive pattern problem that explores how simple rules can generate complex sequences.

Imagine a magical grammar system that starts with a single 0 in the first row. Each subsequent row is generated by applying these transformation rules to the previous row:
• Replace every 0 with 01
• Replace every 1 with 10

This creates an expanding pattern:
• Row 1: 0
• Row 2: 01
• Row 3: 0110
• Row 4: 01101001

Your task: Given integers n and k, find the k-th symbol (1-indexed) in the n-th row without generating the entire string. Can you discover the mathematical pattern hidden within this seemingly chaotic expansion?

Input & Output

example_1.py — Simple Case
$ Input: n = 1, k = 1
Output: 0
💡 Note: Row 1 contains only '0', so the 1st symbol is 0
example_2.py — Second Row
$ Input: n = 2, k = 1
Output: 0
💡 Note: Row 2 is '01', so the 1st symbol is 0
example_3.py — Larger Example
$ Input: n = 4, k = 5
Output: 1
💡 Note: Row 4 is '01101001', so the 5th symbol is 1

Constraints

  • 1 ≤ n ≤ 30
  • 1 ≤ k ≤ 2n-1
  • Note: The n-th row has exactly 2n-1 symbols

Visualization

Tap to expand
Grammar Tree: Recursive Structure0Row 101Row 20110Row 3🌟 Recursive Relationship• Left subtree: Same as parent's pattern• Right subtree: Complement of parent's pattern🎯 Algorithm Steps1. If n=1, return 02. Calculate half-length = 2^(n-2)3. If k ≤ half-length: recurse on left half4. Else: recurse on right half and flip result
Understanding the Visualization
1
Root Level
Start with '0' at the root (Row 1)
2
First Expansion
0 becomes 01 (Row 2)
3
Pattern Recognition
Each level doubles and shows the complement pattern
4
Path Tracing
Find the k-th position by tracing the tree path
Key Takeaway
🎯 Key Insight: The grammar follows a recursive binary tree structure where each level doubles in size, and the right half is always the complement of the left half. This allows us to solve the problem in O(n) time without generating the exponentially large strings.
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
73.9K Views
Medium Frequency
~15 min Avg. Time
1.8K 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