Minimum Window Substring (LeetCode 76): Solution and Explanation
Given a string s and a pattern t, find the shortest contiguous piece of s that contains every character of t, including duplicates as many times as they appear in t. Return an empty string if no such piece exists.
Watch it run step by step
Try your own input and write the code →Intuition
The brute force checks every substring of s, counts its characters, and compares the counts against t. There are O(m²) substrings and each check costs more time on top, so this is far too slow for strings of a hundred thousand characters. Still, it frames the goal: among all windows that cover t, find the shortest.
Two facts about windows make a linear solution possible. If a window covers t, any larger window containing it also covers t. And if a window does not cover t, shrinking it cannot help. That monotonic behavior is the signature of a sliding window. Move a right pointer forward to grow the window until it becomes valid, then move a left pointer forward to shrink it as far as possible while it stays valid, recording the length each time. When it stops being valid, resume growing on the right.
The remaining question is how to test validity cheaply. Recounting the window each time costs O(52) per step, which is fine but unnecessary. The reference code keeps need, the number of distinct characters in t, and have, the number of those characters whose count in the window has reached the required count. have changes only at the exact moment a character's count crosses its target, either going up or going down, so the window is valid exactly when have == need, an O(1) check.
Approach: Sliding window with have and need counters
- Count the characters of
tintocountTand setneed = len(countT),have = 0. - Move
racrosss, addings[r]to thewindowcounts. - If
s[r]is incountTand its window count now equals the required count, incrementhave. - While
have == need, the window is valid. If its lengthr - l + 1beatsresLen, record[l, r]as the best so far. - Still inside that loop, remove
s[l]from the window. If it is a required character whose count dropped below the target, decrementhave. Then advancel. - After the scan, return the recorded slice, or an empty string if
resLenis still infinity.
Step-by-step example
s = "AXBCA", t = "ABC"
countT = {A:1, B:1, C:1}andneed = 3. r = 0 adds A, sohave = 1. r = 1 adds X, which is not required.- r = 2 adds B (
have = 2) and r = 3 adds C (have = 3). The window "AXBC" from 0 to 3 is valid, sores = [0, 3]andresLen = 4. - Shrink: removing A drops its count to 0, below 1, so
have = 2and l = 1. The window is no longer valid. - r = 4 adds A, so
have = 3again. The window "XBCA" has length 4, which does not beat 4. Removing X keeps it valid and l = 2. - The window "BCA" has length 3, so
res = [2, 4]andresLen = 3. Removing B makeshave = 2and l = 3. - The scan ends. Return
s[2:5], which is "BCA".
Code: Python, Java, C++
1class Solution:
2 def minWindow(self, s: str, t: str) -> str:
3 if t == "": return ""
4
5 countT, window = {}, {}
6 for c in t:
7 countT[c] = 1 + countT.get(c, 0)
8
9 have, need = 0, len(countT)
10 res, resLen = [-1, -1], float("infinity")
11 l = 0
12
13 for r in range(len(s)):
14 c = s[r]
15 window[c] = 1 + window.get(c, 0)
16
17 if c in countT and window[c] == countT[c]:
18 have += 1
19
20 while have == need:
21 if (r - l + 1) < resLen:
22 res = [l, r]
23 resLen = r - l + 1
24
25 window[s[l]] -= 1
26 if s[l] in countT and window[s[l]] < countT[s[l]]:
27 have -= 1
28 l += 1
29 l, r = res
30 return s[l : r + 1] if resLen != float("infinity") else ""1class Solution {
2 public String minWindow(String s, String t) {
3 if (t.length() == 0) return "";
4 Map<Character, Integer> countT = new HashMap<>();
5 for (char c : t.toCharArray()) countT.put(c, countT.getOrDefault(c, 0) + 1);
6
7 int have = 0, need = countT.size();
8 int l = 0;
9 int[] res = {-1, -1};
10 int resLen = Integer.MAX_VALUE;
11 Map<Character, Integer> window = new HashMap<>();
12
13 for (int r = 0; r < s.length(); r++) {
14 char c = s.charAt(r);
15 window.put(c, window.getOrDefault(c, 0) + 1);
16
17 if (countT.containsKey(c) && window.get(c).intValue() == countT.get(c).intValue()) {
18 have++;
19 }
20
21 while (have == need) {
22 if ((r - l + 1) < resLen) {
23 res[0] = l; res[1] = r;
24 resLen = r - l + 1;
25 }
26
27 char leftChar = s.charAt(l);
28 window.put(leftChar, window.get(leftChar) - 1);
29 if (countT.containsKey(leftChar) && window.get(leftChar) < countT.get(leftChar)) {
30 have--;
31 }
32 l++;
33 }
34 }
35 return resLen != Integer.MAX_VALUE ? s.substring(res[0], res[1] + 1) : "";
36 }
37}1class Solution {
2public:
3 string minWindow(string s, string t) {
4 if (t == "") return "";
5 unordered_map<char, int> countT;
6 for (char c : t) countT[c]++;
7
8 int have = 0, need = countT.size();
9 int l = 0;
10 int res[2] = {-1, -1};
11 int resLen = INT_MAX;
12 unordered_map<char, int> window;
13
14 for (int r = 0; r < s.length(); r++) {
15 char c = s[r];
16 window[c]++;
17
18 if (countT.count(c) && window[c] == countT[c]) {
19 have++;
20 }
21
22 while (have == need) {
23 if ((r - l + 1) < resLen) {
24 res[0] = l; res[1] = r;
25 resLen = r - l + 1;
26 }
27
28 window[s[l]]--;
29 if (countT.count(s[l]) && window[s[l]] < countT[s[l]]) {
30 have--;
31 }
32 l++;
33 }
34 }
35 return resLen != INT_MAX ? s.substr(res[0], resLen) : "";
36 }
37};Time and space complexity
O(m + n)
Counting t takes O(n). Each character of s enters the window once when r passes it and leaves at most once when l passes it, so the window work is O(m).
O(k)
The two hash maps store counts for at most k distinct characters, which is at most 52 for upper and lowercase letters, so it is effectively constant.
Other approaches
Brute force over all substrings (time O(m² × k), space O(k))
Try every start and end, count the characters in the substring, and keep the shortest one that covers t. It is easy to reason about and useful for testing small cases, but it is far too slow at the given limits.
Filtered sliding window (time O(m + n), space O(m))
First build a list of (index, character) pairs for only the characters of s that appear in t, then run the same window over that shorter list. It does the same asymptotic work but is faster when s contains many irrelevant characters.
Common mistakes
- Incrementing
havewhenever a required character is added, instead of only when its count reaches exactly the target. Extra copies would pushhavepastneed. - Decrementing
havewhenever a required character leaves, instead of only when its count falls below the target. Surplus copies can leave without breaking validity. - Ignoring duplicate characters in
t. Iftis "AA", a window with a single A is not valid, which is why counts are compared, not just membership. - Recording the answer after the shrink loop rather than inside it, which misses the smallest valid window.
Frequently asked questions
Why is minimum window substring O(m + n) and not O(m²)?
Both pointers only move forward. The right pointer visits each index once and the left pointer can pass each index at most once, so the total number of window adjustments is at most 2m, plus O(n) to count t.
What do the have and need variables mean?
need is the number of distinct characters in t. have is how many of those characters currently appear in the window at least as often as t requires. The window covers t exactly when the two are equal.
How are duplicate characters in t handled?
countT stores how many of each character are required, and have only increases when the window count reaches that number. So for t = "AAB" the window must hold two As and one B before it is considered valid.
Can I use an array instead of a hash map?
Yes. Since the input uses only ASCII letters, an array of size 128 indexed by character code works for both counts and is often faster in Java and C++.