Start learning free

LESSON 449 OF 671 · SLIDING WINDOW

Minimum Window Substring in Java: O(n + m) Sliding Window

Practice O(n) Read the full explanation

You are given two strings s and t made of English letters. Return the shortest substring of s that contains every character of t, repeats included: if a letter appears twice in t, the substring must contain it at least twice.

If no substring of s contains all the characters of t, return an empty string, "". Uppercase and lowercase letters are different characters.

A substring is a run of consecutive characters of s. The tests are made so that the answer is unique.

 

Example 1:

Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
Explanation: "BANC" contains an A, a B and a C, and no shorter substring contains all three. "ADOBEC" and "CODEBA" contain them too, but they are longer.

Example 2:

Input: s = "a", t = "a"
Output: "a"
Explanation: s itself contains every character of t, and there is nothing shorter to try.

Example 3:

Input: s = "a", t = "aa"
Output: ""
Explanation: t needs two a's, but s has only one, so no substring works. The expected output shows an empty line for it.

 

Constraints:

  • 1 <= s.length, t.length <= 105
  • s and t are made of uppercase and lowercase English letters only (a to z, A to Z).

Note:

Your algorithm should run in O(n + m) time, where n is the length of s and m the length of t, and use O(1) extra space: one count for each character code.

STEP 1 OF 17
    Ctrl + Enter to check

    JAVA · SLIDING WINDOW

    Minimum Window Substring in Java, explained

    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.

    1. Move last right, adding one character at a time, until the window holds everything t asks for.
    2. Move first right as long as the window stays complete. This removes characters the window doesn't need, such as extra copies or letters that aren't in t at all.
    3. That window is the shortest complete one that ends at last. Compare it with the best so far, then continue with last.

    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

    1. Create need, an int[128]. Letters have codes below 128, so one slot per code covers a to z and A to Z separately. Java fills the array with zeros.
    2. Count the characters of t with a for-each loop over t.toCharArray(), adding 1 to need[c]. A char is a number, so it can index the array directly. A letter that appears twice in t ends up needed twice.
    3. Set missing to t.length(): at the start the window lacks every character.
    4. Declare first and bestStart as 0, and bestLength as s.length() + 1. No window can be that long, so that value means "none found yet".
    5. Loop last over s and store the new character in an int named code. Assigning a char to an int keeps its code.
    6. Count it as found when it was needed. If need[code] > 0, t still wanted this character, so decrease missing. If the entry is 0 or less, the copy is extra and missing stays.
    7. Decrease need[code] in every case: the window now holds one more of this character. The entry can go negative.
    8. When missing == 0, shrink from the left. While need[s.charAt(first)] < 0, the window holds more of that character than needed, so drop it: add 1 back to its entry and move first right.
    9. Keep the best window. If last - first + 1 < bestLength, save first as bestStart and the length as bestLength. Only two integers are stored, and the substring is cut once at the end.
    10. Finish. If bestLength is still above s.length(), return "". Otherwise return s.substring(bestStart, bestStart + bestLength). The second argument of substring is 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 t start 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 need positive and the window incomplete.
    • Using a char as an index. need[c] compiles because a char widens to int. It works here because the inputs hold only English letters; a character with a code of 128 or more would throw ArrayIndexOutOfBoundsException.
    • Compare strings with equals. substring makes a new String object, 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" and t = "aa" returns "aa", and s = "a" with t = "aa" returns "". A set of letters would get the second case wrong.
    • Case matters. s = "Ab" and t = "aB" returns "", because a and A have different codes.
    • The window is all of s. s = "abc" and t = "cba" returns "abc".
    • Extra characters at the front. s = "aabdec" and t = "abc" returns "abdec": the first a is a spare and is dropped.
    • Decrementing missing for every matching letter. Only copies that t still needs count, which is why the check need[code] > 0 comes before the decrement of need[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 "".
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free