Problem overview
The method minWindow receives two strings, s and t. 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. When no substring works, it returns the empty string "". Uppercase and lowercase letters are different characters, and the tests guarantee a unique answer.
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.
Approach
Checking every substring of s against t is far too slow. A sliding window does it in one pass. The window is the substring from index first to index last. The right end last moves forward one character at a time, adding characters until the window holds everything t asks for. Then the left end first moves forward to cut every character the window can spare, which gives the shortest complete window ending at last. The best of these over all positions of last is the answer.
Both ends only move right, so each character enters and leaves the window at most once. The time is O(n + m) for s of length n and t of length m.
To know whether the window is complete without comparing whole counts every time, the code keeps two things: an array need with the number of copies of each character the window still needs, and a number missing with how many characters of t the window still lacks.
Step by step
- One count per character code.
needhas 128 zeros, indexed by character code. Letters have codes below 128, so this coversatozandAtoZ, each case on its own. - Count the characters of
t. Afor...ofloop overtadds one toneed[c.charCodeAt(0)]for each characterc. A letter that appears twice intends up with a count of 2. missingstarts att.length. It is the number of characters, repeats counted, that the empty window lacks. When it reaches 0, the window is complete.- The window and the best answer.
firstandbestStartstart at 0.bestLengthstarts ats.length + 1, which no real window can reach, so it also means "none found yet". - Add a character. The loop moves
lastovers. The character's code,s.charCodeAt(last), picks its slot inneed. - Did this character help? If
need[code]is above 0, the window was still short of that character, somissinggoes down by one. If it is 0 or below, the window already had enough copies and this one is extra. - Update the count.
need[code]goes down by one in either case. It can become negative, and a negative value means the window holds more of that character thantasks for. - React when the window is complete. When
missing === 0, awhileloop movesfirstforward as long asneed[s.charCodeAt(first)] < 0: the first character is a spare, so removing it keeps the window complete. Each removal adds one back to its count. - Keep the best window. If
last - first + 1is shorter thanbestLength, rememberfirstand the new length. Only the start and the length are stored; the substring is cut once at the end. - Return the result. If
bestLengthis still aboves.length, no window was ever complete and the answer is"". Otherwise it iss.substring(bestStart, bestStart + bestLength).
The solution in TypeScript
class Solution {
minWindow(s: string, t: string): string {
let need: number[] = new Array(128).fill(0);
for (const c of t) {
need[c.charCodeAt(0)]++;
}
let missing = t.length;
let first = 0, bestStart = 0;
let bestLength = s.length + 1;
for (let last = 0; last < s.length; last++) {
let code = s.charCodeAt(last);
if (need[code] > 0) missing--;
need[code]--;
if (missing === 0) {
while (need[s.charCodeAt(first)] < 0) {
need[s.charCodeAt(first)]++;
first++;
}
if (last - first + 1 < bestLength) {
bestStart = first;
bestLength = last - first + 1;
}
}
}
if (bestLength > s.length) return "";
return s.substring(bestStart, bestStart + bestLength);
}
}
Details worth knowing:
for (const c of t)goes over the characters of a string, and eachcis a one-character string. That is whyc.charCodeAt(0)is needed to get a number.charCodeAtreturns UTF-16 code units. For letters this is the ASCII code, below 128. A character outside that range would index past the 128 slots ofneed, so the array suits the lesson's inputs, which have English letters only.substring(i, j)returns the characters from indexiup to, but not including, indexj.- The array stays a plain array of numbers. Reading a slot that was never changed gives
0because offill(0).
Walking through an example
For s = "ADOBECODEBANC" and t = "ABC", each turn ends like this:
last | letter | missing | window | note |
|---|---|---|---|---|
| 0 | A | 2 | "A" | |
| 1 | D | 2 | "AD" | |
| 2 | O | 2 | "ADO" | |
| 3 | B | 1 | "ADOB" | |
| 4 | E | 1 | "ADOBE" | |
| 5 | C | 0 | "ADOBEC" | new best |
| 6 | O | 0 | "ADOBECO" | complete, not shorter |
| 7 | D | 0 | "ADOBECOD" | complete, not shorter |
| 8 | E | 0 | "ADOBECODE" | complete, not shorter |
| 9 | B | 0 | "ADOBECODEB" | complete, not shorter |
| 10 | A | 0 | "CODEBA" | complete, not shorter |
| 11 | N | 0 | "CODEBAN" | complete, not shorter |
| 12 | C | 0 | "BANC" | new best |
At last = 10 the new A makes the first A a spare, so first jumps forward and the window shrinks from the left to "CODEBA". At last = 12 the new C makes the earlier one a spare, and the window shrinks to "BANC", of length 4.
Complexity
Time: O(n + m). Counting t takes m steps. After that last visits each index of s once, and first only moves right, so the while body runs at most n times in total. Space: O(1). need always has 128 slots.
Edge cases and common mistakes
- Repeated letters in
t.s = "a"andt = "aa"gives"":tneeds twoa's andshas one. A set of characters would not catch this; counts do. - No window at all.
s = "abc"andt = "d"gives"", which is whybestLengthstarts above any possible length. - Letter case.
"aAbB"witht = "Ab"gives"Ab", becauseAandahave different codes. - The whole string.
s = "aa"andt = "aa"gives"aa", ands = "a"witht = "a"gives"a". - Counting extras as progress. Lowering
missingfor every matching letter would make it reach 0 too early. Only copieststill needs, those withneed[code] > 0, count. - Shrinking too far. The
whileloop must stop at a character with a count of 0 or more, because dropping it would break the window. - Returning from the loop. The first complete window is rarely the shortest, so keep scanning to the end of
s.
Testing
s | t | Result |
|---|---|---|
"ADOBECODEBANC" | "ABC" | "BANC" |
"a" | "a" | "a" |
"a" | "aa" | "" |
"aa" | "aa" | "aa" |
"abc" | "cba" | "abc" |
"ab" | "b" | "b" |
"bba" | "ab" | "ba" |
"abc" | "d" | "" |
