Sponsored
Sponsored
This approach utilizes the recursive nature of the transformation of each row. We start from the nth row and trace back to see which position in the previous level gives us the current k-th position.
Time Complexity: O(n), as each recursive call reduces the problem size by a constant factor.
Space Complexity: O(n), due to the recursion stack.
1using System;
2
3class KthSymbol {
4 public int KthGrammar(int n, int k) {
5 if (n == 1) return 0;
6 int mid = 1 << (n - 2);
7 if (k <= mid) {
8 return KthGrammar(n - 1, k);
9 } else {
10 return 1 - KthGrammar(n - 1, k - mid);
11 }
12 }
13
14 static void Main() {
15 KthSymbol symbol = new KthSymbol();
16 Console.WriteLine(symbol.KthGrammar(3, 2)); // Output: 1
17 }
18}
The recursive method KthGrammar
checks if the position k lies in the first or second half. It leverages the characteristic of binary tree depth to recursively find the value.
The iterative approach to solve this problem is based on tracing the path from the kth element in the nth row back to the root (1st element of the 1st row). Depending on whether k
is odd or even, we determine whether to toggle the current result bit as we move up levels until we arrive at the base case.
Time Complexity: O(n).
Space Complexity: O(1), as no additional space is used outside of constant variables.
1
This implementation initializes a variable result
to 0 as we start tracing from the bottom. For each level, based on whether k
is odd or even, we might toggle the bit stored in result
. We keep shifting k
up till it equals 1.