Check If a String Contains All Binary Codes of Size K — LeetCode 1461 Python Solution
MediumBit ManipulationHash TableStringHash FunctionRolling Hash
- Problem
- #1461
- Pattern
- Bit Manipulation
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a binary string s and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false.
Example
- Input
- s = "00110110", k = 2
- Output
- true
- Explanation
- The binary codes of length 2 are "00", "01", "10" and "11". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.
Python solution
Python
class Solution:
def hasAllCodes(self, s: str, k: int) -> bool:
n = len(s)
m = 1 << k
if n - k + 1 < m:
return False
ss = {s[i : i + k] for i in range(n - k + 1)}
return len(ss) == mComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times k) |
| Space | O(n) auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1461. Check If a String Contains All Binary Codes of Size K is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1461. Check If a String Contains All Binary Codes of Size K?
- LeetCode 1461. Check If a String Contains All Binary Codes of Size K is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1461. Check If a String Contains All Binary Codes of Size K?
- The Python solution on this page runs in O(n \times k).
- What is the space complexity of LeetCode 1461. Check If a String Contains All Binary Codes of Size K?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1461. Check If a String Contains All Binary Codes of Size K cover?
- LeetCode 1461. Check If a String Contains All Binary Codes of Size K is tagged Bit Manipulation, Hash Table, String, Hash Function and Rolling Hash on LeetCode.