K-th Symbol in Grammar — LeetCode 779 Python Solution

MediumBit ManipulationRecursionMath
Problem
#779
Reading time
2 min

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))) ^ 1

Complexity

MeasureComplexity
TimeO(n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview