Problem overview
The method 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. If no substring qualifies, it returns an empty string. 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" also contain an A, a B and a C, but they are longer. For s = "a" and t = "aa" the answer is the empty string, 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 for each character code.
Approach: grow until complete, then shrink
Checking every substring of s and counting its letters is far too slow for strings of 100,000 characters. A sliding window avoids the repeated work. The window is the part of s from index first to index last, and both ends only move right.
- Move
lastright, adding one character at a time, until the window contains everythingtasks for. - Once it is complete, move
firstright to drop every character the window can spare. What is left is the shortest complete window that ends atlast. Compare it with the best so far. - Keep moving
last. The window stays complete, so the shrinking step runs again after each addition and finds shorter or equal candidates.
The bookkeeping is a single array, need, with an entry for each character code. need[code] is how many more of that character the window still needs. At the start it holds the counts from t. Adding a character to the window subtracts 1 from its entry, and removing one adds 1. A positive entry means the window is still short of that character. A negative entry means the window holds more copies than t asks for, so one can leave without harm.
A second variable, missing, starts at t.Length and counts how many needed characters the window still lacks. When it reaches 0, the window is complete. It only drops when a character is added whose need entry was positive, because an extra copy of something already covered doesn't help.
Here is the run on s = "ADOBECODEBANC" and t = "ABC", showing the state after each step of last:
last=0 'A' missing=2 first=0 best=""
last=1 'D' missing=2 first=0 best=""
last=2 'O' missing=2 first=0 best=""
last=3 'B' missing=1 first=0 best=""
last=4 'E' missing=1 first=0 best=""
last=5 'C' missing=0 first=0 best="ADOBEC"
last=6 'O' missing=0 first=0 best="ADOBEC"
last=7 'D' missing=0 first=0 best="ADOBEC"
last=8 'E' missing=0 first=0 best="ADOBEC"
last=9 'B' missing=0 first=0 best="ADOBEC"
last=10 'A' missing=0 first=5 best="ADOBEC"
last=11 'N' missing=0 first=5 best="ADOBEC"
last=12 'C' missing=0 first=9 best="BANC"
At last = 5 the window "ADOBEC" becomes complete. At last = 10 a second A arrives, so the first A, and the characters after it that are now spare, can go, and first jumps to 5. The window "CODEBA" ties the best length, but it must be strictly shorter to replace it. At last = 12 the window shrinks to "BANC", which is shorter, and that becomes the answer.
Step by step
- Create
needas anint[]of size 128. Letters have codes below 128, so one entry per code covers a to z and A to Z, each case separately. A new array is filled with zeros. - Count the characters of
twith aforeachloop over itschars, adding 1 toneed[c]. A letter that appears twice is needed twice. - Set
missingtot.Length. When it reaches 0 the window holds all oft. - Declare
firstandbestStartas 0, thenbestLengthass.Length + 1. No window can be that long, so this value means "none found yet". - Loop
lastovers. Stores[last]in anintnamedcodeto get the character's code. - If
need[code] > 0, decreasemissing. This copy was still needed. Then decreaseneed[code]either way: the window now holds one more of this character. - When
missing == 0, shrink from the left whileneed[s[first]] < 0. A negative entry means the first character is surplus. For each one dropped, add 1 back to its entry and movefirstright. - Compare lengths. If
last - first + 1 < bestLength, rememberfirstasbestStartand the length asbestLength. Only two numbers are stored; the substring is cut once at the end. - After the loop, return
""ifbestLengthis still aboves.Length, otherwises.Substring(bestStart, bestLength).
The solution in C#
class Solution {
public string MinWindow(string s, string t) {
int[] need = new int[128];
foreach (char c in t) {
need[c]++;
}
int missing = t.Length;
int first = 0, bestStart = 0;
int bestLength = s.Length + 1;
for (int last = 0; last < s.Length; last++) {
int code = s[last];
if (need[code] > 0) missing--;
need[code]--;
if (missing == 0) {
while (need[s[first]] < 0) {
need[s[first]]++;
first++;
}
if (last - first + 1 < bestLength) {
bestStart = first;
bestLength = last - first + 1;
}
}
}
if (bestLength > s.Length) return "";
return s.Substring(bestStart, bestLength);
}
}
The C# details worth knowing:
- A
charconverts tointimplicitly.int code = s[last];stores the character's code, 65 for'A'and 97 for'a'. The same conversion letsneed[c]use achardirectly as an array index. - Array indexes are checked. A character whose code is 128 or more, such as an accented letter, would throw
IndexOutOfRangeExceptionhere. The lesson guarantees plain English letters, so 128 is enough. Substring(start, length)takes a length, not an end index. The second argument is how many characters to take. Code ported from Java, whosesubstringtakes an end index, gets this wrong.- Strings are immutable.
Substringcreates a new string, which is why the code remembers onlybestStartandbestLengthduring the loop and builds the result once at the end. - The one-line
ifandreturnwithout braces are legal C#, but only the single next statement belongs to theif.
Complexity
Time: O(n + m). Counting t takes m steps. The for loop runs n times, and the inner while only moves first to the right, so across the whole run it executes at most n times. The final Substring copies at most n characters once.
Space: O(1) extra. The need array has a fixed size of 128, whatever the input. The returned string is the output, not working memory.
Edge cases and common mistakes
- No valid window.
s = "a",t = "aa"ands = "abcdef",t = "z"both return"".missingnever reaches 0, sobestLengthkeeps its starting value. - Repeats in
t. Counting distinct letters instead of copies would accept a window with one a fort = "aa". Counting copies, asneeddoes, avoids that. - Case matters.
s = "AbC"witht = "abc"returns"", because'A'and'a'have different codes. - The whole string is the answer.
s = "aa",t = "aa"returns"aa", ands = "aab",t = "aab"returns"aab". - The window can start late.
s = "bba",t = "ab"returns"ba": the extra leading b is dropped by the shrinking loop. - Counting every character as missing. Decreasing
missingwithout checkingneed[code] > 0would count extra copies and report a complete window too early. - Shrinking before the window is complete. The
whileloop must run only whenmissing == 0. Otherwise it could drop characters the window still needs. - Using the length as an end index.
s.Substring(bestStart, bestLength)is correct, while passingbestStart + bestLengthas the second argument would take too many characters or throw.
Testing
s = "ADOBECODEBANC",t = "ABC"gives"BANC".s = "a",t = "a"gives"a".s = "a",t = "aa"gives"".s = "abc",t = "cba"gives"abc".s = "ab",t = "b"gives"b".s = "bba",t = "ab"gives"ba".s = "AbC",t = "abc"gives"".
