Skip to content

Commit eb13076

Browse files
authored
Create check-if-a-string-contains-all-binary-codes-of-size-k.py
1 parent aa78139 commit eb13076

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Time: O(n * k)
2+
# Space: O(k * 2^k)
3+
4+
class Solution(object):
5+
def hasAllCodes(self, s, k):
6+
"""
7+
:type s: str
8+
:type k: int
9+
:rtype: bool
10+
"""
11+
return 2**k <= len(s) and len({s[i:i+k] for i in xrange(len(s)-k+1)}) == 2**k
12+
13+
14+
# Time: O(n * k)
15+
# Space: O(2^k)
16+
class Solution2(object):
17+
def hasAllCodes(self, s, k):
18+
"""
19+
:type s: str
20+
:type k: int
21+
:rtype: bool
22+
"""
23+
lookup = set()
24+
base = 2**k
25+
if base > len(s):
26+
return False
27+
num = 0
28+
for i in xrange(len(s)):
29+
num = (num << 1) + (s[i] == '1')
30+
if i >= k-1:
31+
lookup.add(num)
32+
num -= (s[i-k+1] == '1') * (base//2)
33+
return len(lookup) == base

0 commit comments

Comments
 (0)