[LeetCode] K-th Symbol in Grammar

779. K-th Symbol in Grammar

We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now 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.

  • For example, for n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110.

Given two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int kthGrammar(int n, int k) {
int len = 1<<(n-1);
bool reverse = false;
while(len != 1) {
if(k > len / 2) {
k = len - k + 1;
if(!(n & 1))
reverse = !reverse;
}
len>>=1;
n--;
}
return reverse ? 1 : 0;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/10/PS/LeetCode/k-th-symbol-in-grammar/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.