Back to Dashboard
Minimum Window Substring
HardProblem Statement
Given a string and a pattern, find the smallest substring in the given string which has all the character occurrences of the given pattern.
Examples
Example 1:
- Input:
s = "ADOBECODEBANC", t = "ABC" - Output:
"BANC"
Approach 1 Sliding Window:
class Solution {
public String minWindow(String s, String t) {
int windowStart = 0, matched = 0;
var out = "";
var charMap = new HashMap<Character, Integer>();
for (var i = 0; i < t.length(); i ++) {
var ch = t.charAt(i);
charMap.put(ch, charMap.getOrDefault(ch, 0) + 1);
}
for (var windowEnd = 0; windowEnd < s.length(); windowEnd ++) {
var chEnd = s.charAt(windowEnd);
if (charMap.containsKey(chEnd)) {
charMap.put(chEnd, charMap.get(chEnd) - 1);
if (charMap.get(chEnd) == 0) {
matched ++;
}
}
while (matched == charMap.size() && windowStart < s.length()) {
if (windowEnd - windowStart + 1 < out.length() || out.isEmpty()) {
out = s.substring(windowStart, windowEnd + 1);
}
var chStart = s.charAt(windowStart);
if (charMap.containsKey(chStart)) {
if (charMap.get(chStart) == 0) {
matched --;
}
charMap.put(chStart, charMap.get(chStart) + 1);
}
windowStart ++;
}
}
return out;
}
}