779. K-th Symbol in Grammar

Problem Statement

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.

Example 1:

Input: n = 1, k = 1
Output: 0
Explanation: row 1: 0

Example 2:

Input: n = 2, k = 1
Output: 0
Explanation: 
row 1: 0
row 2: 01

Example 3:

Input: n = 2, k = 2
Output: 1
Explanation: 
row 1: 0
row 2: 01

Constraints:

  • 1 <= n <= 30

  • 1 <= k <= 2n - 1

Intuition

Approach:
1->0
2->0|1
3->01|10
4->0110|1001

See that bits are flipped, after some time

Try recursion to find that 

https://leetcode.com/problems/k-th-symbol-in-grammar/

Approach 1:

C++
class Solution {
public:
    unordered_map<string,int> mp;
    int find_ans(int n, int k){
        if(n == 1 and k == 1)
            return 0;
        
        string key = to_string(n) + "_" + to_string(k);
        if(mp.find(key) != mp.end())
            return mp[key];

        int dist = pow(2,n-2) + 1;

        if(k < dist)
            return mp[key] = find_ans(n-1, k);
        
        return mp[key] = 1 ^ find_ans(n, k-dist+1);
    }

    int kthGrammar(int n, int k) {
        int ans = find_ans(n, k);
        for(auto &it: mp){
            cout<<it.first <<" "<<it.second;
            cout<<endl;
        }
        return ans;
    }
};

Approach 2:

C++

Approach 3:

C++

Approach 4:

C++

Similar Problems

Last updated