K-th Symbol in Grammar Medium 0 attempts
LeetCode ↗

K-th Symbol in Grammar

Medium BacktrackingRecursion LeetCode

We build a table of n rows (1-indexed). We start with 0 in the 1st row. In every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10. Given integers n and k, return the kth (1-indexed) symbol in the nth row.

Sample Input
n = 2, k = 1
Sample Output
0
Constraints
  • 1 <= n <= 30
  • 1 <= k <= 2^(n-1)
Test Cases
Case 1
Args: [2,1] Expected: 0

The first half of row n mirrors row n-1, and the second half is its complement. If k is in the first half, recurse with the same k. If k is in the second half, recurse with k minus the half-size and flip the result.

function kthGrammar(n, k) {
  if (n === 1) return 0;
  const half = Math.pow(2, n - 2);
  if (k <= half) {
    return kthGrammar(n - 1, k);
  } else {
    return kthGrammar(n - 1, k - half) ^ 1;
  }
}

Time: O(n) Space: O(n) for recursion stack

Saved in this browser only. Private to you.

JavaScript