← Home

1461. Check If a String Contains All Binary Codes of Size K

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
sliding windowC++Markdown
146

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 1461. Check If a String Contains All Binary Codes of Size K, the solution in this repository is mainly a sliding window solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: sliding window, bit manipulation.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are hasAllCodes.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • A set is doing the membership or uniqueness work, which keeps the main loop readable.
  • Substring checks are convenient but not free, so they are part of the real complexity story.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 1648 ms, faster than 16.67% of C++ online submissions for Check If a String Contains All Binary Codes of Size K.
02//Memory Usage: 60.1 MB, less than 100.00% of C++ online submissions for Check If a String Contains All Binary Codes of Size K.
03class Solution {
04public:
05    bool hasAllCodes(string s, int k) {
06        set<string> codes;
07        
08        for(int i = 0; i+k-1 < s.size(); i++){
09            codes.insert(s.substr(i, k));
10        }
11        
12        return codes.size() == pow(2, k);
13    }
14};
15
16//sliding window + set
17//https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/discuss/660632/Incorrect-problem-statement!!!
18//Runtime: 1048 ms, faster than 30.69% of C++ online submissions for Check If a String Contains All Binary Codes of Size K.
19//Memory Usage: 61.3 MB, less than 100.00% of C++ online submissions for Check If a String Contains All Binary Codes of Size K.
20class Solution {
21public:
22    bool hasAllCodes(string s, int k) {
23        /*
24        choose deque so that we can use .begin() and .end()
25        */
26        deque<char> q;
27        /*
28        set<string> gives us TLE!!!
29        so use unordered_set here!
30        */
31        unordered_set<string> subset;
32        for(char c : s){
33            q.push_back(c);
34            if(q.size() == k){
35                // cout << string(q.begin(), q.end()) << endl;
36                subset.insert({q.begin(), q.end()});
37                q.pop_front();
38            }
39        }
40        
41        return subset.size() == (1 << k);
42    }
43};
44
45//replace deque with string to speed up
46//Runtime: 636 ms, faster than 61.41% of C++ online submissions for Check If a String Contains All Binary Codes of Size K.
47//Memory Usage: 58.3 MB, less than 100.00% of C++ online submissions for Check If a String Contains All Binary Codes of Size K.
48class Solution {
49public:
50    bool hasAllCodes(string s, int k) {
51        string window;
52        unordered_set<string> subset;
53        for(char c : s){
54            window += c;
55            if(window.size() == k){
56                // cout << window << endl;
57                subset.insert(window);
58                /*
59                string.erase(starting_pos, char_count)!
60                need to set the second argument to 1 o.w.
61                it will erase to the end!!
62                */
63                window.erase(0, 1);
64            }
65        }
66        
67        return subset.size() == (1 << k);
68    }
69};
70
71//brute-force
72//https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/discuss/660632/Incorrect-problem-statement!!!
73//TLE
74//195 / 196 test cases passed.
75class Solution {
76public:
77    bool hasAllCodes(string s, int k) {
78        int n = 1 << k;
79        //we want to find all 0 to n-1 in s
80        for (auto i{ 0 }; i < n; ++i) {
81            //32: just to ensure t can hold i
82            auto t = bitset<32>(i).to_string();
83            // cout << "size: " << t.size() << endl;
84            // cout << i << ", " << t << ", " << t.size() - k << endl;
85            //select the k least significant bis
86            t = t.substr(t.size() - k);
87            // cout << "t: " << t << endl;
88            if (s.find(t) == string::npos)
89                return false;
90        }
91        return true;
92    }
93};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.