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
Binary String Processing"0 0 1 1 0 1 1 0"00Window00011110Hash Set Size: 4 = 2^2 โœ“All possible binary codes found!
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

n
2n
โœ“ Linear Growth
Space Complexity
O(2^k ร— k)

Hash set stores at most 2^k strings, each of length k

n
2n
โœ“ 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
Asked in
Google 45 Facebook 32 Amazon 28 Microsoft 25
25.8K Views
Medium Frequency
~18 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen