Minimum Window Substring in Python and Java
In this tutorial, we will learn LeetCode #76: Minimum Window Substring in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.
What Is the Minimum Window Substring Problem?
This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.
For this problem, we will use sliding window because it gives a clean and optimized solution.
Example input: s = "CABEFGECA", t = "ACE" Expected result: Output: "ECA" Explanation: ECA contains A, C, and E.
Beginner-Friendly Idea
The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.
At each step, ask: “What do I already know, and how does the current value change my answer?”
Using our example: s = "CABEFGECA", t = "ACE" Approach: sliding window We update variables step by step until we reach: Output: "ECA"
Why Do We Use This Approach?
A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.
That is why sliding window is useful for this problem.
Step-by-Step Explanation
Let us dry run the algorithm using a custom example.
Step 1 Use this custom example. s = "CABEFGECA", t = "ACE" We will solve it using sliding window. Step 2 Look at the first important value from the example and create the variables needed by the algorithm. current_state = based on the first value answer = not finished yet Step 3 Move to the next useful value and update the state. The algorithm compares the new value with the old state. If the new value improves the answer, we update the answer. Step 4 Continue this process until all useful values are processed. After processing the example, we get: Output: "ECA" Why? ECA contains A, C, and E.
Important Code Logic
The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.
Think like this: old_state = what we knew before current_value = value we are checking now new_state = updated result after using current_value For our example, the final state gives: Output: "ECA"
Example 1
Input: s = "CABEFGECA", t = "ACE" Output: Output: "ECA" Explanation: ECA contains A, C, and E.
Example 2
Input: s = "thisisatest", t = "sat" Output: "ast" Explanation: The smallest window containing s, a, and t is 'ast'.
Python Code
Here is the complete Python solution for LeetCode #76.
from collections import Counter
class MinimumWindowSubstringFinder:
def min_window(self, text, target):
if not text or not target:
return ""
need = Counter(target)
window = {}
have = 0
required = len(need)
left = 0
best = float("inf")
answer = ""
for right, char in enumerate(text):
window[char] = window.get(char, 0) + 1
if char in need and window[char] == need[char]:
have += 1
while have == required:
if right - left + 1 < best:
best = right - left + 1
answer = text[left:right + 1]
left_char = text[left]
window[left_char] -= 1
if left_char in need and window[left_char] < need[left_char]:
have -= 1
left += 1
return answer
finder = MinimumWindowSubstringFinder()
print(finder.min_window("XYABZCBA", "ABC")) # Output: BZC or CBA depending window order, shortest length 3
print(finder.min_window("hello", "xyz")) # Output: ""Java Code
Here is the complete Java solution for LeetCode #76.
import java.util.HashMap;
import java.util.Map;
class MinimumWindowSubstringFinder {
public String minWindow(String text, String target) {
if (text.length() == 0 || target.length() == 0) return "";
Map<Character, Integer> need = new HashMap<>();
for (char ch : target.toCharArray()) need.put(ch, need.getOrDefault(ch, 0) + 1);
Map<Character, Integer> window = new HashMap<>();
int have = 0;
int required = need.size();
int left = 0;
int bestLength = Integer.MAX_VALUE;
int bestStart = 0;
for (int right = 0; right < text.length(); right++) {
char ch = text.charAt(right);
window.put(ch, window.getOrDefault(ch, 0) + 1);
if (need.containsKey(ch) && window.get(ch).intValue() == need.get(ch).intValue()) {
have++;
}
while (have == required) {
if (right - left + 1 < bestLength) {
bestLength = right - left + 1;
bestStart = left;
}
char leftChar = text.charAt(left);
window.put(leftChar, window.get(leftChar) - 1);
if (need.containsKey(leftChar) && window.get(leftChar) < need.get(leftChar)) {
have--;
}
left++;
}
}
return bestLength == Integer.MAX_VALUE ? "" : text.substring(bestStart, bestStart + bestLength);
}
public static void main(String[] args) {
MinimumWindowSubstringFinder finder = new MinimumWindowSubstringFinder();
System.out.println(finder.minWindow("XYABZCBA", "ABC"));
System.out.println(finder.minWindow("hello", "xyz")); // ""
}
}Time and Space Complexity
Time Complexity: O(n)
The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.
Space Complexity: O(n)
The extra space is used for the variables or data structures needed by the optimized approach.
Final Summary
LeetCode #76: Minimum Window Substring becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.