Start learning free

LESSON 168 OF 314 · SLIDING WINDOW

Minimum Window Substring in C++: Sliding Window with a Count Array

Practice O(n) Read the full explanation

You are given two strings s and t made of English letters. Return the shortest substring of s that contains every character of t, repeats included: if a letter appears twice in t, the substring must contain it at least twice.

If no substring of s contains all the characters of t, return an empty string, "". Uppercase and lowercase letters are different characters.

A substring is a run of consecutive characters of s. The tests are made so that the answer is unique.

 

Example 1:

Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
Explanation: "BANC" contains an A, a B and a C, and no shorter substring contains all three. "ADOBEC" and "CODEBA" contain them too, but they are longer.

Example 2:

Input: s = "a", t = "a"
Output: "a"
Explanation: s itself contains every character of t, and there is nothing shorter to try.

Example 3:

Input: s = "a", t = "aa"
Output: ""
Explanation: t needs two a's, but s has only one, so no substring works. The expected output shows an empty line for it.

 

Constraints:

  • 1 <= s.length, t.length <= 105
  • s and t are made of uppercase and lowercase English letters only (a to z, A to Z).

Note:

Your algorithm should run in O(n + m) time, where n is the length of s and m the length of t, and use O(1) extra space: one count for each character code.

STEP 1 OF 17
    Ctrl + Enter to check

    C++ · SLIDING WINDOW

    Minimum Window Substring in C++, explained

    Problem overview

    The function minWindow receives two strings, s and t, made of English letters. It returns the shortest substring of s that contains every character of t, repeats included: if t has two as, the substring needs at least two. Uppercase and lowercase letters are different characters. If no substring qualifies, the function returns an empty string.

    For s = "ADOBECODEBANC" and t = "ABC" the answer is "BANC". Substrings such as "ADOBEC" and "CODEBA" also hold an A, a B and a C, but both are longer. For s = "a" and t = "aa" the answer is "", because s holds only one a.

    The budget is O(n + m) time, where n and m are the lengths of s and t, and constant extra space.

    Approach: a window that grows, then shrinks

    Checking every substring of s costs at least O(n²) windows, each needing a count, which is far too slow for strings of 100,000 characters. A sliding window avoids that. The window is the substring from index first to index last, and it only ever moves right.

    1. Move last to the right one character at a time, adding that character to the window.
    2. As soon as the window holds everything t asks for, move first to the right to drop every character the window can spare. What remains is the shortest complete window that ends at last.
    3. Remember it if it beats the best one so far.

    Both first and last move right at most n times, so the total work is O(n) after an O(m) pass over t.

    The tricky part is knowing, in constant time, whether the window is complete. The lesson keeps one integer array, need, indexed by character code, and one counter, missing. need[c] is how many more copies of c the window still needs. A negative value means the window holds more copies of c than t asks for, and that many can leave without hurting. missing counts the characters of t still lacking, repeats included. When it reaches 0, the window is complete.

    Characters that don't appear in t start at 0 in need, so when they enter the window they drop below zero straight away: all of them count as spare.

    Here is the run on s = "ADOBECODEBANC", t = "ABC", one row per value of last:

    last  char  missing  first  best length
    0     A     2        0      none
    1     D     2        0      none
    2     O     2        0      none
    3     B     1        0      none
    4     E     1        0      none
    5     C     0        0      6
    6     O     0        0      6
    7     D     0        0      6
    8     E     0        0      6
    9     B     0        0      6
    10    A     0        5      6
    11    N     0        5      6
    12    C     0        9      4
    

    The window first becomes complete at last = 5, as "ADOBEC". At last = 10 the new A makes the old one at index 0 spare, so first jumps to 5, giving "CODEBA", which ties the best length and doesn't replace it. At last = 12 the new C makes the one at index 5 spare, and first moves to 9: the window is "BANC", of length 4.

    Step by step

    1. Create need as a vector<int> of 128 zeros. Letters have codes below 128, so one slot per code is enough, and it keeps a and A apart.
    2. Count t. A range-based for over t adds 1 to need[c] for each character. A char is a small integer in C++, so it indexes the vector directly, and a letter that appears twice is needed twice.
    3. Set missing to t.size(): at the start, the window lacks every character of t.
    4. Declare first and bestStart as 0: the window's left end and where the best window starts.
    5. Set bestLength to s.size() + 1. No window can be that long, so this value means "none found yet".
    6. Loop last over every index of s, adding one character per turn.
    7. Store the new character in an int named code, which keeps its numeric code.
    8. Update missing. If need[code] is above 0, t still wanted this character, so missing goes down. If it is 0 or less, the window already had enough copies and this one is extra.
    9. Decrease need[code] in every case: the window now holds one more of that character.
    10. Check missing == 0. Only a complete window is worth shrinking and comparing.
    11. Shrink from the left while need[s[first]] < 0, which means the first character is spare. Each dropped character gets need raised by one and first moved right. The loop stops at a character the window can't lose.
    12. Compare lengths. If last - first + 1 is below bestLength, save bestStart and bestLength. Only two integers are kept, and the substring is cut once at the end.
    13. Handle "no answer". If bestLength is still above s.size(), no window was ever complete, so return "".
    14. Return s.substr(bestStart, bestLength): substr takes a start position and a length.

    The solution in C++

    class Solution {
    public:
        string minWindow(string s, string t) {
            vector<int> need(128, 0);
            for (char c : t) {
                need[c]++;
            }
            int missing = t.size();
            int first = 0, bestStart = 0;
            int bestLength = s.size() + 1;
            for (int last = 0; last < s.size(); last++) {
                int code = s[last];
                if (need[code] > 0) missing--;
                need[code]--;
                if (missing == 0) {
                    while (need[s[first]] < 0) {
                        need[s[first]]++;
                        first++;
                    }
                    if (last - first + 1 < bestLength) {
                        bestStart = first;
                        bestLength = last - first + 1;
                    }
                }
            }
            if (bestLength > s.size()) return "";
            return s.substr(bestStart, bestLength);
        }
    };
    

    The C++ details worth a closer look:

    • char as an index. need[c] and need[s[first]] use a character as a vector index. That is fine for letters, whose codes are 65 to 90 and 97 to 122. A character with a negative char value, which plain char can have on common platforms for non-ASCII bytes, would index out of range, but the constraints allow letters only.
    • Unsigned sizes. s.size() is unsigned. last < s.size() and bestLength > s.size() compare an int with an unsigned value. Both are safe here because the ints are never negative. int missing = t.size() converts quietly to int, which is fine for 100,000.
    • The shrink loop stops in time. It runs only when the window is complete, so every character t needs is inside it. A character's need is negative only while the window holds a spare copy of it, so the loop always stops at a character the window must keep, and first never passes last.
    • Copying strings. The function takes s and t by value, so each call copies them. That costs O(n + m), the same as the algorithm. Taking const string& would avoid the copy, but the lesson's signature uses values.
    • substr. s.substr(pos, len) returns a new string of up to len characters starting at pos. Here the range always lies inside s.

    Complexity

    Time: O(n + m). Counting t takes m steps. After that, last visits each index of s once, and first only moves right, so the shrink loop runs at most n times in total over the whole run. The final substr is O(n).

    Space: O(1) extra. need always has 128 entries, whatever the input sizes. The returned substring is the output, not working space.

    Edge cases and common mistakes

    • No answer. s = "xyz" with t = "abc" returns "". So does s = "a" with t = "aa", where s has the right letter but too few copies.
    • Repeated characters in t. Checking only which letters appear would accept "a" for t = "aa". The counts in need are what enforce the repeats.
    • Case matters. s = "AaBb" with t = "ab" returns "aBb", because A is not a.
    • s shorter than t. No window can be complete, and the function returns "".
    • The whole string. s = "aa" with t = "aa" returns "aa": the window never shrinks.
    • Decrementing missing too often. If missing went down for every character of t seen, a window with three as would look complete for t = "abc". The need[code] > 0 test prevents that.
    • Forgetting to put the count back. When first drops a character, need must go up by one, or later windows will undercount.

    Testing

    • s = "ADOBECODEBANC", t = "ABC" gives "BANC".
    • s = "a", t = "a" gives "a".
    • s = "a", t = "aa" gives "".
    • s = "aabdec", t = "abc" gives "abdec".
    • s = "bba", t = "ab" gives "ba".
    • s = "AaBb", t = "ab" gives "aBb".
    • s = "xyz", t = "abc" gives "".
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free