Start learning free

LESSON 168 OF 314 · SLIDING WINDOW

Minimum Window Substring in Swift: 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 18
    Ctrl + Enter to check

    SWIFT · SLIDING WINDOW

    Minimum Window Substring in Swift, explained

    Problem overview

    The method minWindow(_ s: String, _ t: String) receives two strings of English letters. 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 a's. If no substring qualifies, it returns "". Uppercase and lowercase letters are different characters, and the tests are made so that the answer is unique.

    For s = "ADOBECODEBANC" and t = "ABC" the answer is "BANC". The substrings "ADOBEC" and "CODEBA" hold an A, a B and a C too, but they are longer. For s = "a" and t = "a" the answer is "a". For s = "a" and t = "aa" it is "", because s has only one a.

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

    Approach: grow the window, then shrink it

    Checking every substring of s against t takes far too long for strings of 100,000 characters. A sliding window does the work in one pass. The window is the substring from index first to index last, and both ends only move right:

    • Move last right one character at a time. Each turn adds one character to the window.
    • When the window holds everything t asks for, move first right as long as the window stays complete, to make it as short as possible.
    • Compare that window with the best one so far and keep the shorter.

    The bookkeeping is one array, need, indexed by character code. need[code] is how many more of that character the window still needs. It starts as the count of each character in t. Adding a character to the window subtracts 1 from its entry. A positive entry means the window still lacks some; zero means exactly enough; a negative entry means the window holds extras that can leave without breaking it.

    A second counter, missing, starts at the length of t and goes down each time the window gains a character it still needed. When missing is 0, the window is complete. Checking one integer is much cheaper than scanning the whole array at each step.

    Here is the run on s = "ADOBECODEBANC" and t = "ABC". After each turn, the columns show the character just added, the value of missing, and the best window found so far as start and length:

    last  char  missing  best (start,length)
    0     A     2        none
    1     D     2        none
    2     O     2        none
    3     B     1        none
    4     E     1        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        0,6
    11    N     0        0,6
    12    C     0        9,4
    

    At last = 5 the window "ADOBEC" is complete, and it has nothing to trim at the front, so it is the first best window. At last = 10 the window shrinks to "CODEBA", which is also 6 long and doesn't replace the best. At last = 12 the window shrinks to "BANC", with length 4, and that wins.

    Step by step

    1. Copy the bytes into an array. A Swift String can't be indexed with an integer, so let chars = Array(s.utf8) gives the codes of the letters, with chars[i] for index i.
    2. Create need as 128 zeros. Letters have codes below 128, so one entry per code covers both cases separately.
    3. Count the characters of t with a for loop over t.utf8.
    4. Add 1 to need[Int(c)] for each one. c is a UInt8, and Int(c) converts it to an Int so it can index the array. A letter that appears twice in t is needed twice.
    5. Set missing to t.utf8.count, the number of characters the window still lacks.
    6. Declare first and bestStart as 0. first is the window's left end, and bestStart is where the shortest complete window so far starts.
    7. Declare bestLength as chars.count + 1. No window can be longer than s, so this value means that none has been found yet.
    8. Grow the window with a for loop where last goes over 0..<chars.count.
    9. Store the new character's code in code.
    10. If need[code] is above 0, the window needed this character, so subtract 1 from missing. A value of 0 or less means the window already has all the copies t asks for, and this one is extra.
    11. Subtract 1 from need[code] in every case, because the window now holds one more of it. The entry can go below 0.
    12. Check whether missing == 0. Once the window is complete, the next steps trim it.
    13. Trim the left end with a while loop that runs while need[Int(chars[first])] < 0. A negative entry means the window has more of that character than t needs, so dropping one keeps the window complete.
    14. Drop the first character: add 1 to its need entry and add 1 to first.
    15. Compare lengths. If last - first + 1 < bestLength, this window is the shortest complete one so far.
    16. Remember it by setting bestStart and bestLength. Only the start and the length are kept, and the substring is cut once at the end.
    17. Return "" if bestLength is still above chars.count, which means that no window was ever complete.
    18. Otherwise cut the best window out of chars and turn the codes back into a string.

    The solution in Swift

    class Solution {
        func minWindow(_ s: String, _ t: String) -> String {
            let chars = Array(s.utf8)
            var need = [Int](repeating: 0, count: 128)
            for c in t.utf8 {
                need[Int(c)] += 1
            }
            var missing = t.utf8.count
            var first = 0, bestStart = 0
            var bestLength = chars.count + 1
            for last in 0..<chars.count {
                let code = Int(chars[last])
                if need[code] > 0 { missing -= 1 }
                need[code] -= 1
                if missing == 0 {
                    while need[Int(chars[first])] < 0 {
                        need[Int(chars[first])] += 1
                        first += 1
                    }
                    if last - first + 1 < bestLength {
                        bestStart = first
                        bestLength = last - first + 1
                    }
                }
            }
            if bestLength > chars.count { return "" }
            return String(decoding: chars[bestStart..<bestStart + bestLength], as: UTF8.self)
        }
    }
    

    The Swift details worth a closer look:

    • utf8 gives bytes. s.utf8 is a view of the string as UInt8 values, one per ASCII letter. That is why the loop variable c needs Int(c) before it can be used as an index.
    • Slicing an array. chars[bestStart..<bestStart + bestLength] is an ArraySlice<UInt8>, the codes from bestStart up to but not including bestStart + bestLength. String(decoding:as:) reads them as UTF-8 text and builds a new String.
    • One-line if bodies. Swift always requires braces around an if body, so if need[code] > 0 { missing -= 1 } is the shortest form.
    • Counts that go negative. The entries of need are signed Int values, which is what lets a negative entry stand for "extra copies in the window". With an unsigned type, this would crash on the first subtraction below zero.
    • Two variables on one line. var first = 0, bestStart = 0 declares two separate Int variables.

    Complexity

    Time: O(n + m). Counting the characters of t takes O(m). The main loop runs n times, and the inner while loop only moves first to the right, so across the whole run its body executes at most n times. Converting s to an array is O(n).

    Space: O(1) extra for the 128 counters and a few integers. The chars array is a copy of the input, which allows indexing; the answer string is built once at the end.

    Edge cases and common mistakes

    • Repeated characters in t. s = "a" and t = "aa" gives "", since missing never gets below 1. Counting each character as present or absent, instead of how many times it appears, would give the wrong answer here.
    • Extras in s. s = "aab" and t = "ab" gives "ab": the first a is extra, so the trimming loop drops it.
    • Case matters. s = "AaBb" and t = "ab" gives "aBb", because the capital A and the lowercase a are different characters.
    • The window is all of s. s = "abc" and t = "cba" gives "abc". The order of the characters in t doesn't matter.
    • No answer. s = "xyz" and t = "abc" gives "". bestLength stays at chars.count + 1, which is what the final check looks at.
    • Decrementing missing for every character. Only characters that t still needs count. Without the need[code] > 0 test, missing would reach 0 too early.

    Testing

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