LeetCode 779: K-th Symbol in Grammar Solution

Master LeetCode problem 779 (K-th Symbol in Grammar), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

779. K-th Symbol in Grammar

Problem Explanation

Explanation

To solve this problem, we can observe that for each row, the first half of the row is the same as the previous row, and the second half is the complement of the previous row. This allows us to recursively determine the value of the k-th symbol by looking at the parent row and adjusting the index based on whether k is in the first half or the second half of the row.

Algorithm

  1. If n = 1, return 0 since the first row is always 0.
  2. Recursively find the value of the parent row at position (k+1)/2.
  3. If k is in the first half of the row, return the value from the parent row.
  4. If k is in the second half of the row, return the complement of the value from the parent row.

Time Complexity

The time complexity of this algorithm is O(log n) as we are recursively reducing the problem size by half.

Space Complexity

The space complexity is also O(log n) due to the recursion stack space.

Solution Code

class Solution {
    public int kthGrammar(int n, int k) {
        if (n == 1) {
            return 0;
        }
        
        int parent = kthGrammar(n-1, (k+1)/2);
        
        if (k % 2 == 0) {
            return 1 - parent;
        } else {
            return parent;
        }
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 779 (K-th Symbol in Grammar)?

This page provides optimized solutions for LeetCode problem 779 (K-th Symbol in Grammar) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 779 (K-th Symbol in Grammar)?

The time complexity for LeetCode 779 (K-th Symbol in Grammar) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 779 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 779 in Java, C++, or Python.

Back to LeetCode Solutions