779. K-th Symbol in Grammar
We build a table of n rows (1-indexed). We start by writing 0 in the 1 s t 1^{st} 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 1 s t 1^{st} 1st row is 0, the 2 n d 2^{nd} 2nd row is 01, and the 3 r d 3^{rd} 3rd row is 0110.
Given two integer n and k, return the
k
t
h
k^{th}
kth (1-indexed) symbol in the
n
t
h
n^{th}
nth row of a table of n rows.
Example 1:
Input: n = 1, k = 1
Output: 0
Explanation: r o w 1 : 0 ‾ row 1: \underline{0} row1:0
Example 2:
Input: n = 2, k = 1
Output: 0
Explanation:
row 1: 0
r o w 2 : 0 ‾ 1 row 2: \underline{0}1 row2:01
Example 3:
Input: n = 2, k = 2
Output: 1
Explanation:
row 1: 0
r o w 2 : 0 1 ‾ row 2: 0\underline{1} row2:01
Constraints:
- 1 <= n <= 30
- 1 < = k < = 2 n − 1 1 <= k <= 2^{n - 1} 1<=k<=2n−1
From: LeetCode
Link: 779. K-th Symbol in Grammar
Solution:
Ideas:
-
Each row is generated by transforming the previous row:
- 0 → 01, 1 → 10
-
This means:
- The first half of the row is the same as the previous row.
- The second half is the flipped version.
-
mid = 2^(n-2) represents the size of the first half.
-
Recursively:
- If k is in the first half → same value as previous row.
- If k is in the second half → flipped value of corresponding position in previous row.
Code:
int kthGrammar(int n, int k) {
if (n == 1) return 0;
int mid = 1 << (n - 2); // 2^(n-2), the midpoint of the row
if (k <= mid)
return kthGrammar(n - 1, k); // Left half: same as in previous row
else
return 1 - kthGrammar(n - 1, k - mid); // Right half: flipped value
}