Suppose on the first row, we have a 0. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 by 01, and each occurrence of 1 by 10. Suppose we have N rows and index K, we have to find the K-th indexed symbol in row N. (The values of K are 1-indexed.) (1 indexed). So if N = 4 and K = 5, then the output will be 1. This is because −
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int kthGrammar(int N, int K) { if(N == 1) return 0; if(K % 2 == 0){ return kthGrammar(N - 1, K / 2) == 0 ? 1 : 0; }else{ return kthGrammar(N - 1, (K + 1) / 2); } } }; main(){ Solution ob; cout << (ob.kthGrammar(4, 5)); }
4 5
1