⚡Flashcard Drill➔
NeetCode #208LC-779MediumTwo Pointers
← Back to All Problems

#208 · #779 · K-th Symbol in Grammar(第 K 个语法符号)

📌 Problem Statement & Constraints

We build row 1 as 0. Row i is obtained from row i-1 by replacing each 0 with 01 and each 1 with 10. Given n and k (1-indexed), return the k-th symbol in row n. Constraints: 1 <= n <= 30, 1 <= k <= 2^(n-1).

💡 Core Algorithmic Approaches

  1. The expansion is the Thue-Morse sequence: the value at position k in row n is the parity of the number of 1 bits in k - 1.
  2. Intuition: moving from a parent position to a child position appends one bit, and each appended bit flips the value exactly when the parent index had a certain parity.
  3. So the answer is bin(k - 1).count("1") % 2 -- O(log k) time and O(1) space.
  4. A recursive alternative halves k at each level, which is the same idea expressed differently.

💻 Benchmark Python3 Implementation

class Solution:
    def kthGrammar(self, n: int, k: int) -> int:
        # Thue-Morse: the symbol is the parity of the popcount of (k - 1)
        return bin(k - 1).count("1") % 2


# Recursive formulation: halve k at each level
class Solution2:
    def kthGrammar(self, n: int, k: int) -> int:
        if n == 1:
            return 0
        parent = self.kthGrammar(n - 1, (k + 1) // 2)
        if k % 2 == 1:                 # first child keeps the parent's value
            return parent
        return 1 - parent              # second child flips it

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(log k) for the bit-count version, or O(n) for the recursion.
💾 Space Complexity
O(1) for the bit-count version, O(n) for the recursion stack.

⚠️ Interview Pitfalls & Follow-ups

  • Generating row n explicitly: it has 2^(n-1) symbols, up to 5 * 10^8 for n = 30.
  • Forgetting the 1-indexed k: the formula uses k - 1.
  • Assuming the recursion base is k == 1: the base is n == 1, where the single symbol is 0.
  • Getting the child parity backwards: the first child (odd k) keeps the parent's value and the second child flips it.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Two Pointers Problems

中文速览与面试要点

第 K 个语法符号

我们构建了一个包含 n 行(下标从 1 开始)的表。首先在第一行写上 0。接下来的每一行,将前一行中的 0 替换为 01,1 替换为 10。例如,第 1 行是 0,第 2 行是 01,第 3 行是 0110,第 4 行是 01101001。给你两个整数 n 和 k,返回第 n 行的第 k 个字符。约束:1 ≤ n ≤ 30;1 ≤ k ≤ 2^(n−1)。

核心要点

  • 规律观察 :第 k 个字符由 k − 1 的 二进制中 1 的个数 的奇偶决定——偶数个 1 则为 0,奇数个 1 则为 1。
  • 为什么 :每次从上一行继承时,若 k 落在右半部分(对应二进制的某一位为 1),字符会翻转一次。因此翻转次数恰为 k − 1 的二进制中 1 的个数。
  • 一行写法 : bin(k - 1).count("1") % 2 。
  • 等价的分治写法 :用二分不断把 k 归约到上半或下半区间,若进入下半则翻转当前值。时间 O(n)。

常见陷阱

  • 真的构造出第 n 行的字符串 :第 n 行长度为 2^(n−1) ,n = 30 时约 5 × 10^8,内存与时间都不可行。必须用规律或分治。
  • 位计数时用 k 而非 k − 1 :下标从 1 开始,因此对应的是 k − 1 的二进制表示。
  • 误以为要数 0 的个数 :数的是 1 的个数。
  • 分治写法中 mid 的计算 :必须用 (l + r) // 2 且左闭右闭区间;写成左闭右开会漏掉一个元素。

参考实现

class Solution:
    def kthGrammar(self, n: int, k: int) -> int:
        # 规律:第 k 个字符 = (k-1) 的二进制中 1 的个数的奇偶
        return bin(k - 1).count('1') % 2

# 分治写法(O(n),更易解释):
# class Solution:
#     def kthGrammar(self, n: int, k: int) -> int:
#         cur = 0                     # 第 1 行的唯一字符
#         l, r = 1, 1 << (n - 1)      # 第 n 行的下标范围
#         while l < r:
#             mid = (l + r) // 2
#             if k <= mid:            # 落在左半:字符不变
#                 r = mid
#             else:                   # 落在右半:字符翻转
#                 l = mid + 1
#                 cur ^= 1
#         return cur