Minimum Window Containing All Target Characters
StringsAuto-graded · 20 test casesLast updated
Tests the ability to efficiently find the smallest substring containing all required characters using sliding window and hash tables.
You are given two strings source and target. Your task is to locate the smallest contiguous portion of source that includes every character from target, respecting duplicate occurrences.
When multiple substrings share the minimum length, you may return any of them. If no valid substring exists, return an empty string.
Constraints:
1 <= len(source) <= 10^51 <= len(target) <= 10^4- Both strings consist of uppercase and lowercase English letters
- Character comparison is case-sensitive
Examples
Example 1
Input: min_window_with_chars('ADOBECODEBANC', 'ABC')
Output: 'BANC'
Example 2
Input: min_window_with_chars('a', 'aa')
Output: ''
Hints
Hint 1
Consider using two pointers to define a window that expands and contracts as you scan the source string.
Hint 2
Track how many distinct characters in your current window satisfy the target's requirements—this avoids repeatedly comparing full frequency maps.
Hint 3
Once your window becomes valid, try shrinking it from the left while maintaining validity to find the smallest possible window.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core technique is a variable-size sliding window with two pointers that traverse the source string in a single pass. Checking every possible substring would require examining O(n²) candidates, but the sliding window reduces this to linear time.
We maintain:
required: a frequency map of characters needed fromtargetwindow: a frequency map of characters in our current windowformed: count of distinct characters whose frequency requirements are currently satisfiedneeded: total number of distinct characters intarget
The algorithm alternates between two phases:
-
Expand: Move the right pointer forward, adding characters to the window. When a character's count reaches its required frequency, increment
formed. -
Contract: Once
formed == needed, the window is valid. Record it if it's the shortest seen, then shrink from the left. Remove characters one at a time, decrementingformedonly when a character's count drops below its requirement.
By tracking formed incrementally, we avoid comparing entire hash maps on each step—validity is checked in O(1) time.
Correctness
Every optimal window is examined because:
- The right pointer scans every position, ensuring we consider all possible endpoints
- When a valid window exists, the contraction phase explores all valid left boundaries for that right endpoint
- We only skip windows that cannot be valid (insufficient character coverage)
The formed counter correctly handles duplicates: it only increments when a character's count first meets the requirement (not when it exceeds it), and only decrements when falling below the requirement.
Complexity
Time: O(|source| + |target|)
- Building the
requiredmap takes O(|target|) - Each pointer traverses the source at most once, for 2|source| total movements
- Each character addition or removal involves O(1) hash operations
Space: O(k) where k is the alphabet size
- For English letters, k ≤ 52 (constant space)
- We store frequency maps for at most k distinct characters
Implementation
from collections import Counter
def min_window_with_chars(source: str, target: str) -> str:
if not target or len(target) > len(source):
return ""
required = Counter(target)
window = {}
formed = 0
needed = len(required)
left = 0
best_start = 0
best_length = len(source) + 1
for right, char in enumerate(source):
window[char] = window.get(char, 0) + 1
if char in required and window[char] == required[char]:
formed += 1
while formed == needed:
length = right - left + 1
if length < best_length:
best_start = left
best_length = length
outgoing = source[left]
window[outgoing] -= 1
if outgoing in required and window[outgoing] < required[outgoing]:
formed -= 1
left += 1
return "" if best_length == len(source) + 1 else source[best_start:best_start + best_length]