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 Substring Checker INPUT Binary String s: 0 0 1 1 0 1 1 0 0 1 2 3 4 5 6 7 k = 2 Required Codes (2^2 = 4): 00 01 10 11 Input Values s = "00110110" k = 2 Length: 8 characters Need: 4 unique codes ALGORITHM STEPS 1 Initialize Hash Set Create empty set for codes 2 Rolling Hash Window Slide k-size window over s 3 Add Substrings Add each k-substring to set 4 Early Termination Stop when set.size = 2^k Hash Set Contents "00" hash--> 0 "01" hash--> 1 "11" hash--> 3 "10" hash--> 2 Set: {00, 01, 11, 10} Size: 4 = 2^2 [OK] Early termination triggered! FINAL RESULT All Binary Codes Found: "00" [OK] "01" [OK] "10" [OK] "11" [OK] Output: true Verification Found: 4 unique codes Required: 2^2 = 4 codes Key Insight: Rolling hash converts each k-length binary substring to an integer (0 to 2^k-1) in O(1) time. By using a HashSet, we track unique codes efficiently. Early termination occurs when set size reaches 2^k, avoiding unnecessary iterations. Time: O(n*k) or O(n) with rolling hash. Space: O(2^k) for the set. TutorialsPoint - Check If a String Contains All Binary Codes of Size K | Rolling Hash with Early Termination
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