MediumNo. 0779

K-th Symbol in Grammar — LeetCode 779 Python Solution

Topics
Bit Manipulation, Recursion, Math
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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
0231Power of TwoEasy
0342Power of FourEasy
0782Transform to ChessboardHard
0029Divide Two IntegersMedium
0067Add BinaryEasy
0371Sum of Two IntegersMedium

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.

Free to download. Check it runs on your machine, then pick a plan.