The K-th Symbol in Grammar problem can be formulated as follows:
We build a table of n rows (1-indexed). We start by writing “0” in the 1st row. Then, 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”.
Input: n = 1, k = 1 Output: 0
Input: n = 2, k = 1 Output: 0
Input: n = 2, k = 2 Output: 1
To solve the problem, observe the properties of the sequence:
Key Observations:
ceil(k / 2)
in row n-1
.k
is odd, it can either be “0” or “1”.k
is even, it can either be “1” or “0”.public class KthSymbolInGrammar {
public int kthGrammar(int n, int k) {
if (n == 1) {
return 0; // Base case: The first row is always "0"
}
int parent = kthGrammar(n - 1, (k + 1) / 2); // Recursively find the parent symbol
boolean isKEven = k % 2 == 0;
// If parent is 0: "0" -> "01", If parent is 1: "1" -> "10"
if (parent == 0) {
return isKEven ? 1 : 0;
} else {
return isKEven ? 0 : 1;
}
}
public static void main(String[] args) {
KthSymbolInGrammar solver = new KthSymbolInGrammar();
System.out.println(solver.kthGrammar(1, 1)); // Output: 0
System.out.println(solver.kthGrammar(2, 1)); // Output: 0
System.out.println(solver.kthGrammar(2, 2)); // Output: 1
// Further testing can be done here
}
}
The time complexity of this recursive solution can be analyzed as:
n
to 1.n
.Thus, the time complexity is:
[ O(n) ]
This solution is efficient given the constraints (1 <= n <= 30).
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?