K-th Symbol in Grammar (LeetCode 779): Solution and Explanation

Medium
Math
Bit Manipulation
Recursion

Row 1 is "0" and each next row replaces 0 with "01" and 1 with "10". Given n and k, return the k-th symbol of row n without building the row.

Intuition

Row n has 2^(n-1) symbols, over half a billion for n = 30, so building it is out of the question. We need to find one symbol without the rest.

Each symbol in a row produces exactly two symbols in the next row. That makes the table a complete binary tree: the symbol at position p has children at 2p - 1 and 2p, and the symbol at position k has its parent at (k + 1) / 2.

The replacement rule says the left child (0 -> 0, 1 -> 1) copies its parent and the right child (0 -> 1, 1 -> 0) flips it. An odd position is a left child; an even position is a right child.

So the target is just the root 0 flipped once for every right child on the path from the root down to it. Climb from k to the root, count the even positions, and return the parity of that count.

Approach: Climb to the root and count flips

  1. Set flips = 0.
  2. While n > 1: if k is even, the current node is a right child, so toggle flips.
  3. Move to the parent: k = (k + 1) // 2 and n -= 1.
  4. At row 1 the symbol is 0, so the answer is flips.

Step-by-step example

n = 4, k = 6
  1. Row 4, position 6 is even: a right child, flips = 1. Parent is (6 + 1) / 2 = 3 in row 3.
  2. Row 3, position 3 is odd: a left child, no flip. Parent is 2 in row 2.
  3. Row 2, position 2 is even: a right child, flips = 0. Parent is 1 in row 1.
  4. Row 1 reached. The root 0 was flipped twice, so the answer is 0. Check: row 4 is 01101001 and its 6th symbol is 0.

Code: Python, Java, C++

1class Solution:
2    def kthGrammar(self, n: int, k: int) -> int:
3        flips = 0
4        while n > 1:
5            if k % 2 == 0:
6                flips ^= 1
7            k = (k + 1) // 2
8            n -= 1
9        return flips
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Bit count of k - 1 O(log k)
Climb to the root and count flips O(n)
Recursion on the parent O(n)
Build the rows O(2^n)
Time

O(n)

Each loop iteration moves up one row, and there are n - 1 rows above the target.

Space

O(1)

Only k, n and the flip counter are kept.

Other approaches

Recursion on the parent (time O(n), space O(n))

kthGrammar(n, k) = kthGrammar(n - 1, (k + 1) / 2) when k is odd, and 1 minus it when k is even. Same idea, but uses O(n) stack.

Bit count of k - 1 (time O(log k), space O(1))

Written in binary, k - 1 has a 1 exactly at each level where the path goes right, so the answer is popcount(k - 1) mod 2. A one-liner, but it hides why it works.

Build the rows (time O(2^n), space O(2^n))

Generate every row as a string and index into the last one. Correct for small n, but row 30 has 2^29 symbols.

Common mistakes

  • Using k / 2 instead of (k + 1) / 2 for the parent with 1-indexed positions, which sends odd positions to the wrong parent.
  • Mixing up which child flips. The left child (odd k) copies; the right child (even k) flips.
  • Building the actual rows, which runs out of memory long before n = 30.
  • Forgetting that n = 1 has no loop iterations and must return 0.

Frequently asked questions

Why does the parity of set bits in k - 1 give the answer?

With 0-indexed position k - 1, each bit from the top says whether the path goes left (0) or right (1) at that level. Every right step flips the symbol, so the answer is the number of 1 bits mod 2.

Is this sequence known?

Yes. Row n is a prefix of the Thue-Morse sequence, where the i-th term is the parity of the number of 1 bits in i.

Does n matter beyond bounding k?

Not for the answer. Every row is a prefix of the next, so the k-th symbol is the same in every row long enough to contain it. n only sets how many times the loop runs.