#779
K-th Symbol in Grammar
MediumMathBit ManipulationRecursionRecursionBit Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of generating all rows, we can determine the k-th symbol directly using properties of binary representation. The k-th symbol can be derived from the previous row based on the parity of the number of flips.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the position of the k-th symbol in the previous row using the formula: prevK = (k + 1) / 2.
- 2Step 2: Check if the number of flips (n - 1) is even or odd to determine the symbol.
- 3Step 3: If n is odd, return '0' if prevK is even, else return '1'. If n is even, return '1' if prevK is even, else return '0'.
solution.py6 lines
1def kthGrammar(n, k):
2 if n == 1:
3 return 0
4 if k % 2 == 0:
5 return 1 if kthGrammar(n - 1, k // 2) == 0 else 0
6 return kthGrammar(n - 1, (k + 1) // 2)ℹ
Complexity note: The time complexity is O(n) since we make n recursive calls, but we do not store any intermediate results. The space complexity is O(1) as we only use a constant amount of space.
- 1The sequence grows exponentially, so generating all rows is inefficient.
- 2The k-th symbol can be derived recursively without generating the entire sequence.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.