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 as, the substring needs at least two. When no substring qualifies, it returns "". Uppercase and lowercase letters are different characters.
For s = "ADOBECODEBANC" and t = "ABC" the answer is "BANC": it has an A, a B and a C, and nothing shorter does. For s = "a" and t = "aa" the answer is "", because s has only one a.
Approach: grow until complete, then shrink as far as possible
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 with two indexes, first and last, that only move right.
- Move
lastright, adding one character at a time, until the window holds everythingtasks for. - Move
firstright as long as the window stays complete. This removes characters the window doesn't need, such as extra copies or letters that aren't intat all. - That window is the shortest complete one that ends at
last. Compare it with the best so far, then continue withlast.
To know whether the window is complete without rescanning it, the code keeps one number per character code in an array need. need[code] is how many more copies of that character the window still needs. It starts as the count in t. Adding a character to the window lowers its entry by one; removing it raises it by one. A positive entry means the window is short of that character, zero means it has exactly enough, and a negative entry means it holds spare copies. A second counter, missing, tracks the total number of characters still lacking, so the window is complete when missing is 0.
Step by step
- Create
need, anint[128]. Letters have codes below 128, so one slot per code coversatozandAtoZseparately. Java fills the array with zeros. - Count the characters of
twith a for-each loop overt.toCharArray(), adding 1 toneed[c]. Acharis a number, so it can index the array directly. A letter that appears twice intends up needed twice. - Set
missingtot.length(): at the start the window lacks every character. - Declare
firstandbestStartas 0, andbestLengthass.length() + 1. No window can be that long, so that value means "none found yet". - Loop
lastoversand store the new character in anintnamedcode. Assigning acharto anintkeeps its code. - Count it as found when it was needed. If
need[code] > 0,tstill wanted this character, so decreasemissing. If the entry is 0 or less, the copy is extra andmissingstays. - Decrease
need[code]in every case: the window now holds one more of this character. The entry can go negative. - When
missing == 0, shrink from the left. Whileneed[s.charAt(first)] < 0, the window holds more of that character than needed, so drop it: add 1 back to its entry and movefirstright. - Keep the best window. If
last - first + 1 < bestLength, savefirstasbestStartand the length asbestLength. Only two integers are stored, and the substring is cut once at the end. - Finish. If
bestLengthis still aboves.length(), return"". Otherwise returns.substring(bestStart, bestStart + bestLength). The second argument ofsubstringis exclusive.
The solution in Java
class Solution {
public String minWindow(String s, String t) {
int[] need = new int[128];
for (char c : t.toCharArray()) {
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.charAt(last);
if (need[code] > 0) missing--;
need[code]--;
if (missing == 0) {
while (need[s.charAt(first)] < 0) {
need[s.charAt(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 understanding:
- One array does two jobs. Characters that are not in
tstart at 0, so as soon as one enters the window its entry becomes negative. The shrinking loop treats it as spare and drops it from the left edge when it gets there. That is how leading junk disappears. - The window stays complete while shrinking. The loop stops at the first character whose entry is 0, which the window needs. Dropping it would make
needpositive and the window incomplete. - Using a
charas an index.need[c]compiles because acharwidens toint. It works here because the inputs hold only English letters; a character with a code of 128 or more would throwArrayIndexOutOfBoundsException. - Compare strings with
equals.substringmakes a newStringobject, so if you test the method yourself,result.equals("BANC")is the right check;==compares references.
Complexity
Time: O(n + m), where n is the length of s and m the length of t. Counting t takes m steps. After that last visits each index of s once, and first only moves right, so the shrinking loop's body runs at most n times in total. The final substring copies at most n characters.
Space: O(1) extra for the 128-slot array and the integers. The returned string is the output.
Edge cases and common mistakes
- Repeated letters in
t.s = "aa"andt = "aa"returns"aa", ands = "a"witht = "aa"returns"". A set of letters would get the second case wrong. - Case matters.
s = "Ab"andt = "aB"returns"", becauseaandAhave different codes. - The window is all of
s.s = "abc"andt = "cba"returns"abc". - Extra characters at the front.
s = "aabdec"andt = "abc"returns"abdec": the firstais a spare and is dropped. - Decrementing
missingfor every matching letter. Only copies thattstill needs count, which is why the checkneed[code] > 0comes before the decrement ofneed[code]. - Shrinking before the window is complete. The shrink loop belongs inside the
if (missing == 0)block. - Returning
s.substring(bestStart, bestLength). The second argument is an end index, not a length.
Testing
s = "ADOBECODEBANC",t = "ABC"returns"BANC".s = "a",t = "a"returns"a".s = "a",t = "aa"returns"".s = "ab",t = "b"returns"b".s = "aabdec",t = "abc"returns"abdec".s = "Ab",t = "aB"returns"".
