Algorithm-Day12-Minimum-Window-Substring-lc-76

🧩 Problem Description

Given two strings s and t, return the minimum window substring of s such that every character in t (including duplicates) is included in the window.

If there is no such substring, return the empty string "".

Example:

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

šŸ’” Brute Force? Not Efficient

Try all substrings of s and check if they contain all characters of t.

  • Time: O(n³)
  • āŒ Way too slow

šŸ’” Optimal Approach: Sliding Window + Hash Map

🧠 Key Ideas

  • Use a sliding window defined by two pointers: left and right
  • Expand the window to the right until all required characters are included
  • Then try to shrink the window from the left to find the minimum
  • Track character counts using hash maps

šŸ”¢ Java Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

class Solution {
public String minWindow(String s, String t) {
if (s.length() < t.length()) return "";

Map<Character, Integer> need = new HashMap<>();
for (char c : t.toCharArray()) {
need.put(c, need.getOrDefault(c, 0) + 1);
}

Map<Character, Integer> window = new HashMap<>();
int left = 0, right = 0;
int valid = 0;
int minLen = Integer.MAX_VALUE;
int start = 0;

while (right < s.length()) {
char c = s.charAt(right++);
if (need.containsKey(c)) {
window.put(c, window.getOrDefault(c, 0) + 1);
if (window.get(c).intValue() == need.get(c).intValue()) {
valid++;
}
}

// Try to shrink the window
while (valid == need.size()) {
if (right - left < minLen) {
minLen = right - left;
start = left;
}

char d = s.charAt(left++);
if (need.containsKey(d)) {
if (window.get(d).intValue() == need.get(d).intValue()) {
valid--;
}
window.put(d, window.get(d) - 1);
}
}
}

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

ā± Time and Space Complexity

  • Time Complexity: O(n + m)
    Where n is length of s, m is length of t
  • Space Complexity: O(m)
    For the hash maps tracking counts

āœļø Summary

  • A classic and foundational sliding window problem
  • Mastering this helps with problems like:
    • lc-567 (Permutation in String)
    • lc-438 (Find All Anagrams)
    • lc-239 (Sliding Window Maximum)

Key challenge: tracking when the window becomes valid and shrinking it optimally.