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
lastright one character at a time. Each turn adds one character to the window. - When the window holds everything
tasks for, movefirstright 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
- Copy the bytes into an array. A Swift
Stringcan't be indexed with an integer, solet chars = Array(s.utf8)gives the codes of the letters, withchars[i]for indexi. - Create
needas 128 zeros. Letters have codes below 128, so one entry per code covers both cases separately. - Count the characters of
twith aforloop overt.utf8. - Add 1 to
need[Int(c)]for each one.cis aUInt8, andInt(c)converts it to anIntso it can index the array. A letter that appears twice intis needed twice. - Set
missingtot.utf8.count, the number of characters the window still lacks. - Declare
firstandbestStartas 0.firstis the window's left end, andbestStartis where the shortest complete window so far starts. - Declare
bestLengthaschars.count + 1. No window can be longer thans, so this value means that none has been found yet. - Grow the window with a
forloop wherelastgoes over0..<chars.count. - Store the new character's code in
code. - If
need[code]is above 0, the window needed this character, so subtract 1 frommissing. A value of 0 or less means the window already has all the copiestasks for, and this one is extra. - Subtract 1 from
need[code]in every case, because the window now holds one more of it. The entry can go below 0. - Check whether
missing == 0. Once the window is complete, the next steps trim it. - Trim the left end with a
whileloop that runs whileneed[Int(chars[first])] < 0. A negative entry means the window has more of that character thantneeds, so dropping one keeps the window complete. - Drop the first character: add 1 to its
needentry and add 1 tofirst. - Compare lengths. If
last - first + 1 < bestLength, this window is the shortest complete one so far. - Remember it by setting
bestStartandbestLength. Only the start and the length are kept, and the substring is cut once at the end. - Return
""ifbestLengthis still abovechars.count, which means that no window was ever complete. - Otherwise cut the best window out of
charsand 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:
utf8gives bytes.s.utf8is a view of the string asUInt8values, one per ASCII letter. That is why the loop variablecneedsInt(c)before it can be used as an index.- Slicing an array.
chars[bestStart..<bestStart + bestLength]is anArraySlice<UInt8>, the codes frombestStartup to but not includingbestStart + bestLength.String(decoding:as:)reads them as UTF-8 text and builds a newString. - One-line
ifbodies. Swift always requires braces around anifbody, soif need[code] > 0 { missing -= 1 }is the shortest form. - Counts that go negative. The entries of
needare signedIntvalues, 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 = 0declares two separateIntvariables.
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"andt = "aa"gives"", sincemissingnever 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"andt = "ab"gives"ab": the first a is extra, so the trimming loop drops it. - Case matters.
s = "AaBb"andt = "ab"gives"aBb", because the capital A and the lowercase a are different characters. - The window is all of
s.s = "abc"andt = "cba"gives"abc". The order of the characters intdoesn't matter. - No answer.
s = "xyz"andt = "abc"gives"".bestLengthstays atchars.count + 1, which is what the final check looks at. - Decrementing
missingfor every character. Only characters thattstill needs count. Without theneed[code] > 0test,missingwould 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".
