Start learning free

LESSON 449 OF 671 · SLIDING WINDOW

Minimum Window Substring in JavaScript: O(n + m) Sliding Window

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

    JAVASCRIPT · SLIDING WINDOW

    Minimum Window Substring in JavaScript, explained

    Problem overview

    minWindow(s, t) receives two strings and returns the shortest substring of s that contains every character of t, repeats included. If t has two a's, the substring needs at least two. When no substring works, the function returns "". Uppercase and lowercase letters are different characters, and the tests are built so that the answer is unique.

    For s = "ADOBECODEBANC" and t = "ABC" the answer is "BANC". "ADOBEC" and "CODEBA" also contain an A, a B and a C, but they are longer.

    The statement asks for O(n + m) time, where n is the length of s and m the length of t, and O(1) extra space: one counter per character code.

    Approach: grow until complete, then shrink

    Checking every substring of s against t would be far too slow for strings of 100,000 characters. A sliding window avoids it. The window is the substring from index first to index last.

    1. Move last to the right, adding one character at a time, until the window holds everything t asks for.
    2. Once it does, move first to the right while the window can spare its first character, so that it is as short as possible for this right end.
    3. Compare that window with the best one so far and keep the shorter.

    Both ends only move right, so each index is visited at most twice and the loop does O(n) work. Counting the characters of t costs O(m).

    The bookkeeping uses one array, need, plus a number, missing:

    • need[code] is how many more of that character the window still needs. It starts as the number of times the character appears in t. Adding a character to the window lowers it, and removing one raises it.
    • A value below 0 means the window holds more of that character than t asks for. One of those extras can leave without breaking the window.
    • missing is how many characters of t the window still lacks, counting repeats. It starts at t.length, and the window is complete when it reaches 0.

    Here is the run on s = "ADOBECODEBANC" and t = "ABC". The last column is the best window found so far.

    lastaddedmissingfirstbest
    0A20none
    3B10none
    5C00ADOBEC
    9B00ADOBEC
    10A05ADOBEC
    12C09BANC

    At last = 10 the second A arrives, so the first A, the D, O, B and E in front of the C can all leave, and first jumps to 5. At last = 12 a second C arrives, which frees the leading C and everything up to index 9, and the window becomes "BANC".

    Step by step

    1. Create need with 128 zeros. Letters have character codes below 128, so one slot per code covers a to z and A to Z, each case separately.
    2. Loop over t with for...of, taking one character c at a time.
    3. Count each character by adding 1 at need[c.charCodeAt(0)]. A letter that appears twice in t ends up needed twice.
    4. Set missing to t.length. The empty window lacks every character of t.
    5. Declare first and bestStart at 0: the window's left end, and where the best window starts.
    6. Set bestLength to s.length + 1. No window can be that long, so the value means that none has been found yet.
    7. Loop with last over the indexes of s. Each turn adds one character.
    8. Store the character's code in code.
    9. Check whether the window needed it. If need[code] is above 0, t still asked for this character, so missing goes down. If it is 0 or less, this one is an extra.
    10. Lower need[code] in both cases, since the window now holds one more of that character. It can go negative.
    11. Test for a complete window with missing === 0.
    12. Shrink from the left while need[s.charCodeAt(first)] < 0. A negative count means the first character is an extra.
    13. Drop it: raise its count by one and move first right.
    14. Compare with the best window: its length is last - first + 1.
    15. Remember it by storing bestStart and bestLength. The substring itself is cut only once, at the end.
    16. After the loop, if bestLength is still above s.length, no window was ever complete, so return "".
    17. Otherwise cut the answer with substring(bestStart, bestStart + bestLength).

    The solution in JavaScript

    class Solution {
        minWindow(s, t) {
            let need = new Array(128).fill(0);
            for (const c of t) {
                need[c.charCodeAt(0)]++;
            }
            let missing = t.length;
            let first = 0, bestStart = 0;
            let bestLength = s.length + 1;
            for (let last = 0; last < s.length; last++) {
                let code = s.charCodeAt(last);
                if (need[code] > 0) missing--;
                need[code]--;
                if (missing === 0) {
                    while (need[s.charCodeAt(first)] < 0) {
                        need[s.charCodeAt(first)]++;
                        first++;
                    }
                    if (last - first + 1 < bestLength) {
                        bestStart = first;
                        bestLength = last - first + 1;
                    }
                }
            }
            if (bestLength > s.length) return "";
            return s.substring(bestStart, bestStart + bestLength);
        }
    }
    

    The details worth a closer look:

    • for...of over a string gives one character at a time, each as a one-character string. That is why the code calls charCodeAt(0) on c.
    • The array index is a number. need is indexed by character code, so "A" and "a" land in different slots (65 and 97), which is exactly the case sensitivity the problem wants.
    • substring(i, j) returns the characters from index i up to but not including j, so the end is bestStart + bestLength.
    • One-line if. if (need[code] > 0) missing--; is valid without braces. Only the single statement that follows belongs to the if, so the next line, need[code]--;, runs every time.
    • The order of the two updates matters. The test need[code] > 0 must come before need[code]--. Reversed, a needed character would look like an extra.

    Why does the window stay complete while it shrinks? The loop only drops a character whose count is negative, which means the window holds more copies than t needs. After the drop, the count is still at least 0 for every character, so nothing t asks for has been lost. The loop stops at the first character the window can't spare.

    Complexity

    Time: O(n + m). Counting t takes m steps. After that, last moves across s once, and first only moves right, so the shrinking loop's body runs at most n times in total.

    Space: O(1). The array has 128 entries whatever the input. The answer string is cut once at the end.

    Edge cases and common mistakes

    • Repeats in t. s = "a" with t = "aa" returns "": t needs two a's and s has only one. s = "aa" with t = "aa" returns "aa".
    • Letter case. s = "Ab" with t = "aB" returns "", because A is not a.
    • A missing letter. s = "abc" with t = "d" returns "", and bestLength keeps its starting value.
    • t equals s or is a single character. s = "a" with t = "a" returns "a".
    • Extras at the front. s = "aaab" with t = "ab" returns "ab", not "aaab": the shrinking loop drops the spare a's.
    • Counting distinct letters instead of copies. Setting missing to the number of different letters in t would accept "a" for t = "aa".
    • Returning the length or the start only. The function returns the substring, so both pieces of data are kept until the end.
    • Shrinking when the window isn't complete. The shrinking loop belongs inside the missing === 0 check. Outside it, characters that t still needs could be dropped.

    Testing

    • s = "ADOBECODEBANC", t = "ABC" gives "BANC".
    • s = "a", t = "a" gives "a".
    • s = "a", t = "aa" gives "".
    • s = "aa", t = "aa" gives "aa".
    • s = "Ab", t = "aB" gives "".
    • s = "abc", t = "d" gives "".
    • s = "bba", t = "ab" gives "ba".
    • s = "aaab", t = "ab" gives "ab".
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free