K-th Symbol in Grammar — LeetCode 779 Python Solution
MediumBit ManipulationRecursionMath
- Problem
- #779
- Pattern
- Bit Manipulation
- Reading time
- 2 min
- Source
- leetcode.com
The problem
We build a table of n rows (1-indexed). We start by writing 0 in the 1st row.
Example
- Input
- n = 1, k = 1
- Output
- 0
- Explanation
- row 1: 0
Python solution
Python
class Solution:
def kthGrammar(self, n: int, k: int) -> int:
if n == 1:
return 0
if k <= (1 << (n - 2)):
return self.kthGrammar(n - 1, k)
return self.kthGrammar(n - 1, k - (1 << (n - 2))) ^ 1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 779. K-th Symbol in Grammar is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 779. K-th Symbol in Grammar?
- LeetCode 779. K-th Symbol in Grammar is rated Medium on LeetCode.
- What is the time complexity of LeetCode 779. K-th Symbol in Grammar?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 779. K-th Symbol in Grammar?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 779. K-th Symbol in Grammar cover?
- LeetCode 779. K-th Symbol in Grammar is tagged Bit Manipulation, Recursion and Math on LeetCode.