C++ 1461.cpp
class Solution {
public:
bool hasAllCodes(string s, int k)
{
// too short
if (s.size() <= k)
return false;
vector<bool> have(1 << k, false);
int mask = (1 << k) - 1;
int bits = 0;
// build initial code of length k - 1
for (int i = 0; i < k - 1; i++)
{
bits <<= 1;
bits |= s[i] - '0';
}
// add all codes with length k
for (int i = k - 1; i < s.size(); i++)
{
bits <<= 1;
bits &= mask;
bits |= s[i] - '0';
have[bits] = true;
}
// if all codes of length k are found, then all codes of small length are part of s, too
for (int i = 0; i < have.size(); i++)
if (!have[i])
return false;
return true;
}
};
Difficulty
and has an acceptance rate of about 62% (400k+ submissions).
Typical patterns to solve this problem:
- Bit Manipulation
- Hash Function
- Hash Table
- Rolling Hash
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation determines whether a binary string s contains every possible binary code of length k. It returns true only when each of the 2^k distinct substrings of length k appears at least once in s. The algorithm proceeds by sliding a fixed-size window across the string, encoding each window as an integer, and marking its presence in a compact boolean array.
Key Steps
The function begins with a guard clause that eliminates strings that are too short to possibly contain all codes. If the length of s is less than or equal to k, the function immediately returns false. This early exit prevents unnecessary work for inputs that cannot satisfy the requirement.
if (s.size() <= k)
return false;
A vector of booleans, sized to 2^k, is allocated to record which codes have been observed. Each index corresponds to a distinct binary pattern, and the vector is initialized to false.
vector<bool> have(1 << k, false);
A mask value consisting of k low-order bits set to 1 is computed. This mask is used later to truncate the sliding window representation to exactly k bits after each shift.
int mask = (1 << k) - 1;
The variable bits holds the integer representation of the current window. The algorithm first constructs the initial window of length k-1 by iterating over the first k-1 characters. For each character, the current bits are shifted left and the new bit (derived from the character '0' or '1') is OR-ed in.
int bits = 0;
for (int i = 0; i < k - 1; i++)
{
bits <<= 1;
bits |= s[i] - '0';
}
The main loop starts at position k-1 and proceeds to the end of the string. In each iteration, the window is extended by one character: bits is shifted left, the mask is applied to discard any overflow beyond k bits, and the new bit from s[i] is incorporated. The resulting integer uniquely identifies the current substring of length k, and the corresponding entry in have is set to true.
for (int i = k - 1; i < s.size(); i++)
{
bits <<= 1;
bits &= mask;
bits |= s[i] - '0';
have[bits] = true;
}
After processing the entire string, the function scans the have vector to verify that every possible code has been seen. If any entry remains false, the function returns false; otherwise it returns true.
for (int i = 0; i < have.size(); i++)
if (!have[i])
return false;
return true;
Edge Cases Handled
The early length check ensures that strings whose length is exactly k are correctly rejected, because a single substring of length k cannot cover all 2^k possibilities unless k is zero, which is not a meaningful scenario for binary codes. The sliding window logic gracefully handles leading zeros because each character is converted by subtracting '0', yielding a numeric 0 or 1. The mask operation guarantees that bits beyond the most recent k characters are never retained, preventing contamination from earlier portions of the string. The final verification loop correctly identifies missing codes even when the string contains many repeated substrings, as each distinct pattern must be marked individually.
Performance Optimizations
The algorithm leverages bitwise operations to maintain the current window in constant time per character. Shifting and masking avoid the overhead of substring extraction or string comparison, yielding a highly efficient sliding window. Storing the presence flags in a vector<bool> compresses the memory footprint to one bit per possible code, which is especially beneficial when k is moderate and the number of codes grows exponentially. The use of a pre-computed mask eliminates the need for conditional checks to enforce the window size, allowing the inner loop to consist solely of inexpensive arithmetic and logical instructions. The final linear scan of the boolean vector is the only additional pass required, and it operates over a fixed size of 2^k, independent of the input string length.
ELI5 - Simplified Explanation
Imagine a very long street covered in patterns made of zeros and ones. This code is like a little robot helper that wants to make sure it has seen every possible combination of zeros and ones with a specific length called k.
First, the robot looks at the street to see if it is long enough to hold all the different combinations. If the street is too short, the robot knows it cannot possibly find everything it needs.
Next, the robot creates a giant checklist where every single box starts empty. This checklist represents every possible pattern of length k.
The robot starts walking along the street. It picks up a small chunk of the street with length k and looks at the pattern. It uses a clever trick with math to remember exactly which pattern it is holding, and then it marks that pattern as found on its giant checklist. The robot slides along the street, always keeping a window of length k open, and checks every possible overlapping chunk. Each time it sees a new pattern, it puts a big checkmark on the list.
After the robot finishes walking the whole street, it takes one final look at the checklist. It checks every single box to see if any are still empty. If the robot finds any empty boxes, it means it missed at least one pattern. If every single box has a checkmark, the robot is very happy because it knows it saw every pattern that could possibly exist for that length.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | TS | ||||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fartem | Ruby | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| withaarzoo | C++ | ||||||||
| YuriSpiridonov | Python | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| withaarzoo | C++ | ||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 836: Rectangle Overlap
- problem 867: Transpose Matrix
- problem 2824: Count Pairs Whose Sum is Less than Target
- problem 475: Heaters
- problem 672: Bulb Switcher II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality