Given two strings s and t of lengths m and n respectively, 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 "".
The testcases will be generated such that the answer is unique.
Example 1:
Input: s = "ADOBECODEBANC", t = "ABC" Output: "BANC" Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.
Example 2:
Input: s = "a", t = "a" Output: "a" Explanation: The entire string s is the minimum window.
Example 3:
Input: s = "a", t = "aa" Output: "" Explanation: Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string.
Constraints:
m == s.lengthn == t.length1 <= m, n <= 105s and t consist of uppercase and lowercase English letters.Follow up: Could you find an algorithm that runs in O(m + n) time?
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you need to find the shortest piece of a long word that contains a specific set of required letters. The brute force approach works by examining every single possible slice of the long word from start to finish to see if it contains everything you need.
Here's how the algorithm would work step-by-step:
def min_window(source_string, target_string):
from collections import Counter
shortest_slice = ""
minimum_length = float('inf')
target_counts = Counter(target_string)
string_length = len(source_string)
# We test every conceivable starting point to evaluate all possible window positions
for start_index in range(string_length):
for end_index in range(start_index, string_length):
current_slice = source_string[start_index:end_index + 1]
current_counts = Counter(current_slice)
# We must verify if the current slice satisfies all character quantity demands
is_valid = True
for character, count in target_counts.items():
if current_counts[character] < count:
is_valid = False
break
if is_valid:
# We track the minimum length to ensure we isolate the absolute shortest valid window
if len(current_slice) < minimum_length:
minimum_length = len(current_slice)
shortest_slice = current_slice
return shortest_sliceInstead of checking every possible section of text, we use a smart sliding window strategy that expands and shrinks to find the shortest valid segment. We dynamically track the needed items as we sweep through the text, ensuring we find the best answer efficiently.
Here's how the algorithm would work step-by-step:
def min_window(source_string, target_string):
from collections import Counter
required_counts = Counter(target_string)
unique_target_items = len(required_counts)
window_start_index = 0
matched_items_count = 0
current_window_counts = {}
minimum_length = float('inf')
substring_start_index = 0
# Expand the right side of the window to include new characters until all required items are gathered.
for window_end_index, current_character in enumerate(source_string):
current_window_counts[current_character] = current_window_counts.get(current_character, 0) + 1
if current_character in required_counts and current_window_counts[current_character] == required_counts[current_character]:
matched_items_count += 1
# Shrink the left side while the window remains valid to find the shortest possible segment.
while matched_items_count == unique_target_items:
current_window_size = window_end_index - window_start_index + 1
if current_window_size < minimum_length:
minimum_length = current_window_size
substring_start_index = window_start_index
left_character = source_string[window_start_index]
current_window_counts[left_character] -= 1
if left_character in required_counts and current_window_counts[left_character] < required_counts[left_character]:
matched_items_count -= 1
window_start_index += 1
# Return the smallest valid substring found or an empty string if no valid window existed.
if minimum_length == float('inf'):
return ""
return source_string[substring_start_index:substring_start_index + minimum_length]| Case | How to Handle |
|---|---|
| String t is longer than string s | Return an empty string immediately since it is impossible for s to contain all characters of t. |
| String t is empty | Return an empty string because an empty requirement has no valid minimum window substring. |
| String s is empty | Return an empty string since no characters are available to form a window. |
| No valid window exists containing all characters of t | Return an empty string after the sliding pointer traversal finishes without a successful match. |
| String t contains duplicate characters | Track character frequencies using a hash map to ensure all duplicate counts are fully satisfied in the window. |
| Multiple valid minimum windows of the same length exist | The problem statement guarantees a unique minimum length window so this scenario will not occur. |
| String s and t consist of single identical characters | The sliding window correctly captures the single-character match and returns it in constant time. |
| Extremely large input strings s and t | The two-pointer sliding window approach scales efficiently with an optimal linear time complexity of O(N + M). |