Start learning free

LESSON 168 OF 314 · SLIDING WINDOW

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

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

    TYPESCRIPT · SLIDING WINDOW

    Minimum Window Substring in TypeScript, explained

    Problem overview

    The method minWindow receives two strings, s and t. It 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, it returns the empty string "". Uppercase and lowercase letters are different characters, and the tests guarantee a unique answer.

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

    Approach

    Checking every substring of s against t is far too slow. A sliding window does it in one pass. The window is the substring from index first to index last. The right end last moves forward one character at a time, adding characters until the window holds everything t asks for. Then the left end first moves forward to cut every character the window can spare, which gives the shortest complete window ending at last. The best of these over all positions of last is the answer.

    Both ends only move right, so each character enters and leaves the window at most once. The time is O(n + m) for s of length n and t of length m.

    To know whether the window is complete without comparing whole counts every time, the code keeps two things: an array need with the number of copies of each character the window still needs, and a number missing with how many characters of t the window still lacks.

    Step by step

    1. One count per character code. need has 128 zeros, indexed by character code. Letters have codes below 128, so this covers a to z and A to Z, each case on its own.
    2. Count the characters of t. A for...of loop over t adds one to need[c.charCodeAt(0)] for each character c. A letter that appears twice in t ends up with a count of 2.
    3. missing starts at t.length. It is the number of characters, repeats counted, that the empty window lacks. When it reaches 0, the window is complete.
    4. The window and the best answer. first and bestStart start at 0. bestLength starts at s.length + 1, which no real window can reach, so it also means "none found yet".
    5. Add a character. The loop moves last over s. The character's code, s.charCodeAt(last), picks its slot in need.
    6. Did this character help? If need[code] is above 0, the window was still short of that character, so missing goes down by one. If it is 0 or below, the window already had enough copies and this one is extra.
    7. Update the count. need[code] goes down by one in either case. It can become negative, and a negative value means the window holds more of that character than t asks for.
    8. React when the window is complete. When missing === 0, a while loop moves first forward as long as need[s.charCodeAt(first)] < 0: the first character is a spare, so removing it keeps the window complete. Each removal adds one back to its count.
    9. Keep the best window. If last - first + 1 is shorter than bestLength, remember first and the new length. Only the start and the length are stored; the substring is cut once at the end.
    10. Return the result. If bestLength is still above s.length, no window was ever complete and the answer is "". Otherwise it is s.substring(bestStart, bestStart + bestLength).

    The solution in TypeScript

    class Solution {
        minWindow(s: string, t: string): string {
            let need: number[] = 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);
        }
    }
    

    Details worth knowing:

    • for (const c of t) goes over the characters of a string, and each c is a one-character string. That is why c.charCodeAt(0) is needed to get a number.
    • charCodeAt returns UTF-16 code units. For letters this is the ASCII code, below 128. A character outside that range would index past the 128 slots of need, so the array suits the lesson's inputs, which have English letters only.
    • substring(i, j) returns the characters from index i up to, but not including, index j.
    • The array stays a plain array of numbers. Reading a slot that was never changed gives 0 because of fill(0).

    Walking through an example

    For s = "ADOBECODEBANC" and t = "ABC", each turn ends like this:

    lastlettermissingwindownote
    0A2"A"
    1D2"AD"
    2O2"ADO"
    3B1"ADOB"
    4E1"ADOBE"
    5C0"ADOBEC"new best
    6O0"ADOBECO"complete, not shorter
    7D0"ADOBECOD"complete, not shorter
    8E0"ADOBECODE"complete, not shorter
    9B0"ADOBECODEB"complete, not shorter
    10A0"CODEBA"complete, not shorter
    11N0"CODEBAN"complete, not shorter
    12C0"BANC"new best

    At last = 10 the new A makes the first A a spare, so first jumps forward and the window shrinks from the left to "CODEBA". At last = 12 the new C makes the earlier one a spare, and the window shrinks to "BANC", of length 4.

    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 while body runs at most n times in total. Space: O(1). need always has 128 slots.

    Edge cases and common mistakes

    • Repeated letters in t. s = "a" and t = "aa" gives "": t needs two a's and s has one. A set of characters would not catch this; counts do.
    • No window at all. s = "abc" and t = "d" gives "", which is why bestLength starts above any possible length.
    • Letter case. "aAbB" with t = "Ab" gives "Ab", because A and a have different codes.
    • The whole string. s = "aa" and t = "aa" gives "aa", and s = "a" with t = "a" gives "a".
    • Counting extras as progress. Lowering missing for every matching letter would make it reach 0 too early. Only copies t still needs, those with need[code] > 0, count.
    • Shrinking too far. The while loop must stop at a character with a count of 0 or more, because dropping it would break the window.
    • Returning from the loop. The first complete window is rarely the shortest, so keep scanning to the end of s.

    Testing

    stResult
    "ADOBECODEBANC""ABC""BANC"
    "a""a""a"
    "a""aa"""
    "aa""aa""aa"
    "abc""cba""abc"
    "ab""b""b"
    "bba""ab""ba"
    "abc""d"""
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free