Skip to content

Commit

Permalink
"K-th Symbol in Grammar" solution
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Oct 25, 2023
1 parent a8d030f commit cf8f179
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/k_th_symbol_in_grammar.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class Solution:
def kthGrammar(self, n: int, k: int) -> int:
total = 2 ** (n - 1)
current = 0

while k > 2:
half = total // 2

if k > half:
k -= half
current = 0 if current else 1
else:
current = 1 if current else 0

total = half

if current:
return 1 if k == 1 else 0
else:
return 1 if k == 2 else 0
16 changes: 16 additions & 0 deletions tests/test_k_th_symbol_in_grammar.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import pytest

from src.k_th_symbol_in_grammar import Solution


@pytest.mark.parametrize(
"n,k,expected",
(
(1, 1, 0),
(2, 1, 0),
(2, 2, 1),
(3, 3, 1),
),
)
def test_solution(n, k, expected):
assert Solution().kthGrammar(n, k) == expected

0 comments on commit cf8f179

Please sign in to comment.