Problem
Given a binary strings and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false.
Examples
Constraints
1 <= s.length <= 5 * 10^5s[i]is either'0'or'1'.1 <= k <= 20
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 1461 with 25 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 1461 # by problem number
lcpy gen -s check_if_a_string_contains_all_binary_codes_of_size_k # by problem name
s and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false.
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.
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.
Input: s = "0110", k = 2
Output: false
Explanation: The binary code "00" is of length 2 and does not exist in the array.
1 <= s.length <= 5 * 10^5s[i] is either '0' or '1'.1 <= k <= 20class Solution:
# Time: O(n) each window hashed once; Space: O(2^k) for the set
def has_all_codes(self, s: str, k: int) -> bool:
need = 1 << k
if len(s) < need + k - 1:
return False
seen = set()
for i in range(len(s) - k + 1):
seen.add(s[i : i + k])
if len(seen) == need:
return True
return False
| Time | Space |
|---|---|
| O(n) each window hashed once; Space: O(2^k) for the set | - |