The problem is from LeetCode and states:
We build a table of n
rows (1-indexed). We start by writing 0
in the 1
st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0
with 01
, and each occurrence of 0
with 10
. Given two integers n
and k
, return the k
-th indexed symbol in the n
-th row. (The value of k is 1-indexed.)
n = 1
, k = 1
0
n = 2
, k = 1
0
n = 2
, k = 2
1
0
, it turns into 01
in the next row.1
, it turns into 10
in the next row.k
is odd, look at the left (first half of the row).k
is even, look at the right (second half of the row).By analyzing further, we can come to the conclusion:
k
in the n
-th row is determined by ceil(k/2)
in the (n-1)
-th row.k
is odd or even.Here is a C++ implementation of the solution:
class Solution {
public:
int kthGrammar(int n, int k) {
// Base case
if (n == 1) return 0;
// Determine the length of the previous row
int length_of_prev_row = 1 << (n - 2); // 2^(n-2)
if (k <= length_of_prev_row) {
// The first half of the row
return kthGrammar(n - 1, k);
} else {
// The second half of the row
return !kthGrammar(n - 1, k - length_of_prev_row);
}
}
};
The time complexity for this recursive approach:
The space complexity is also (O(n)) due to the recursion stack.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?