← Whiteboard questions

Minimum Window Substring

Find the shortest piece of text that holds all needed letters

DSA, Hard, Sliding Window

Which structure or algorithm, and what does it cost.

You get two strings, text and need. Return the shortest substring of text that holds every character of need, as many times as need has it: if need has two A, the substring needs at least two A. If no substring works, return an empty string. If two substrings tie for the shortest length, return the one that starts first.

Examples

Input text = "DABXEBAXCDA", need = "ABC"
Output "BAXC"
Why it is the shortest piece with an A, a B and a C. The start "ABXEBAXC" works too, but it is longer.
Input text = "ABAAB", need = "AAB"
Output "ABA"
Why two A and one B are needed. "ABA", "BAA" and "AAB" all have length 3, so the first one wins.
Input text = "MOON", need = "NOON"
Output ""
Why the text has only one N, so two N cannot be found and the answer is empty.

Constraints

Your answer must contain

Target Aim for O(n + m) time and O(k) memory, with n the length of text, m the length of need and k the number of different letters (at most 52).

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Take one window of the text. How can you tell if it holds everything in need, repeats included?

Hint 2 the approach

Grow the window to the right until it holds everything. Then move the left side in while it still does, to make it as short as possible.

Hint 3 the key step

Count the needed letters still missing. It drops when a needed letter enters and rises when one leaves. At zero the window is valid, so shrink it.

Walkthrough

Full walkthrough brute force to best

Brute force

Check every substring of the text and test if it holds all needed letters, with repeats. Keep the shortest, and the first one on a tie. There are about n^2 / 2 substrings, so for 100,000 letters that is about 5 billion windows, and each check costs more. That is too slow.

Better method

Slide a window with two sides. Move the right side one step at a time. After each step, compare the full letter counts of the window against the counts of need, and shrink from the left while the window is still valid. This is correct, but each comparison costs one step per distinct needed letter, up to 52, so it is O(52 * n).

Best method

Use the same two-sided window, but keep a number missing, the count of needed letters, repeats included, that the window still lacks. A letter that enters and is still needed lowers missing by one. A needed letter that leaves and drops below its need raises it by one. When missing is 0, the window is valid, so record it if it is shorter than the best, then move left in. Keep moving while the window stays valid. Each valid window is the shortest one that ends at the current right side, so no shorter window is skipped. The strict < keeps the earliest window, because the first valid window of a length ends furthest left. Each side moves at most n steps.

Hand trace

Run on text "DABXEBAXCDA" and need "ABC". The right side moves over D, A, B, X, E, B, A, X. After A and B the window still lacks C, so missing is 1. Nothing is valid until position 8 (C). Then the window is "DABXEBAXC", missing 0, length 9. Shrink: drop D, A, B, X, E one at a time. The window stays valid, because a second A at position 6 and a second B at position 5 cover for the first ones. It reaches "BAXC", positions 5 to 8, length 4. Dropping that B leaves no B, so missing is 1 and the shrink stops. The right side moves on, finds nothing shorter, and the answer is "BAXC".

Code

def min_window(text, need):
    want = {}
    for ch in need:
        want[ch] = want.get(ch, 0) + 1
    missing = len(need)
    have = {}
    best_start, best_len = 0, len(text) + 1
    left = 0
    for right, ch in enumerate(text):
        if ch in want:
            have[ch] = have.get(ch, 0) + 1
            if have[ch] <= want[ch]:
                missing -= 1
        while missing == 0:
            if right - left + 1 < best_len:
                best_start, best_len = left, right - left + 1
            c = text[left]
            if c in want:
                have[c] -= 1
                if have[c] < want[c]:
                    missing += 1
            left += 1
    return "" if best_len > len(text) else text[best_start:best_start + best_len]

Time and memory

O(n + m) time, because the right side and the left side each move at most n steps and building the need counts takes m. O(k) memory for the letter counts, where k is the number of distinct letters, at most 52.

Common mistakes

  • Counting distinct letters and not repeats. For need "AAB" a window with one A and one B is not enough.
  • Moving left only once after the window becomes valid. Keep moving while it stays valid, or the answer is not the shortest.
  • Recording the window after moving left. Record first, then remove the letter at left, because the move can break the window.

Related problems

More Sliding Window problems
Minimum Window Substring: walkthrough and Python solution