Minimum Window Substring

Find the shortest part of a string that contains every character of another string, repeats included.

Given two strings s and t, return the shortest substring of s that contains every character of t, including repeats. A substring is a run of consecutive characters. If no substring of s qualifies, return the empty string "". Both strings hold only English letters, and upper and lower case count as different characters. When there is an answer, only one substring has the shortest length.

Example 1
Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
Example 2
Input: s = "a", t = "a"
Output: "a"
Example 3
Input: s = "a", t = "aa"
Output: ""
Explanation: t needs two a's, but s has only one.
Solution

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" and the list is A, B and C. The stretch ADOBEC at the start has an A, a B and a C, so it works, and it is six characters long. BANC near the end works too, with only four characters, and nothing shorter does.

Repeats count. In Example 3, t is "aa", so a stretch must hold two a's. The string "a" has only one, so the answer is the empty string.

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 string ADOBECODEBANC with positions 0 to 12. In the row labelled right = 5 the box covers ADOBEC, length 6. In the row labelled right = 10 it covers CODEBA, length 6. In the row labelled right = 12 it covers BANC, length 4.

The box in each row marks a stretch, and the row label says where it ends. In the row labelled right = 5, the stretch ends at the first C. It must start at position 0, because the only A so far is there, so it is ADOBEC. In the row labelled right = 10, it ends at the second A and can start as late as the C at position 5: CODEBA, still six characters. In the row labelled right = 12, it ends at the last C and starts at the B at position 9: BANC, the answer.

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: right for the end and left for the start, and both only walk forward through s. The stretch between two markers that move like this is called a window, and the technique is called a sliding window. Sliding Window Basics shows it on simpler problems.

Solution Approach

Turning that idea into code means settling four things: how to tell quickly whether the window holds all of t, how to widen it, how to narrow it, and how to remember the shortest one.

Counting what the window still needs

How do we know the window holds every character of t without recounting it at each step? Keep two running counts. need[c] says how many more copies of the character c the window still needs. It starts as the number of times c appears in t, so for t = "ABC" it is 1 for A, B and C and 0 for every other letter.

missing says how many characters of t, counting repeats, are not in the window yet. It starts at the length of t, 3 here. When missing reaches 0, the window holds all of t. We say the window covers t.

need is an array of 128 counts, one for each character code from 0 to 127. That range, called ASCII, includes all English letters, so a character can serve as its own index, as in need['A'].

Widening the window

What happens when right moves onto a new character? Its count in need goes down by one. If the count was above 0 before, the window was still waiting for that character, so missing goes down too. If the count was 0 or less, the character is a spare. Its count drops below 0, which records the spare, and missing stays the same. D, O and E in the first row of the picture are spares like this.

Narrowing the window

Once missing is 0, how far can left move? Remove the character at left by raising its count in need by one. If the count is now above 0, the window has lost a character it needed. missing goes up and the narrowing stops. Otherwise the character was a spare, and left can keep going.

In the row labelled right = 10, the window first runs from D at position 1 to A at position 10. Removing D, O and E is free. Removing the B at position 3 is free too, because the B at position 9 is still inside. Removing the C at position 5 would leave no C, so the window stops at CODEBA.

Remembering the shortest

Where does the answer come from? Right before each removal, the window still covers t, so that is the moment to compare its length with the best so far. Two numbers are enough to remember the best window: where it starts and how long it is. If no window ever covers t, the best length is never set, and the answer is "".

Java Solution

The method minWindow works in these steps:

  1. First, count the characters of t into need, an array of 128 counts, and set missing to t.length().
  2. Set left to 0. bestStart and bestLen remember the shortest window found; bestLen starts at Integer.MAX_VALUE, larger than any real length.
  3. A loop moves right over s, one character at a time. Each step lowers the character's count in need, and lowers missing if the count was above 0 before.
  4. Inside, a while loop runs as long as missing is 0. It records the window from left to right if it is shorter than bestLen. Then it removes the character at left: it raises that count, raises missing if the count is now above 0, and moves left forward.
  5. After the loop, return "" if bestLen is still Integer.MAX_VALUE, or else the substring of length bestLen starting at bestStart.

The main method runs the three examples and three more cases. "AAB" with t = "AB" checks that a spare A does not count as the B. Then come "baacba" with t = "aab", where t has a repeat, and "abc" with t = "A", where the only letter differs in case. Each result is printed in brackets, so an empty string shows as [].

Java
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:

Output
[BANC]
[a]
[]
[AB]
[baa]
[]

[BANC] is the window from the row labelled right = 12 in the picture. The [] on the third line is Example 3: t = "aa" asks for two a's, missing stops at 1, and bestLen is never set.

Look at [AB] on the fourth line. When right reaches the second A, the count for A is already 0, so missing stays at 1 and AA does not count as a cover. That is why the code checks the count before lowering missing. We also ran a version that lowers missing for every character that appears in t, needed or not, and it returned AA for this input.

[baa] holds both a's and the b that t = "aab" asks for. The last line is empty because "abc" has a lowercase a, and t asks for an uppercase A.

The two tests in the code look alike but differ. need[...]-- > 0 compares the count before it is lowered, which asks "was this character still needed?". ++need[...] > 0 compares the count after it is raised, which asks "is it needed now that it left?".

The original implementation, MinimumWindowSubstring.java, is on GitHub.

Complexity

The work is one pass over t to fill need, then one forward walk of each marker over s.

  • Time: O(m + n), where m is the length of t and n the length of s. Counting t takes m steps. right visits each of the n characters once, and left only moves forward, so all the runs of the while loop together take at most n steps.
  • Space: O(1) besides the answer. need always has 128 counts, however long the strings are, and the rest is a few numbers.

When the window must hold exactly the letters of t and nothing else, see Permutation in String.