Check If a String Contains All Binary Codes of Size K Problem
Description
LeetCode Problem 1461.
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 1:
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.
Example 2:
Input: s = "0110", k = 1
Output: true
Explanation: The binary codes of length 1 are "0" and "1", it is clear that both exist as a substring.
Example 3:
Input: s = "0110", k = 2
Output: false
Explanation: The binary code "00" is of length 2 and does not exist in the array.
Constraints:
1 <= s.length <= 5 * 10^5s[i]is either'0'or'1'.1 <= k <= 20
Solution
Approach: Rolling Bitmask over Every Window
There are 2k binary codes of length k, and s has only len(s) - k + 1 substrings of that length. If there are fewer windows than codes, some code must be missing, so we can return false right away. This quick check also covers k = 19 and k = 20, which would need a string longer than the limit.
Otherwise, read each window as a k-bit number. Sliding one step to the right is cheap: shift the number left by one, add the new bit, and keep only the low k bits with & (2^k - 1), which drops the bit that left the window. Mark each number in a boolean table of size 2k and count how many different ones we have seen. Once all 2k are marked the answer is true; if the scan ends first, it is false.
Only windows that are complete count, so we start marking at index k - 1.
Complexity: O(n) time, where n is the length of s, and O(2k) extra space for the table. Storing the substrings themselves in a set also works but costs O(nk).
class Solution:
def hasAllCodes(self, s: str, k: int) -> bool:
total = 1 << k
if len(s) - k + 1 < total:
return False # not enough windows to hold every code
mask = total - 1
seen = [False] * total
missing = total
code = 0
for i, ch in enumerate(s):
code = ((code << 1) | (ord(ch) - 48)) & mask # keep only the last k bits
if i >= k - 1 and not seen[code]:
seen[code] = True
missing -= 1
if missing == 0:
return True
return False