Check If a String Contains All Binary Codes of Size K (LeetCode 1461): Solution and Explanation
Given a binary string s and an integer k, decide whether all 2^k binary strings of length k appear in s as substrings.
Intuition
Every substring of length k is one window of s, and s has exactly len(s) - k + 1 windows. If that is fewer than 2^k, some code is missing no matter what the bits are, so the answer is false right away.
Otherwise you need to know which codes the windows produce. Putting each window's text into a set works, but slicing a window costs O(k) and hashing strings is slow when k is 20 and s has half a million characters.
A window of k bits is just a number from 0 to 2^k - 1. When the window slides one step, the number shifts left by one, the top bit falls off, and the new bit enters on the right: code = ((code << 1) & mask) | bit with mask = 2^k - 1. That is O(1) per step.
Use the code as an index into a boolean array of size 2^k. Count how many entries flip from false to true, and stop as soon as the count reaches 2^k.
Approach: Rolling bitmask with a seen array
- Set
need = 1 << k. Iflen(s) - k + 1 < need, return false. - Create
seenof size need,mask = need - 1,code = 0,count = 0. - For each index i, update
code = ((code << 1) & mask) | bit. - Once
i >= k - 1the code is a full window. Ifseen[code]is false, set it and increase count. - When count reaches need, return true. If the loop ends first, return false.
Step-by-step example
s = "00110110", k = 2
- need = 4 codes, and s has 7 windows, so the answer is still possible.
- i = 0 shifts in 0; only one bit, no full window yet.
- i = 1 gives window 00 = code 0, new. count = 1.
- i = 2 gives 01 = code 1, new. count = 2.
- i = 3 gives 11 = code 3, new. count = 3.
- i = 4 gives 10 = code 2, new. count = 4 = need, so return true.
Code: Python, Java, C++
1class Solution:
2 def hasAllCodes(self, s: str, k: int) -> bool:
3 need = 1 << k
4 if len(s) - k + 1 < need:
5 return False
6 seen = [False] * need
7 mask = need - 1
8 code = 0
9 count = 0
10 for i in range(len(s)):
11 code = ((code << 1) & mask) | (ord(s[i]) - 48)
12 if i >= k - 1 and not seen[code]:
13 seen[code] = True
14 count += 1
15 if count == need:
16 return True
17 return False1class Solution {
2 public boolean hasAllCodes(String s, int k) {
3 int need = 1 << k;
4 if (s.length() - k + 1 < need) {
5 return false;
6 }
7 boolean[] seen = new boolean[need];
8 int mask = need - 1;
9 int code = 0;
10 int count = 0;
11 for (int i = 0; i < s.length(); i++) {
12 code = ((code << 1) & mask) | (s.charAt(i) - '0');
13 if (i >= k - 1 && !seen[code]) {
14 seen[code] = true;
15 count++;
16 if (count == need) {
17 return true;
18 }
19 }
20 }
21 return false;
22 }
23}1class Solution {
2public:
3 bool hasAllCodes(string s, int k) {
4 int need = 1 << k;
5 if ((int)s.size() - k + 1 < need) {
6 return false;
7 }
8 vector<bool> seen(need, false);
9 int mask = need - 1;
10 int code = 0;
11 int count = 0;
12 for (int i = 0; i < (int)s.size(); i++) {
13 code = ((code << 1) & mask) | (s[i] - '0');
14 if (i >= k - 1 && !seen[code]) {
15 seen[code] = true;
16 count++;
17 if (count == need) {
18 return true;
19 }
20 }
21 }
22 return false;
23 }
24};Time and space complexity
O(n + 2^k)
Each bit is processed in O(1), and allocating the seen array costs 2^k. The pre-check skips the allocation when s is too short.
O(2^k)
One flag per possible code, about a million for k = 20.
Other approaches
Set of substrings (time O(n * k), space O(2^k * k))
Insert s[i:i+k] for every i into a hash set and compare its size with 2^k. Short and clear, but each slice and hash costs O(k).
Set of rolling codes (time O(n), space O(min(n, 2^k)))
Same rolling update, but store the integers in a hash set instead of an array. It avoids allocating 2^k flags when most codes are missing, at the cost of hashing.
Common mistakes
- Counting windows before the first k bits are in. The code only describes a full window once i >= k - 1.
- Forgetting the mask. Without
& mask, the old bits never leave and the code keeps growing. - Allocating 2^20 entries for a tiny s. The window count pre-check returns false before the allocation.
Frequently asked questions
Why is the window count check valid?
Each window produces exactly one code, so len(s) - k + 1 windows can produce at most that many different codes. If that is below 2^k, at least one code is missing.
What is the shortest string that contains every code?
A De Bruijn sequence. Read as a cycle it has length 2^k; unrolled into a plain string it needs 2^k + k - 1 characters. The preset 0001011100 is one for k = 3.
Why stop as soon as count reaches 2^k?
Once every code is marked nothing later can change the answer, so the rest of the scan is wasted work.