Minimum Window Containing All Required Characters
StringsAuto-graded · 16 test casesLast updated
Tests sliding window technique with character frequency tracking to find the smallest substring that satisfies multiplicity constraints.
You are given two strings source and target. Find the shortest contiguous substring within source that includes every character from target with at least the required frequency.
If multiple substrings of the same minimum length exist, return the one that appears first. If no valid substring exists, return an empty string.
Constraints:
0 <= len(source), len(target) <= 10^5- Both strings consist of printable ASCII characters
- Characters are case-sensitive:
'A'and'a'are distinct - If
targetis empty, return"" - Character frequency matters: if
targetcontains'a'twice, the result must contain at least two'a'characters
Examples
Example 1
Input: min_window_substring('ADOBECODEBANC', 'ABC')
Output: 'BANC'
Example 2
Input: min_window_substring('a', 'a')
Output: 'a'
Example 3
Input: min_window_substring('a', 'aa')
Output: ''
Hints
Hint 1
Use two pointers to maintain a window that expands to include required characters and contracts to find the minimum length.
Hint 2
Track how many of each required character you still need rather than rescanning the window each time.
Hint 3
Once a valid window is found, try shrinking from the left by removing characters that appear more times than needed.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use a sliding window with two pointers to efficiently explore all candidate substrings without repeatedly checking the entire window.
Maintain a frequency counter tracking how many more of each character we need. For characters in target, the counter starts positive; as we encounter them in source, we decrement the counter. When a counter reaches zero, we have enough of that character. We also track missing, the total count of required characters not yet satisfied.
Expand phase: Move the right pointer forward, adding characters to the window. When we add a character we need (counter > 0), decrement missing.
Contract phase: Once missing reaches zero, the window is valid. Shrink from the left by removing characters that appear more than required (counter < 0). When we cannot shrink further without breaking validity, record this window if it is the shortest found so far.
Then remove one more character from the left, breaking validity, and continue expanding to find the next valid window.
The left pointer never moves backward because any window starting earlier and ending later would be longer than one already examined.
Correctness
For any fixed right endpoint, validity is monotonic in the left endpoint: if [l, r] is valid, then so is [l', r] for all l' ≤ l. Therefore the shortest valid window ending at r begins at the rightmost valid left position. The contraction loop finds exactly that position.
Since we never move left backward, we examine every minimal valid window exactly once. On ties (equal length), we keep the first occurrence because we update only when strictly shorter.
Complexity
- Time: O(|source| + |target|). Each pointer traverses the string at most once, and building the initial counter takes O(|target|).
- Space: O(k), where k is the number of distinct characters across both strings.
Solution
from collections import Counter
def min_window_substring(source, target):
if not target or not source:
return ""
need = Counter(target)
missing = len(target)
left = 0
best_start = 0
best_len = len(source) + 1
for right, char in enumerate(source):
if need[char] > 0:
missing -= 1
need[char] -= 1
while missing == 0:
window_len = right - left + 1
if window_len < best_len:
best_start = left
best_len = window_len
left_char = source[left]
need[left_char] += 1
if need[left_char] > 0:
missing += 1
left += 1
return "" if best_len > len(source) else source[best_start:best_start + best_len]