Python coding

Smallest window covering every needed character

Given a string s and a non-empty string need, return the shortest contiguous substring of s that contains every character of need, repeats included: if need has two as, the window must hold at least two. Matching is case-sensitive. If several shortest windows tie, return the leftmost; if no window works, return "".

Aim for O(len(s) + len(need)) time.

Besides the tests, one large input (a 2,500-character string) with a ~300 ms limit (scaled to your device's speed): brute force won't pass.

  • min_cover("ADOBECODEBANC", "ABC") → "BANC"
  • min_cover("a", "a") → "a"
  • min_cover("a", "aa") → ""
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Variable-size window: move right until the window covers need, then shrink left while it still covers it, recording each valid window.

Hint 2

Do not compare two maps every step. Keep owed[ch] and one missing total; the window is valid exactly when missing == 0.

Hint 3

A character changes missing only while it is still owed: entering when owed[ch] > 0, or leaving when that makes owed[ch] positive again.

Solution and why it works
pythonO(n + m), n = len(s), m = len(need) · O(k), k = distinct characters
from collections import Counter

def min_cover(s: str, need: str) -> str:
    owed = Counter(need)
    missing = len(need)
    left, start, size = 0, 0, len(s) + 1
    for right, ch in enumerate(s):
        if owed[ch] > 0:
            missing -= 1
        owed[ch] -= 1
        while missing == 0:
            if right - left + 1 < size:
                start, size = left, right - left + 1
            owed[s[left]] += 1
            if owed[s[left]] > 0:
                missing += 1
            left += 1
    return s[start:start + size] if size <= len(s) else ""

Both edges only move forward, so each character enters and leaves the window once: O(n + m) instead of checking O(n²) substrings. One missing counter makes validity an O(1) check. The trap is repeats: an extra copy of a character the window already has enough of must not lower missing, or "aa" would pass as covering "ab".

Related lab: Sliding window, step by step