Check If a String Contains All Binary Codes of Size K - 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.

A binary code of length k is a string of exactly k characters, where each character is either '0' or '1'.

Note: There are exactly 2^k different binary codes of length k. For example, when k=2, the binary codes are "00", "01", "10", and "11".

Input & Output

Example 1 — All Codes Present
$ Input: s = "00110110", k = 2
Output: true
💡 Note: For k=2, we need all 4 binary codes: "00", "01", "10", "11". String contains: "00" at index 0, "01" at index 1, "11" at index 2-3, "10" at index 4-5. All codes are present.
Example 2 — Missing Code
$ Input: s = "0110", k = 1
Output: true
💡 Note: For k=1, we need codes "0" and "1". String "0110" contains both: "0" at index 0 and "1" at indices 1,2. All codes present.
Example 3 — String Too Short
$ Input: s = "0110", k = 2
Output: false
💡 Note: For k=2, we need 4 codes: "00", "01", "10", "11". String contains "01" at index 0, "11" at index 1, "10" at index 2. Missing "00", so return false.

Constraints

  • 1 ≤ s.length ≤ 5 × 104
  • 1 ≤ k ≤ 20
  • s consists of only '0' and '1' characters

Visualization

Tap to expand
Binary Codes Problem: Find All 2^k SubstringsInput: s = "00110110", k = 2Need to find all 2² = 4 binary codes of length 200110110"00"Required codes (2² = 4):00011011Found in string:00011110Result: true
Understanding the Visualization
1
Input
Binary string s and integer k
2
Process
Extract all k-length substrings and count unique ones
3
Output
Return true if count equals 2^k
Key Takeaway
🎯 Key Insight: Use rolling hash to convert k-length binary substrings to integers for O(1) processing
Asked in
Facebook 35 Google 28 Amazon 22
28.5K Views
Medium Frequency
~25 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