K-th Symbol in Grammar in C++


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 −

  • Row 1: 0
  • Row 2: 01
  • Row 3: 0110
  • Row 4: 01101001

To solve this, we will follow these steps −

  • Suppose the name of the method is kthGrammar. This takes N and K.
  • if N is 1, then return 0
  • if k is even, return 1 when then kthGrammar(N – 1, K/2) is 0, otherwise 0
  • otherwise return kthGrammar(N – 1, (K + 1)/2)

Let us see the following implementation to get better understanding −

Example

 Live Demo

#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));
}

Input

4
5

Output

1

Updated on: 04-May-2020

830 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements