π One-stop destination for all your technical interview Preparation π
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.
!(k-mid)
,because previous row is half of current row and 2nd half of current row is complement of first row.int kthGrammar(int n, int k)
{
if (n == 1 && k == 1)
return 0;
int mid = pow(2, n - 1) / 2; // middle of the current row
if (k <= mid)
return kthGrammar(n - 1, k);
else
return !kthGrammar(n - 1, k - mid);
}