Start learning free

LESSON 168 OF 314 · SLIDING WINDOW

Minimum Window Substring in Go: Sliding Window, 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

    GO · SLIDING WINDOW

    Minimum Window Substring in Go, 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. When no substring works, it returns "". Uppercase and lowercase letters are different characters, and the tests guarantee 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 "", because s has only one a.

    The target is O(n + m) time, where n and m are the lengths of s and t, and O(1) extra space: one counter per character code.

    Approach: grow until complete, trim what can be spared

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

    • last moves right one character at a time, adding that character to the window.
    • Once the window holds everything t asks for, first moves right as long as the character it leaves behind is a spare, that is, the window holds more copies of it than t needs.
    • The window is then the shortest complete window that ends at last. If it beats the best one so far, remember where it starts and how long it is.

    To know whether the window is complete, one slice of counts does all the work. need[code] says how many more copies of that character the window still needs. It starts as the count of the character in t, drops when the window gains a copy, and goes negative when the window holds more than t asks for. A negative count therefore marks a spare, and a separate counter, missing, says how many characters of t are still lacking in total. When it reaches 0, the window is complete.

    Both ends only move right, so each moves at most n times and the scan is linear.

    Step by step

    1. Create need. make([]int, 128) gives 128 zeros, one per ASCII code. Letters have codes below 128, and each case has its own codes.
    2. Count the characters of t. A for loop with range over t yields the index and the rune; the index is skipped with _. Each rune is a number, so it can index need directly, and need[c]++ counts it. A letter that appears twice in t is needed twice.
    3. Set missing to len(t). It is the number of characters of t the window still lacks.
    4. Set up the bookkeeping. first is the left end and bestStart is where the best window starts; both are 0. bestLength starts at len(s) + 1, which is longer than any window, so it also means that nothing has been found yet.
    5. Grow the window. The loop moves last across s. code := s[last] is the byte for the new character.
    6. Is this character still needed? If need[code] > 0, t still wanted it, so missing goes down. If the count is 0 or negative, the window already has enough copies and this one is extra.
    7. Update the count. need[code]-- records that the window holds one more copy. It can become negative, which marks a spare.
    8. Act only when complete. If missing == 0, trim from the left with for need[s[first]] < 0: while the first character is a spare, put its count back with need[s[first]]++ and move first right.
    9. Compare with the best. If last-first+1 is below bestLength, store the new bestStart and bestLength. Only two numbers are kept, and the substring is cut once, at the end.
    10. Return. If bestLength is still above len(s), no window was ever complete, so return "". Otherwise return s[bestStart : bestStart+bestLength].

    The solution in Go

    func minWindow(s string, t string) string {
        need := make([]int, 128)
        for _, c := range t {
            need[c]++
        }
        missing := len(t)
        first, bestStart := 0, 0
        bestLength := len(s) + 1
        for last := 0; last < len(s); last++ {
            code := s[last]
            if need[code] > 0 {
                missing--
            }
            need[code]--
            if missing == 0 {
                for need[s[first]] < 0 {
                    need[s[first]]++
                    first++
                }
                if last-first+1 < bestLength {
                    bestStart = first
                    bestLength = last - first + 1
                }
            }
        }
        if bestLength > len(s) {
            return ""
        }
        return s[bestStart : bestStart+bestLength]
    }
    

    Here is the run on s = "ADOBECODEBANC" and t = "ABC". Each row shows the state after that value of last, with best being the substring stored so far:

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

    The window first becomes complete at last=5. At last=10 the second A arrives, so the first A and the letters up to the first B and C are no longer needed, and first jumps to 5. At last=12 the window is trimmed to "BANC", which is shorter than the best so far.

    Why the trimming loop is safe

    The loop stops at a character whose count is 0 or more. Such a character is one that t needs, with no spare copy in the window, so dropping it would make the window incomplete. The loop also can't run past last: the window is complete, so it contains needed characters, and the first of those has a count of at least 0 and stops the loop.

    Go details

    • range over a string gives runes. In for _, c := range t, c is a rune (an alias for int32), the Unicode code point of each character. Because the input has English letters only, it is below 128.
    • s[last] gives a byte. Indexing a string returns a byte (uint8). Both types are integers, so both index the slice without a conversion.
    • Slicing a string. s[i:j] holds the bytes from i up to but not including j. The result shares memory with s, so no copy is made. Since every letter is one byte, bytes and letters are the same here.
    • Counts as a slice, not a map. A slice of 128 integers is a fixed size, and indexing it is cheap. A character outside ASCII would be out of range and panic, which the constraints rule out.
    • Multiple declarations. first, bestStart := 0, 0 declares two int variables on one line.

    Complexity

    Time: O(n + m). Counting t takes m steps. last visits each index of s once. first only moves right and never passes last, so the trimming loop's body runs at most n times in total.

    Space: O(1). The slice has 128 entries whatever the input, plus a few integers. The returned substring shares the memory of s.

    Edge cases and common mistakes

    • Repeated characters in t. s = "abcabc" and t = "aabc" gives "abca". Counting only which letters are present, and not how many, would accept "abc".
    • No answer. s = "a" and t = "aa", or s = "abc" and t = "d", give "".
    • Case matters. s = "Ab" and t = "aB" gives "", because a and A have different codes.
    • t as long as s. s = "aa" and t = "aa" returns the whole string.
    • Decreasing missing for extra copies. Without the need[code] > 0 test, a spare copy would reduce missing and the window would be called complete too early.
    • Dropping a needed character. Trimming while the count is 0 or more would break the window. The loop condition is strictly below 0.
    • Returning an empty slice instead of checking. bestLength starting at len(s) + 1 is what lets the final test tell "nothing found" from "found".

    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 = "bba", t = "ab" gives "ba".
    • s = "abcabc", t = "aabc" gives "abca".
    • s = "Ab", t = "aB" gives "".
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free