Skip to content
Problem 779 · LeetCode 779(opens in a new tab)

K-th Symbol in Grammar

MediumBit manipulation

Build rows of 0s and 1s. Row 1 is the single symbol 0. Each later row comes from the one above it: every 0 becomes 01 and every 1 becomes 10. So row 2 is 01, row 3 is 0110, and row 4 is 01101001.

Given n and k, return the k-th symbol of row n, counting from 1.

Example 1

Input:  n = 4, k = 6
Output: 0
Why:    row 4 is 01101001 and its 6th symbol is 0
2 more examples and the constraints

Example 2

Input:  n = 3, k = 3
Output: 1
Why:    row 3 is 0110 and its 3rd symbol is 1

Example 3

Input:  n = 5, k = 1
Output: 0
Why:    every row starts with 0

Constraints

  • 1 ≤ n ≤ 30
  • 1 ≤ k ≤ 2ⁿ⁻¹

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Recurse to the parentO(n)
  2. Count the 1 bits of k − 1O(log k)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 30Verdict
Recurse to the parentO(n)
Fine; 30 calls deep
Count the 1 bits of k − 1O(log k)
Best; a short loop, no stack

n = row number; k = position in the row.

Edge cases to test

  • n = 1. The only symbol is 0.
  • k = 1. The first symbol of every row is 0: k − 1 has no 1 bits.
  • Last symbol of a row. k = 2ⁿ⁻¹ gives k − 1 with n − 1 ones, so the answer is (n − 1) mod 2.
  • n = 30. Row 30 has 536,870,912 symbols; building it would run out of time and memory.

Common mistakes

  • Building the rows as strings, which doubles the work and memory every row.
  • Using k instead of k − 1 when counting bits: the positions must start at 0.
  • Getting the parent wrong: it is (k + 1) / 2 for 1-based k, not k / 2.

How to talk through it

  1. 1Clarify. Is k 1-based? Is it always inside row n? (Yes to both.)
  2. 2Reject building rows. Row 30 has half a billion symbols, so work on positions instead.
  3. 3Find the parent. Position k came from (k + 1) / 2 one row up: odd k copies, even k flips.
  4. 4Turn it into bits. With 0-based positions each right child is a 1 bit, so count 1 bits of k − 1.
  5. 5Test out loud. Check n = 4: k = 6 gives 0 and k = 8 gives 1, matching 01101001.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?