The problem is described as follows:
We build a table of n rows (1-indexed). We start with 0 in the 1st row. From the 2nd row onwards, every row is formed based on the previous row using the following rules:
0 becomes 011 becomes 10Given two integers n and k, return the k-th (1-indexed) symbol in the n-th row of the table.
n? (This affects the computational feasibility)k?n=1 or k=1?To solve this problem, we need to understand the relationship between the rows:
0.0 in the 1st row, resulting in 01.0 with 01 and every 1 with 10 from the 2nd row, resulting in 0110, and so on.Observations:
Instead of generating the massive table, we can find a recursive pattern:
(k+1)//2 in (n-1)th row would be.The key insight is to identify the inverse process:
k is in the first half of the nth row, the answer will be the same as the (n-1)th row.k is in the second half of the nth row, the answer will be the inverse of what it would have been in the (n-1)th row.Here is the Python code to solve the problem:
def kthGrammar(n: int, k: int) -> int:
if n == 1:
return 0
if k % 2 == 0:
return 1 - kthGrammar(n - 1, k // 2)
else:
return kthGrammar(n - 1, (k + 1) // 2)
# Example usage
print(kthGrammar(4, 5)) # Output: 1
print(kthGrammar(2, 2)) # Output: 1
n = 1, where the value is always 0.k is an even or odd number:
k is even, we recursively call the function with k/2 in n-1 and invert the result.k is odd, we recursively call the function with (k+1)//2 in n-1.The time complexity is O(n) because we are making a single recursive call that goes all the way up to 1 recursively. Each call reduces n by 1, so the depth of the recursion is n, leading to a linear time complexity.
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?