KatInterview

795. K-th Symbol in Grammar

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the k-th symbol in the n-th row of a recursively defined table. The table starts with 0 in row 1. Each subsequent row is generated by replacing 0 with 01 and 1 with 10. The length of row n is 2^(n-1). For n=30, the length is 2^29, which is far too large to generate and store explicitly. This indicates that we need to find a mathematical property or a recursive relationship to solve the problem efficiently without constructing the full row.

Solution

K-th Symbol in Grammar in Python

class Solution:
    def kthGrammar(self, n: int, k: int) -> int:
        # The problem generates the Thue-Morse sequence. A key property of this
        # sequence is that the value at a 0-indexed position `i` is 1 if the
        # number of set bits (1s) in the binary representation of `i` is odd,
        # and 0 if it is even.
        # This is also known as the parity of the population count.
        #
        # Since the problem uses 1-based indexing for k, we need to find the number
        # of set bits in `k-1`.
        #
        # Example: n = 4, k = 5
        # We are interested in the 5th symbol. We use the 0-indexed position k-1 = 4.
        # The binary representation of 4 is '0b100'.
        # The number of set bits ('1's) is 1.
        # Since 1 is odd, the symbol is 1 (1 % 2 = 1).
        #
        # Example: n = 4, k = 6
        # We use k-1 = 5. Binary is '0b101'.
        # The popcount is 2.
        # Since 2 is even, the symbol is 0 (2 % 2 = 0).

        # In Python 3.10+, (k-1).bit_count() is the most efficient way.
        # For broader compatibility, bin(k-1).count('1') works well.
        # return (k - 1).bit_count() % 2
        return bin(k - 1).count('1') % 2

K-th Symbol in Grammar in Java

class Solution {
    public int kthGrammar(int n, int k) {
        // The problem generates the Thue-Morse sequence. A key property of this
        // sequence is that the value at a 0-indexed position `i` is 1 if the
        // number of set bits (1s) in the binary representation of `i` is odd,
        // and 0 if it is even.
        // This is also known as the parity of the population count.
        //
        // Since the problem uses 1-based indexing for k, we need to find the number
        // of set bits in `k-1`.
        //
        // Example: n = 4, k = 5
        // We are interested in the 5th symbol. We use the 0-indexed position k-1 = 4.
        // The binary representation of 4 is "100".
        // The number of set bits (popcount) is 1.
        // Since 1 is odd, the symbol is 1 (1 % 2 = 1).
        //
        // Example: n = 4, k = 6
        // We use k-1 = 5. Binary is "101".
        // The popcount is 2.
        // Since 2 is even, the symbol is 0 (2 % 2 = 0).

        // Integer.bitCount(x) counts the number of set bits in x.
        // We then take the result modulo 2 to check for parity (odd/even).
        return Integer.bitCount(k - 1) % 2;
    }
}

K-th Symbol in Grammar in C++

class Solution {
public:
    int kthGrammar(int n, int k) {
        // The problem generates the Thue-Morse sequence. A key property of this
        // sequence is that the value at a 0-indexed position `i` is 1 if the
        // number of set bits (1s) in the binary representation of `i` is odd,
        // and 0 if it is even.
        // This is also known as the parity of the population count.
        //
        // Since the problem uses 1-based indexing for `k`, we need to find the number
        // of set bits in `k-1`.
        //
        // Example: n = 4, k = 5
        // We are interested in the 5th symbol. We use the 0-indexed position k-1 = 4.
        // The binary representation of 4 is "100".
        // The number of set bits (popcount) is 1.
        // Since 1 is odd, the symbol is 1 (1 % 2 = 1).
        //
        // Example: n = 4, k = 6
        // We use k-1 = 5. Binary is "101".
        // The popcount is 2.
        // Since 2 is even, the symbol is 0 (2 % 2 = 0).
        
        // We use the GCC/Clang built-in function to count set bits, which is very efficient.
        // For other compilers, a manual implementation might be needed.
        return __builtin_popcount(k - 1) % 2;
    }
};

K-th Symbol in Grammar in TypeScript

function kthGrammar(n: number, k: number): number {
    // The problem generates the Thue-Morse sequence. A key property of this
    // sequence is that the value at a 0-indexed position `i` is 1 if the
    // number of set bits (1s) in the binary representation of `i` is odd,
    // and 0 if it is even.
    // This is also known as the parity of the population count.
    //
    // Since the problem uses 1-based indexing for k, we need to find the number
    // of set bits in `k-1`.
    //
    // Example: n = 4, k = 5
    // We are interested in the 5th symbol. We use the 0-indexed position k-1 = 4.
    // The binary representation of 4 is `100`.
    // The number of set bits (popcount) is 1.
    // Since 1 is odd, the symbol is 1 (1 % 2 = 1).
    //
    // Example: n = 4, k = 6
    // We use k-1 = 5. Binary is `101`.
    // The popcount is 2.
    // Since 2 is even, the symbol is 0 (2 % 2 = 0).

    // We need to calculate the popcount of `k-1`.
    let num = k - 1;
    let popcount = 0;
    while (num > 0) {
        // Brian Kernighan's algorithm to count set bits:
        // num & (num - 1) clears the least significant set bit.
        // The loop runs exactly as many times as there are set bits.
        num &= (num - 1);
        popcount++;
    }
    
    // The result is the parity of the popcount.
    return popcount % 2;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.