Skip to content

Latest commit

 

History

History

779

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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

Companies: Amazon, Bloomberg, Facebook, Adobe, Apple, Google

Related Topics:
Math, Bit Manipulation, Recursion

Hints:

  • Try to represent the current (N, K) in terms of some (N-1, prevK). What is prevK ?

Solution 1. Recursive

// OJ: https://leetcode.com/problems/k-th-symbol-in-grammar/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
    int kthGrammar(int n, int k) {
        if (n == 1) return 0;
        return k <= (1 << (n - 2)) ? kthGrammar(n - 1, k) : (1 - kthGrammar(n - 1, k - (1 << (n - 2))));
    }
};

Or

// OJ: https://leetcode.com/problems/k-th-symbol-in-grammar
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
    int kthGrammar(int n, int k) {
        if (n == 1) return 0;
        return kthGrammar(n - 1, (k + 1) / 2) == k % 2;
    }
};

Solution 2. Iterative

// OJ: https://leetcode.com/problems/k-th-symbol-in-grammar/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    int kthGrammar(int n, int k) {
        int ans = 0;
        for (; n > 1; --n) {
            if (k > (1 << (n - 2))) {
                ans = 1 - ans;
                k -= (1 << (n - 2));
            }
        }
        return ans;
    }
};

Solution 3.

// OJ: https://leetcode.com/problems/k-th-symbol-in-grammar/
// Author: github.com/lzl124631x
// Time: O(1)
// Space: O(1)
// Ref: https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/113736/PythonJavaC%2B%2B-Easy-1-line-Solution-with-detailed-explanation
class Solution {
public:
    int kthGrammar(int N, int K) {
        return __builtin_popcount(K - 1) & 1;
    }
};