Check If a String Contains All Binary Codes of Size K - Problem
Imagine you're a cryptographer working with binary codes! Given a binary string s and an integer k, you need to determine if every possible binary code of length k appears as a substring within s.
For example, if k = 2, there are exactly 4 possible binary codes: "00", "01", "10", and "11". Your task is to check if all of these appear somewhere in the given string s.
Goal: Return true if every binary code of length k is a substring of s, otherwise return false.
Input & Output
example_1.py โ Basic case with k=2
$
Input:
s = "00110110", k = 2
โบ
Output:
true
๐ก Note:
The 4 possible binary codes of length 2 are: "00", "01", "10", and "11". All of these appear as substrings in "00110110": "00" at index 0, "01" at index 1, "11" at index 2, and "10" at index 5.
example_2.py โ Missing code case
$
Input:
s = "0110", k = 1
โบ
Output:
true
๐ก Note:
The 2 possible binary codes of length 1 are: "0" and "1". Both appear in "0110": "0" at indices 0 and 3, "1" at indices 1 and 2.
example_3.py โ Insufficient length
$
Input:
s = "0110", k = 2
โบ
Output:
false
๐ก Note:
The 4 possible binary codes of length 2 are: "00", "01", "10", "11". In string "0110" we can find: "01", "11", "10", but "00" is missing.
Visualization
Tap to expand
Understanding the Visualization
1
Setup
Place sliding window of size k at the start of string
2
Extract
Extract the k-length substring and add to hash set
3
Slide
Move window one position right and repeat
4
Check
Stop when we have 2^k unique codes or reach end
Key Takeaway
๐ฏ Key Insight: We only need to collect 2^k unique substrings, and the sliding window approach with hash set allows us to do this optimally in one pass with early termination.
Time & Space Complexity
Time Complexity
O(n ร k)
Single pass through string of length n, with k time to process each substring
โ Linear Growth
Space Complexity
O(2^k ร k)
Hash set stores at most 2^k strings, each of length k
โ Linear Space
Constraints
- 1 โค s.length โค 5 ร 105
- s[i] is either '0' or '1'
- 1 โค k โค 20
- The string s consists only of binary digits
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code