Start learning free

LESSON 451 OF 673 · SLIDING WINDOW

Minimum Window Substring in Python: Sliding Window with Counts

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

    PYTHON · SLIDING WINDOW

    Minimum Window Substring in Python, 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 as, the substring needs at least two. If no substring works, it 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". The substrings "ADOBEC" and "CODEBA" also hold an A, a B and a C, but they are longer. For s = "a" and t = "aa" the answer is "": t needs two as and s has only one.

    Approach: grow the window, then trim it

    Checking every substring of s against t is far too slow for 100,000 characters. A sliding window does it in one pass. The window is the substring from index first to index last.

    1. Move last to the right, adding one character to the window at a time.
    2. Once the window holds everything t asks for, it is complete. Move first to the right while the window can spare its first character, which makes it as short as possible for this last.
    3. Compare that length with the best found so far.

    To know whether the window is complete without recounting it, keep a list need with one slot per character code. need[code] says how many more copies of that character the window still needs. It starts as the counts of t. Adding a character to the window lowers its slot by 1, and removing one raises it by 1. A slot at 0 means the window holds exactly the copies t asks for. A negative slot means it holds extras, which can leave without breaking the window.

    The variable missing tracks how many characters of t are still lacking, counting repeats. It starts at len(t). When a character enters the window while its slot is above 0, it fills a real need, so missing drops by 1. When missing reaches 0, the window is complete.

    Here is the run on "ADOBECODEBANC" with t = "ABC":

    last=0  A  missing=2
    last=1  D  missing=2
    last=2  O  missing=2
    last=3  B  missing=1
    last=4  E  missing=1
    last=5  C  missing=0  window "ADOBEC"     best "ADOBEC"
    last=6  O  missing=0  window "ADOBECO"    best "ADOBEC"
    last=7  D  missing=0  window "ADOBECOD"   best "ADOBEC"
    last=8  E  missing=0  window "ADOBECODE"  best "ADOBEC"
    last=9  B  missing=0  window "ADOBECODEB" best "ADOBEC"
    last=10 A  missing=0  window "CODEBA"     best "ADOBEC"
    last=11 N  missing=0  window "CODEBAN"    best "ADOBEC"
    last=12 C  missing=0  window "BANC"       best "BANC"
    

    At last=10 the new A makes the first A spare, so the trim drops A, D, O and B and stops at C, which is still needed. At last=12 the trim reaches "BANC", shorter than the best so far.

    Step by step

    1. Create need as [0] * 128. 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 the characters of t and add 1 to need[ord(c)]. A letter that appears twice in t is needed twice.
    3. Set missing to len(t).
    4. Set first = bestStart = 0: the window's left end and the start of the best window so far.
    5. Set bestLength to len(s) + 1. No window can be that long, so this value means that none has been found yet.
    6. Loop last over range(len(s)), adding the character at last to the window.
    7. Take its code with ord(s[last]).
    8. If need[code] is above 0, subtract 1 from missing. A slot at 0 or below means the window already has every copy t asks for, so this one is extra.
    9. Subtract 1 from need[code] in every case, because the window now holds one more of that character.
    10. Check missing == 0. Only a complete window can be an answer.
    11. Trim from the left with a while loop that runs while need[ord(s[first])] is below 0, which means the first character is spare.
    12. Drop the first character: add 1 back to its slot and move first forward.
    13. Compare lengths. If last - first + 1 is less than bestLength, this is the shortest complete window so far.
    14. Remember it by saving bestStart and bestLength. Only the position and length are stored, and the substring is cut once at the end.
    15. If bestLength is still above len(s), no window was ever complete, so return "".
    16. Otherwise return the slice s[bestStart:bestStart + bestLength].

    The solution in Python

    class Solution:
        def minWindow(self, s: str, t: str) -> str:
            need = [0] * 128
            for c in t:
                need[ord(c)] += 1
            missing = len(t)
            first = bestStart = 0
            bestLength = len(s) + 1
            for last in range(len(s)):
                code = ord(s[last])
                if need[code] > 0:
                    missing -= 1
                need[code] -= 1
                if missing == 0:
                    while need[ord(s[first])] < 0:
                        need[ord(s[first])] += 1
                        first += 1
                    if last - first + 1 < bestLength:
                        bestStart = first
                        bestLength = last - first + 1
            if bestLength > len(s):
                return ""
            return s[bestStart:bestStart + bestLength]
    

    Python details worth a closer look:

    • Iterating a string. for c in t yields one-character strings, and ord(c) turns each into its integer code. For example, ord('A') is 65 and ord('a') is 97, which is why the two cases never share a slot.
    • Slices. s[i:j] holds the characters from index i up to but not including j. Strings are immutable, so a slice makes a new string, and this code makes exactly one, at the end.
    • A negative slot is meaningful. Indexing a list with a negative index counts from the end, but here the negative numbers are the values in need, so there is no wrap-around problem. The indices are always character codes, which are never negative.
    • Letters only. A character with a code of 128 or more would be out of range for need and raise IndexError. The constraints promise only English letters.

    Complexity

    Time: O(n + m) for n = len(s) and m = len(t). Counting t takes m steps. After that, last visits each index of s once, and first only moves right, so the trimming loop runs at most n times over the whole run.

    Space: O(1). The list has 128 slots whatever the input length. The returned slice is the answer and not extra working space.

    Edge cases and common mistakes

    • Repeated letters in t. s = "a" with t = "aa" returns "", and s = "aa" with t = "aa" returns "aa". A set of the letters in t would accept both.
    • Case matters. s = "Ab" with t = "a" returns "", because A and a are different characters.
    • t longer than s. s = "ab" with t = "abc" returns "", since missing never reaches 0.
    • Order doesn't matter. s = "abc" with t = "cba" returns "abc". Only counts count.
    • Decrementing missing for extras. If missing dropped for every character in t regardless of the slot, a third a would be counted as progress and the window would look complete too early. The need[code] > 0 test prevents that.
    • Trimming an incomplete window. The trim only runs when missing == 0. Otherwise it could drop a character the window still needs.
    • Using bestLength = len(s) as the starting value. Then a window equal to the whole string could never be recorded as an improvement, and the function would return "" for s = "a" and t = "a". That is why the start is len(s) + 1.

    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 = "b" gives "b".
    • s = "Ab", t = "a" gives "".
    • s = "abc", t = "cba" gives "abc".
    • s = "ab", t = "abc" gives "".
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free