↻one more pass.
Sliding window · Hard

Minimum Window Substring: the idea to remember.

Find the shortest ASCII substring containing every required character, including duplicates.

Solve on LeetCode ↗

The core insight

Expand until all required occurrences are covered; then repeatedly shrink while coverage holds.

Why it works

Each valid right endpoint is paired with its shortest valid window by shrinking. Every left endpoint moves forward at most once.

The mistake to avoid

Track multiplicities, not just distinct characters, and shrink with a loop rather than a single check.

Time: O(n + m)Space: O(1), ASCII counters

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

String minWindow(String s, String t) {
    if (t.isEmpty()) return "";
    int[] need = new int[128]; // ASCII input contract.
    for (char c : t.toCharArray()) need[c]++;
    int missing = t.length(), left = 0, start = 0, best = Integer.MAX_VALUE;
    for (int right = 0; right < s.length(); right++) {
        if (need[s.charAt(right)]-- > 0) missing--;
        while (missing == 0) {
            if (right - left + 1 < best) { start = left; best = right - left + 1; }
            if (++need[s.charAt(left++)] > 0) missing++;
        }
    }
    return best == Integer.MAX_VALUE ? "" : s.substring(start, start + best);
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.