> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# K-th Symbol in Grammar Python Solution

> Tested Python solution for LeetCode 779 with 14 pytest cases. Generate a practice environment with lcpy.

LeetCode 779, [Medium](/catalog/medium). Topics: [Math](/catalog/topics/math), [Bit Manipulation](/catalog/topics/bit-manipulation), [Recursion](/catalog/topics/recursion). [View on LeetCode](https://leetcode.com/problems/kth-symbol-in-grammar/description/).

Generate this problem as a practice environment: tested reference solution, 14 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 779   # by problem number
lcpy gen -s kth_symbol_in_grammar   # by problem name
```

## Problem

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.

### Examples

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

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

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

### Constraints

* 1 \<= n \<= 30
* 1 \<= k \<= 2n - 1

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/kth_symbol_in_grammar/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/kth_symbol_in_grammar/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(1)
    # Space: O(1)
    def kth_grammar(self, n: int, k: int) -> int:
        # kth symbol = parity of set bits in k - 1
        return (k - 1).bit_count() % 2
```

## Complexity

| Time | Space |
| - | - |
| O(1) | O(1) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.