Problem 1461

Abstract / Summary

Check if every possible binary string of length k appears as a substring in the given string.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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;
    }
};
34 lines | 890 bytes | submitted October 22, 2023 | GitHub   14% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

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
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.74 | σ = 1.07

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
30 links | 19 authors | 8 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

3 easy 2 medium
6 solutions   October 22, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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