โ† Back to Index

๐Ÿ” Minimum Window Substring โ€“ Java Cheat Sheet (One Page)

๐Ÿ“Œ What Is It?

The Minimum Window Substring problem involves finding the smallest substring in a string `s` that contains all characters of another string `t`.

๐Ÿงฑ Pattern Template

public String minWindow(String s, String t) {
    int[] smap = new int[128];
    int[] tmap = new int[128];
    int required = 0;

    for (char c : t.toCharArray()) {
        tmap[c]++;
        if (tmap[c] == 1) required++;
    }

    int left = 0, right = 0, matched = 0;
    int minLen = Integer.MAX_VALUE;
    int minStart = 0;

    while (right < s.length()) {
        char c = s.charAt(right);
        smap[c]++;
        if (tmap[c] > 0 && smap[c] == tmap[c]) matched++;

        while (matched == required) {
            if (right - left + 1 < minLen) {
                minLen = right - left + 1;
                minStart = left;
            }
            char lc = s.charAt(left);
            smap[lc]--;
            if (tmap[lc] > 0 && smap[lc] < tmap[lc]) matched--;
            left++;
        }
        right++;
    }

    return minLen == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLen);
}

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example: Minimum Window Substring

Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"

๐Ÿ’ก Pro Tips