Problem overview
minWindow(s, t) receives two strings and 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, the function returns "". Uppercase and lowercase letters are different characters, and the tests are built so that the answer is unique.
For s = "ADOBECODEBANC" and t = "ABC" the answer is "BANC". "ADOBEC" and "CODEBA" also contain an A, a B and a C, but they are longer.
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 per character code.
Approach: grow until complete, then shrink
Checking every substring of s against t would be far too slow for strings of 100,000 characters. A sliding window avoids it. The window is the substring from index first to index last.
- Move
lastto the right, adding one character at a time, until the window holds everythingtasks for. - Once it does, move
firstto the right while the window can spare its first character, so that it is as short as possible for this right end. - Compare that window with the best one so far and keep the shorter.
Both ends only move right, so each index is visited at most twice and the loop does O(n) work. Counting the characters of t costs O(m).
The bookkeeping uses one array, need, plus a number, missing:
need[code]is how many more of that character the window still needs. It starts as the number of times the character appears int. Adding a character to the window lowers it, and removing one raises it.- A value below 0 means the window holds more of that character than
tasks for. One of those extras can leave without breaking the window. missingis how many characters oftthe window still lacks, counting repeats. It starts att.length, and the window is complete when it reaches 0.
Here is the run on s = "ADOBECODEBANC" and t = "ABC". The last column is the best window found so far.
last | added | missing | first | best |
|---|---|---|---|---|
| 0 | A | 2 | 0 | none |
| 3 | B | 1 | 0 | none |
| 5 | C | 0 | 0 | ADOBEC |
| 9 | B | 0 | 0 | ADOBEC |
| 10 | A | 0 | 5 | ADOBEC |
| 12 | C | 0 | 9 | BANC |
At last = 10 the second A arrives, so the first A, the D, O, B and E in front of the C can all leave, and first jumps to 5. At last = 12 a second C arrives, which frees the leading C and everything up to index 9, and the window becomes "BANC".
Step by step
- Create
needwith 128 zeros. Letters have character codes below 128, so one slot per code covers a to z and A to Z, each case separately. - Loop over
twithfor...of, taking one charactercat a time. - Count each character by adding 1 at
need[c.charCodeAt(0)]. A letter that appears twice intends up needed twice. - Set
missingtot.length. The empty window lacks every character oft. - Declare
firstandbestStartat 0: the window's left end, and where the best window starts. - Set
bestLengthtos.length + 1. No window can be that long, so the value means that none has been found yet. - Loop with
lastover the indexes ofs. Each turn adds one character. - Store the character's code in
code. - Check whether the window needed it. If
need[code]is above 0,tstill asked for this character, somissinggoes down. If it is 0 or less, this one is an extra. - Lower
need[code]in both cases, since the window now holds one more of that character. It can go negative. - Test for a complete window with
missing === 0. - Shrink from the left while
need[s.charCodeAt(first)] < 0. A negative count means the first character is an extra. - Drop it: raise its count by one and move
firstright. - Compare with the best window: its length is
last - first + 1. - Remember it by storing
bestStartandbestLength. The substring itself is cut only once, at the end. - After the loop, if
bestLengthis still aboves.length, no window was ever complete, so return"". - Otherwise cut the answer with
substring(bestStart, bestStart + bestLength).
The solution in JavaScript
class Solution {
minWindow(s, t) {
let need = 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);
}
}
The details worth a closer look:
for...ofover a string gives one character at a time, each as a one-character string. That is why the code callscharCodeAt(0)onc.- The array index is a number.
needis indexed by character code, so"A"and"a"land in different slots (65 and 97), which is exactly the case sensitivity the problem wants. substring(i, j)returns the characters from indexiup to but not includingj, so the end isbestStart + bestLength.- One-line
if.if (need[code] > 0) missing--;is valid without braces. Only the single statement that follows belongs to theif, so the next line,need[code]--;, runs every time. - The order of the two updates matters. The test
need[code] > 0must come beforeneed[code]--. Reversed, a needed character would look like an extra.
Why does the window stay complete while it shrinks? The loop only drops a character whose count is negative, which means the window holds more copies than t needs. After the drop, the count is still at least 0 for every character, so nothing t asks for has been lost. The loop stops at the first character the window can't spare.
Complexity
Time: O(n + m). Counting t takes m steps. After that, last moves across s once, and first only moves right, so the shrinking loop's body runs at most n times in total.
Space: O(1). The array has 128 entries whatever the input. The answer string is cut once at the end.
Edge cases and common mistakes
- Repeats in
t.s = "a"witht = "aa"returns"":tneeds two a's andshas only one.s = "aa"witht = "aa"returns"aa". - Letter case.
s = "Ab"witht = "aB"returns"", becauseAis nota. - A missing letter.
s = "abc"witht = "d"returns"", andbestLengthkeeps its starting value. tequalssor is a single character.s = "a"witht = "a"returns"a".- Extras at the front.
s = "aaab"witht = "ab"returns"ab", not"aaab": the shrinking loop drops the spare a's. - Counting distinct letters instead of copies. Setting
missingto the number of different letters intwould accept"a"fort = "aa". - Returning the length or the start only. The function returns the substring, so both pieces of data are kept until the end.
- Shrinking when the window isn't complete. The shrinking loop belongs inside the
missing === 0check. Outside it, characters thattstill needs could be dropped.
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 = "Ab",t = "aB"gives"".s = "abc",t = "d"gives"".s = "bba",t = "ab"gives"ba".s = "aaab",t = "ab"gives"ab".
