Shortest Substring Containing All Required Characters
StringsAuto-graded · 21 test casesLast updated
Tests the sliding window pattern with frequency counting to find the shortest substring of one string that covers every character (with multiplicity) of another.
Shortest Substring Containing All Required Characters
You are given two strings, text and pattern. Find the shortest contiguous substring of text that contains every character from pattern, counting duplicates. In other words, if a character appears three times in pattern, your substring must include at least three copies of it.
Return that shortest substring. If no such substring exists, return "".
When two qualifying substrings share the same minimum length, return whichever one starts at the lower index.
Constraints
1 <= len(text), len(pattern) <= 10^5- Both strings contain only English letters (
'a'–'z'and'A'–'Z'). - Matching is case-sensitive:
'a'and'A'are treated as different characters.
Examples
Example 1
Input: shortest_covering_substring('ADOBECODEBANC', 'ABC')
Output: 'BANC'
Example 2
Input: shortest_covering_substring('a', 'a')
Output: 'a'
Example 3
Input: shortest_covering_substring('a', 'aa')
Output: ''
Hints
Hint 1
Build a frequency map of the characters you need to cover from `pattern`. As you expand your window to the right, track how many of those requirements are currently satisfied — without comparing two full maps on every step.
Hint 2
Use a single integer counter that increments only when a character's count in the window first reaches its required amount, and decrements only when it drops below. This gives you an O(1) validity check.
Hint 3
Once the window satisfies all requirements, try to shrink it from the left as far as possible while it remains valid, recording the shortest valid window seen so far. Use a strict less-than comparison when updating the best so ties resolve in favour of the earlier start.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why sliding window works
A brute-force check of every substring costs O(n²) time or worse. The key insight that justifies two pointers is a monotonicity property: if a window covers pattern, any larger window that contains it also covers pattern. That means once a window becomes valid, the only useful move is to shrink it from the left. There is no need to backtrack either pointer.
Algorithm
-
Build
need, a frequency map counting how many times each character appears inpattern. Letrequired = len(need)— the number of distinct characters that must reach their target count. -
Maintain
have, a frequency map for the current window, and an integerformedthat counts how many distinct characters currently meet their requirement. -
Advance
rightacrosstextone character at a time. When a character's count inhaverises to exactly its value inneed, incrementformed. Going above the threshold changes nothing — the window is not "more valid", just larger. -
Whenever
formed == required, the window is valid. Record it if it is shorter than the best seen so far (strict<keeps the earliest start on ties). Then removetext[left]from the window and advanceleft. If that removal drops the count below the requirement, decrementformed— the window is now invalid and we return to expanding. -
Return the recorded best window, or
""if none was found.
Correctness
Every candidate minimal window is examined. When right reaches the end of any minimal window [L, R], left can only have advanced past index i if the window [i, right'] was valid for some earlier right' < R. In that case [i, R] would also be valid, contradicting the minimality of [L, R] (since i > L would give a shorter window). So left <= L at the moment right = R, and the inner shrinking loop will reduce left to exactly L, at which point the window is recorded.
The strict < update rule means the first minimum-length window encountered is kept. Windows are encountered in order of increasing right, and among windows of equal length the one with the smaller right endpoint also has the smaller left endpoint. So the leftmost minimum window is always returned.
Edge cases
len(pattern) > len(text): impossible to cover, return""immediately.- Duplicate characters in
pattern(e.g.pattern = "aa"): the threshold logic requireshave[ch] == need[ch], so the window must contain at least two'a's beforeformedincrements. - A character required by
patternnever appears intext:formednever reachesrequired, the sentinel stays, and we return"". - The entire string is the answer (e.g.
text = "a", pattern = "a"): the window[0, 0]is found and returned as"a". - Characters in
textnot present inpattern: counted inhavebut thech in needguard keeps them from affectingformed.
Complexity
- Time: O(|text| + |pattern|). Building
needis O(|pattern|). Each index oftextis visited at most twice — once byrightand once byleft. Theformedchecks are O(1) per step. - Space: O(k), where k is the size of the alphabet. Here k ≤ 52, so this is effectively O(1) beyond the input. The output slice is O(answer length).
Full solution
from collections import Counter
def shortest_covering_substring(text: str, pattern: str) -> str:
if not text or not pattern or len(pattern) > len(text):
return ""
need = Counter(pattern) # required count per character
have = {} # counts in the current window
required = len(need) # number of distinct chars that must be satisfied
formed = 0 # number of distinct chars currently satisfied
left = 0
best_start = 0
best_len = len(text) + 1 # sentinel: no valid window found yet
for right, ch in enumerate(text):
have[ch] = have.get(ch, 0) + 1
# Only update formed when the count hits the threshold exactly.
if ch in need and have[ch] == need[ch]:
formed += 1
# Shrink from the left while the window still covers pattern.
while formed == required:
window_len = right - left + 1
if window_len < best_len: # strict: keeps the earliest start on ties
best_len = window_len
best_start = left
left_ch = text[left]
have[left_ch] -= 1
if left_ch in need and have[left_ch] < need[left_ch]:
formed -= 1
left += 1
return "" if best_len == len(text) + 1 else text[best_start:best_start + best_len]