Problem overview
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 a's, the substring needs at least two a's. When no substring qualifies, the function returns the empty string. Uppercase and lowercase letters are different characters, and the tests are built so that the shortest 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 = "a" the answer is "a", and for s = "a" and t = "aa" it is "", because s has only one a.
The statement asks for O(n + m) time, where n is the length of s and m the length of t, and O(1) extra space: one counter for each character code.
Approach: grow until complete, then shrink as far as possible
Trying every substring of s and counting its letters would take far too long for strings of 100,000 characters. A sliding window from index first to index last does it in one pass.
The right end last moves across s one character at a time, and each character joins the window. Once the window holds every character t asks for, it is complete. A complete window stays complete as it grows, so there is no point in growing it further before looking at it. Instead the left end first moves right and drops every character the window can spare. What is left is the shortest complete window that ends at last. The code compares its length with the best one found so far and moves on.
To know what the window can spare, the code keeps one counter per character code, need. It starts as the number of copies of each character that t contains. When a character enters the window, its counter goes down by one. A positive counter means the window still lacks copies of that character. A counter of zero means the window holds exactly the required number. A negative counter means the window holds extras, and one of them may leave without breaking it.
A second variable, missing, starts at t.length and counts how many required characters the window still lacks. It drops by one only when a character that was still needed arrives, so a window is complete exactly when missing is 0. This avoids checking all the counters each time.
Here is the trace for s = "ADOBECODEBANC" and t = "ABC", showing only the steps where the window is complete:
| last | window after shrinking | result |
|---|---|---|
| 5 | ADOBEC | new best, length 6 |
| 6 | ADOBECO | longer than the best |
| 7 | ADOBECOD | longer than the best |
| 8 | ADOBECODE | longer than the best |
| 9 | ADOBECODEB | longer than the best |
| 10 | CODEBA | same length as the best |
| 11 | CODEBAN | longer than the best |
| 12 | BANC | new best, length 4 |
At last = 3, missing is 1: the window ADOB has an A and a B but no C. The window becomes complete at index 5, when the C arrives.
Step by step
- Create
need.Array.fill(128)(0)gives one counter per character code below 128. All letters, in both cases, have codes in that range, and each case gets its own counter. - Count the characters of
t. Aforloop adds 1 toneed(c.toInt)for eachc.toIntgives the character's code, and a letter that appears twice intis counted twice. - Set
missingtot.length. The empty window lacks every character oft. - Declare
firstandbestStart, both 0.firstis the window's left end andbestStartis where the best window begins. - Set
bestLengthtos.length + 1. No window can be that long, so this value means that none has been found. - Grow the window.
for (last <- s.indices)adds the character atlastin each turn. Its code goes intocode. - Update
missingfirst. Ifneed(code)is above 0,tstill wanted this character, somissinggoes down. Otherwise the character is an extra andmissingstays. - Then subtract 1 from
need(code). This order matters: the test must see the counter before the character is counted. - When
missing == 0, shrink. Awhileloop runs whileneed(s(first).toInt) < 0, that is, while the first character is an extra. Each pass gives its copy back withneed(s(first).toInt) += 1and movesfirstright. - Compare lengths. If
last - first + 1is less thanbestLength, store the window's start and length. - Return the result. If
bestLengthis still aboves.length, no window was complete and the function returns"". Otherwises.substring(bestStart, bestStart + bestLength)is the answer.
The solution in Scala
class Solution {
def minWindow(s: String, t: String): String = {
val need = Array.fill(128)(0)
for (c <- t) {
need(c.toInt) += 1
}
var missing = t.length
var first = 0
var bestStart = 0
var bestLength = s.length + 1
for (last <- s.indices) {
val code = s(last).toInt
if (need(code) > 0) missing -= 1
need(code) -= 1
if (missing == 0) {
while (need(s(first).toInt) < 0) {
need(s(first).toInt) += 1
first += 1
}
if (last - first + 1 < bestLength) {
bestStart = first
bestLength = last - first + 1
}
}
}
if (bestLength > s.length) return ""
s.substring(bestStart, bestStart + bestLength)
}
}
The Scala details worth a closer look:
ChartoInt.'A'.toIntis 65 and'z'.toIntis 122, so a 128-element array has a slot for every letter. Bothc.toIntands(last).toIntreturn a code point as anInt.- A one-line
if.if (need(code) > 0) missing -= 1has no braces and noelse. As a statement it just runs the assignment when the condition holds. - Substring end is exclusive.
s.substring(i, j)returns the characters at indexesiup to but not includingj, so the end isbestStart + bestLength. - The early
return.return ""leaves the method with aString. The last line has noreturnbecause the final expression of the block is the result. - Immutable strings. The window is only a pair of indexes. The substring is cut once, at the end, so no intermediate strings are built.
Complexity
Time: O(n + m). Counting the characters of t takes m steps. The loop over s runs n times, and the inner while loop moves first right by one on each pass and never moves it back, so over the whole call its body runs at most n times.
Space: O(1). The counter array has 128 elements whatever the input. The only other storage is a few integers.
Edge cases and common mistakes
- No valid window.
s = "abcdef"witht = "xyz"returns"", and so doess = "a"witht = "aa". - Repeated characters in
t. Witht = "aa", two copies are needed.s = "aab"witht = "aab"returns"aab", ands = "AAB"witht = "AA"returns"AA". - Case matters.
s = "aAbB"witht = "Ab"returns"Ab": the lowercase a before it is a different character. - The order of characters doesn't matter.
s = "abc"witht = "cba"returns"abc". - Counting an extra copy as progress. If
missingdropped for every arriving character that appears int, a window with three a's and no b could look complete whentis"ab". Testingneed(code) > 0before the decrement lets only the copies thattstill wants count. - Swapping the two updates. Decrementing
need(code)first makes the testneed(code) > 0miss the last needed copy. - Dropping a needed character. The shrink loop stops at a counter of 0, not below it: a counter at 0 means that the window holds exactly the copies
trequires. - Returning on the first complete window. The first window found is rarely the shortest. The search continues to the end of
s.
Testing
s = "ADOBECODEBANC",t = "ABC"gives"BANC".s = "a",t = "a"gives"a".s = "a",t = "aa"gives"".s = "ab",t = "b"gives"b".s = "aAbB",t = "Ab"gives"Ab".s = "abcdef",t = "xyz"gives"".
