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.
lastmoves right one character at a time, adding that character to the window.- Once the window holds everything
tasks for,firstmoves right as long as the character it leaves behind is a spare, that is, the window holds more copies of it thantneeds. - 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
- Create
need.make([]int, 128)gives 128 zeros, one per ASCII code. Letters have codes below 128, and each case has its own codes. - Count the characters of
t. Aforloop withrangeovertyields the index and the rune; the index is skipped with_. Each rune is a number, so it can indexneeddirectly, andneed[c]++counts it. A letter that appears twice intis needed twice. - Set
missingtolen(t). It is the number of characters oftthe window still lacks. - Set up the bookkeeping.
firstis the left end andbestStartis where the best window starts; both are 0.bestLengthstarts atlen(s) + 1, which is longer than any window, so it also means that nothing has been found yet. - Grow the window. The loop moves
lastacrosss.code := s[last]is the byte for the new character. - Is this character still needed? If
need[code] > 0,tstill wanted it, somissinggoes down. If the count is 0 or negative, the window already has enough copies and this one is extra. - Update the count.
need[code]--records that the window holds one more copy. It can become negative, which marks a spare. - Act only when complete. If
missing == 0, trim from the left withfor need[s[first]] < 0: while the first character is a spare, put its count back withneed[s[first]]++and movefirstright. - Compare with the best. If
last-first+1is belowbestLength, store the newbestStartandbestLength. Only two numbers are kept, and the substring is cut once, at the end. - Return. If
bestLengthis still abovelen(s), no window was ever complete, so return"". Otherwise returns[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
rangeover a string gives runes. Infor _, c := range t,cis arune(an alias forint32), 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 abyte(uint8). Both types are integers, so both index the slice without a conversion.- Slicing a string.
s[i:j]holds the bytes fromiup to but not includingj. The result shares memory withs, 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, 0declares twointvariables 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"andt = "aabc"gives"abca". Counting only which letters are present, and not how many, would accept"abc". - No answer.
s = "a"andt = "aa", ors = "abc"andt = "d", give"". - Case matters.
s = "Ab"andt = "aB"gives"", becauseaandAhave different codes. tas long ass.s = "aa"andt = "aa"returns the whole string.- Decreasing
missingfor extra copies. Without theneed[code] > 0test, a spare copy would reducemissingand 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.
bestLengthstarting atlen(s) + 1is 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"".
