Algo-Sim › Sliding Window
Minimum Window Substring
Hard · Sliding Window · step through it in Java, Python and C++ on your own input
Return the shortest substring of s that contains every character of t (with multiplicity), or "" if none does.
Problem
Given strings s and t, return the shortest contiguous substring of s that contains every character of t, counting repeats (two as in t need two as in the window). If no such substring exists, return the empty string. The answer is unique when it exists.
Constraints
- 1 ≤ s.length, t.length ≤ 10⁵
- s and t contain uppercase and lowercase English letters
- Follow-up: O(s.length + t.length)
Edge cases to test
- t longer than s:
"" - t with repeated letters:
"aa" - The answer is all of s
Follow-up questions
- How do you know the window is valid in O(1)?
- Keep a
missingcounter of characters of t still needed; decrement when a needed one enters and increment when it leaves. - What if s is much longer than t?
- First filter s to the positions of characters that appear in t, then slide over that shorter list.
Solution
Java
public String minWindow(String s, String t) {
Map<Character, Integer> need = new HashMap<>();
for (char c : t.toCharArray()) need.merge(c, 1, Integer::sum);
Map<Character, Integer> window = new HashMap<>();
int required = need.size(), formed = 0;
int left = 0, bestLen = Integer.MAX_VALUE, bestStart = 0;
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
window.merge(c, 1, Integer::sum);
if (need.containsKey(c) && window.get(c).equals(need.get(c))) {
formed++;
}
while (formed == required) {
if (right - left + 1 < bestLen) {
bestLen = right - left + 1;
bestStart = left;
}
char out = s.charAt(left);
window.merge(out, -1, Integer::sum);
if (need.containsKey(out) && window.get(out) < need.get(out)) {
formed--;
}
left++;
}
}
return bestLen == Integer.MAX_VALUE ? "" : s.substring(bestStart, bestStart + bestLen);
}Python
from collections import Counter
def min_window(s, t):
need = Counter(t)
window = {}
required, formed = len(need), 0
left, best_len, best_start = 0, float("inf"), 0
for right in range(len(s)):
c = s[right]
window[c] = window.get(c, 0) + 1
if c in need and window[c] == need[c]:
formed += 1
while formed == required:
if right - left + 1 < best_len:
best_len = right - left + 1
best_start = left
out = s[left]
window[out] -= 1
if out in need and window[out] < need[out]:
formed -= 1
left += 1
return "" if best_len == float("inf") else s[best_start:best_start + best_len]C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string minWindow(string &s, string &t) {
unordered_map<char, int> need = {};
for (char c : t)
need[c] += 1;
unordered_map<char, int> window = {};
int required = int(need.size()), formed = 0;
int left = 0, bestLen = INT_MAX, bestStart = 0;
for (int right = 0; right < int(s.size()); right++) {
char c = s[right];
window[c] += 1;
if (need.count(c) && (window[c] == need[c])) {
formed++;
}
while (formed == required) {
if (right - left + 1 < bestLen) {
bestLen = right - left + 1;
bestStart = left;
}
char out = s[left];
window[out] += -1;
if (need.count(out) && window[out] < need[out]) {
formed--;
}
left++;
}
}
return bestLen == INT_MAX ? "" : s.substr(bestStart, (bestStart + bestLen) - (bestStart));
}
};
More Sliding Window problems
- Best Time to Buy and Sell Stock (Easy)
- Minimum Size Subarray Sum (Medium)
- Maximum Sum Subarray of Size K (Easy)
- Max Consecutive Ones III (Medium)
- Fruit Into Baskets (Medium)
- Longest Substring Without Repeating Characters (Medium)
- Longest Repeating Character Replacement (Medium)
- Permutation in String (Medium)
- Find All Anagrams in a String (Medium)
- Subarrays with K Different Integers (Hard)