Opening the reading…
Opening the reading…
SLIDING WINDOW › FIXED SIZE SLIDING-WINDOW
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →There are exactly 2^k binary strings of length k. The task is therefore a coverage check: slide a window of length k across s, identify the code in that window, and count how many different codes appear. If the count reaches 2^k, every possible code has been seen. If the scan ends first, at least one code never occurs.
A binary window can be read as a number whose k bits are exactly the characters in the window. For example, 011 has value 3 and 110 has value 6. When the window moves right, shift the old value left, keep only its newest k bits, and append the incoming character. A boolean array indexed by this value records each code without storing substring objects.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | The initial window is built in O(k), and each of the remaining n - k characters causes one shift, mask, lookup, and possible mark. Since k <= n after the early check, this is O(n), with early success only improving the actual run time. |
| Space | O(2^k) extra | The seen array has one entry for each possible code; the current integer and counters use O(1) additional space. The required boolean result is not stored as output, so no output storage is being counted. The bound does not degrade with the arrangement of s; it is set by k, reaching 2^20 entries at the largest allowed k. |
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
bool hasAllCodes(string s, int k) {
int n = static_cast<int>(s.size());
if (k > n) {
return false;
}
int needed = 1 << k;
vector<bool> seen(needed, false);
int count = 0;
int mask = needed - 1;
int num = 0;
for (int i = 0; i < k; ++i) {
num = (num << 1) | (s[i] - '0');
}
seen[num] = true;
++count;
for (int i = k; i < n; ++i) {
num = ((num << 1) & mask) | (s[i] - '0');
if (!seen[num]) {
seen[num] = true;
++count;
if (count == needed) {
return true;
}
}
}
return count == needed;
}
};The mask is the key placement detail. After num is shifted left, it may contain k + 1 meaningful bits, with the oldest bit belonging to the previous window. Applying mask removes that bit before the incoming character is appended. The seen check comes after the update, so each array access describes exactly one contiguous substring of length k.