aboutsummaryrefslogtreecommitdiff
path: root/kth_symbol_grammar.py
diff options
context:
space:
mode:
authorjack <[email protected]>2024-06-14 13:13:15 -0600
committerjack <[email protected]>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /kth_symbol_grammar.py
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'kth_symbol_grammar.py')
-rw-r--r--kth_symbol_grammar.py22
1 files changed, 22 insertions, 0 deletions
diff --git a/kth_symbol_grammar.py b/kth_symbol_grammar.py
new file mode 100644
index 0000000..5089c46
--- /dev/null
+++ b/kth_symbol_grammar.py
@@ -0,0 +1,22 @@
+# 779. K-th Symbol in Grammar
+
+"""
+we build a table of 'n' rows (1-indexed) we start by writing 0 in the first
+row. now in every subsequent row, we look at the previous row and replace
+each occurence of zero with '01', and each occurence of 1 with '10'. for
+example for 'n = 3', the first row is the 0, the second row is the 01, and
+the third row is 0110. given two integer 'n' and 'k', return the k'th
+(1-indexed) symbol in the n'th row of a table of 'n' rows.
+"""
+
+
+class Solution(object):
+ def kthGrammar(self, n, k):
+ return bin(k - 1).count("1") & 1
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.kthGrammar(1, 1)) # expect: 0
+ print(obj.kthGrammar(2, 1)) # expect: 0
+ print(obj.kthGrammar(2, 2)) # expect: 1