Minimum Window Substring
Find the shortest part of a string that contains every character of another string, repeats included.
Given two strings ststs""
Example 1
Output: "BANC"
Example 2
Output: "a"
Example 3
Output: ""
Explanation: t needs two a's, but s has only one.
The Idea
Imagine scanning a line of text for the shortest stretch that uses every letter on a short list. In Example 1 the text is "ADOBECODEBANC"ADOBECBANC
Repeats count. In Example 3, t"aa""a"
How do we find the shortest stretch without checking every substring? A string of 13 characters already has 91 substrings, and checking one means counting its letters. Turn the question around instead: for each position where a stretch could end, what is the shortest stretch that ends there and still holds A, B and C? Look at the picture below.
The box in each row marks a stretch, and the row label says where it ends. In the row labelled right = 5ADOBECright = 10CODEBAright = 12BANC
Now look at where the boxes start: 0, then 5, then 9. The start never moves back. A stretch from position 5 to position 10 holds A, B and C, so the longer stretch from 5 to 12 holds them too. The best start for an end at 12 is therefore at 5 or later.
So two markers are enough: rightlefts
Solution Approach
Turning that idea into code means settling four things: how to tell quickly whether the window holds all of t
Counting what the window still needs
How do we know the window holds every character of tneed[c]cctt = "ABC"
missingttmissingtt
needneed['A']
Widening the window
What happens when rightneedmissingmissing
Narrowing the window
Once missingleftleftneedmissingleft
In the row labelled right = 10CODEBA
Remembering the shortest
Where does the answer come from? Right before each removal, the window still covers tt""
Java Solution
The method minWindow
- First, count the characters of
intot , an array of 128 counts, and setneed tomissing .t.length() - Set
to 0.left andbestStart remember the shortest window found;bestLen starts atbestLen , larger than any real length.Integer.MAX_VALUE - A loop moves
overright , one character at a time. Each step lowers the character's count ins , and lowersneed if the count was above 0 before.missing - Inside, a
loop runs as long aswhile is 0. It records the window frommissing toleft if it is shorter thanright . Then it removes the character atbestLen : it raises that count, raisesleft if the count is now above 0, and movesmissing forward.left - After the loop, return
if"" is stillbestLen , or else the substring of lengthInteger.MAX_VALUE starting atbestLen .bestStart
The main"AAB"t = "AB""baacba"t = "aab"t"abc"t = "A"[]
public class MinimumWindowSubstring {
public static String minWindow(String s, String t) {
int[] need = new int[128]; // how many more of each character the window needs
for (char c : t.toCharArray()) {
need[c]++;
}
int missing = t.length(); // characters of t not yet covered
int left = 0;
int bestStart = 0;
int bestLen = Integer.MAX_VALUE;
for (int right = 0; right < s.length(); right++) {
if (need[s.charAt(right)]-- > 0) {
missing--; // this character was still needed
}
while (missing == 0) { // the window covers t: try to shrink it
if (right - left + 1 < bestLen) {
bestLen = right - left + 1;
bestStart = left;
}
if (++need[s.charAt(left)] > 0) {
missing++; // removing it uncovers a needed character
}
left++;
}
}
return bestLen == Integer.MAX_VALUE ? "" : s.substring(bestStart, bestStart + bestLen);
}
public static void main(String[] args) {
System.out.println("[" + minWindow("ADOBECODEBANC", "ABC") + "]");
System.out.println("[" + minWindow("a", "a") + "]");
System.out.println("[" + minWindow("a", "aa") + "]");
System.out.println("[" + minWindow("AAB", "AB") + "]");
System.out.println("[" + minWindow("baacba", "aab") + "]");
System.out.println("[" + minWindow("abc", "A") + "]");
}
}
Running it prints:
[BANC]
[a]
[]
[AB]
[baa]
[]
[BANC]right = 12[]t = "aa"missingbestLen
Look at [AB]rightmissingAAmissingmissingtAA
[baa]t = "aab""abc"t
The two tests in the code look alike but differ. need[...]-- > 0++need[...] > 0
The original implementation,
Complexity
The work is one pass over tneeds
- Time: O(m + n), where m is the length of
and n the length oft . Countings takes m steps.t visits each of the n characters once, andright only moves forward, so all the runs of theleft loop together take at most n steps.while - Space: O(1) besides the answer.
always has 128 counts, however long the strings are, and the rest is a few numbers.need
When the window must hold exactly the letters of t