K-th Symbol in Grammar
MediumUpdated: Aug 2, 2025
Practice on:
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, the1strow is0, the2ndrow is01, and the3rdrow is0110.
Given two integer n and k, return the kth (1-indexed) symbol in the
nth row of a table of n rows.
Examples
Example 1
Input: n = 1, k = 1
Output: 0
Explanation: row 1: _0_
Example 2
Input: n = 2, k = 1
Output: 0
Explanation:
row 1: 0
row 2: _0_ 1
Example 3
Input: n = 2, k = 2
Output: 1
Explanation:
row 1: 0
row 2: 0 _1_
Constraints
1 <= n <= 301 <= k <= 2n - 1
Solution
Method 1 – Recursion Based on Parent Symbol
Intuition
The k-th symbol in the n-th row depends on its parent in the previous row. Each 0 generates 01, and each 1 generates 10. The left child is always the same as the parent, the right child is the flipped parent. This leads to a recursive solution.
Approach
- If n == 1, return 0 (base case).
- Find the parent position: parent = (k+1)//2 if 1-indexed.
- Recursively get the parent's value.
- If k is odd (left child), return parent value. If even (right child), return flipped parent value (1 - parent).
Code
C++
class Solution {
public:
int kthGrammar(int n, int k) {
if (n == 1) return 0;
int parent = kthGrammar(n-1, (k+1)/2);
if (k % 2 == 1) return parent;
return 1 - parent;
}
};
Go
func kthGrammar(n int, k int) int {
if n == 1 { return 0 }
parent := kthGrammar(n-1, (k+1)/2)
if k%2 == 1 { return parent }
return 1 - parent
}
Java
class Solution {
public int kthGrammar(int n, int k) {
if (n == 1) return 0;
int parent = kthGrammar(n-1, (k+1)/2);
return k % 2 == 1 ? parent : 1 - parent;
}
}
Kotlin
class Solution {
fun kthGrammar(n: Int, k: Int): Int {
if (n == 1) return 0
val parent = kthGrammar(n-1, (k+1)/2)
return if (k % 2 == 1) parent else 1 - parent
}
}
Python
class Solution:
def kthGrammar(self, n: int, k: int) -> int:
if n == 1:
return 0
parent = self.kthGrammar(n-1, (k+1)//2)
return parent if k % 2 == 1 else 1 - parent
Rust
impl Solution {
pub fn kth_grammar(n: i32, k: i32) -> i32 {
if n == 1 { return 0; }
let parent = Solution::kth_grammar(n-1, (k+1)/2);
if k % 2 == 1 { parent } else { 1 - parent }
}
}
TypeScript
class Solution {
kthGrammar(n: number, k: number): number {
if (n === 1) return 0;
const parent = this.kthGrammar(n-1, Math.floor((k+1)/2));
return k % 2 === 1 ? parent : 1 - parent;
}
}
Complexity
- ⏰ Time complexity:
O(n), as the recursion depth is n. - 🧺 Space complexity:
O(n), due to the recursion stack.