Tightest Segment Covering a Required Letter Multiset
StringsAuto-graded · 27 test casesLast updated
Find the shortest contiguous piece of a text that includes all letters of a target, with repeats and case mattering, using a sliding window with counts and earliest-start tie-breaking.
You are given a string text and a string target. Find the shortest contiguous segment of text that covers target.
A segment covers target if, for every letter, the segment contains at least as many copies of that letter as target does. For example, if target has the letter b three times, the segment must contain b at least three times. Letters are case-sensitive, so A and a are different letters.
Return that segment as a string.
Rules
- A segment may contain letters that are not in
target, and may contain more copies of a needed letter than required. - If several covering segments share the minimum length, return the one that begins at the smallest index in
text. - If no segment of
textcoverstarget(for instance, whentargetis longer thantext), return the empty string"".
Constraints
1 <= len(text) <= 10^51 <= len(target) <= 10^5textandtargetcontain only uppercase and lowercase English letters.
Examples
Example 1
Input: shortest_covering_segment('XAYBZAXB', 'ABX')
Output: 'AXB'
Example 2
Input: shortest_covering_segment('cabwba', 'ab')
Output: 'ab'
Example 3
Input: shortest_covering_segment('Aa', 'AA')
Output: ''
Hints
Hint 1
Checking every substring is too slow for 10^5 characters. Think about a window with two moving ends, where extending the right end can only help coverage and shrinking the left end can only hurt it.
Hint 2
Keep a count of how many copies of each target letter are still needed (it can go negative when the window has extras), plus a single counter of the total number of unmatched target characters, so checking coverage is O(1).
Hint 3
Once the window covers the target, advance the left end while the character there is unneeded or surplus. Record the window only if it is strictly shorter than the best so far, which keeps the earliest start on ties. Store start and length, and slice once at the end.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use a variable-size sliding window text[left..right].
Maintain two pieces of state:
need[c]: how many more copies of lettercthe window still requires. It starts as the count ofcintarget, decreases whencenters the window and increases whencleaves. A negative value means the window has surplus copies. Letters not intargetare never tracked.missing: the total number of target characters not yet matched. It drops only when a letter enters whileneed[c] > 0. The window covers the target exactly whenmissing == 0.
Move right across text. Whenever missing becomes 0:
- Shrink: advance
leftpast every character that is not intargetor has a surplus (need[c] < 0, restoring it by incrementing). Stop at the first character withneed[c] == 0; it is essential. - Record:
text[left..right]is now the shortest covering window ending atright. Save its start and length only if it is strictly shorter than the best so far. - Release: drop the essential character (
need += 1,missing += 1,left += 1) so the window becomes invalid by exactly one character and the search continues.
Why it is correct
- The shrink loop always stops at or before
right, because the character just added atrightbrought its need to exactly 0 and shrinking never pushes it above 0. - No optimal window is skipped.
leftpasses a position only if the window starting after it is still covering (so any window starting there and ending later is longer), or if the shortest covering window starting there was already recorded. Hence whenrightreaches the end of an optimal window,leftis at or before its start, and shrinking lands exactly on its start. - Both pointers only move forward, so recorded windows appear in increasing start order. The strict
<comparison keeps the first (earliest-start) window among those of minimum length. - Counts, not a set, handle repeated letters, and case-sensitivity follows from using the raw characters as keys.
Complexity
- Time: O(|text| + |target|), since each pointer advances at most |text| times.
- Space: O(k) where k is the number of distinct letters in
target(at most 52), so effectively O(1). Only the best start and length are stored, with one slice at the end.
Reference solution
def shortest_covering_segment(text: str, target: str) -> str:
need = {}
for ch in target:
need[ch] = need.get(ch, 0) + 1
missing = len(target)
if missing > len(text):
return ""
best_len = len(text) + 1
best_start = 0
left = 0
for right, ch in enumerate(text):
if ch in need:
if need[ch] > 0:
missing -= 1
need[ch] -= 1
if missing == 0:
while True:
c = text[left]
if c in need:
if need[c] == 0:
break
need[c] += 1
left += 1
if right - left + 1 < best_len:
best_len = right - left + 1
best_start = left
need[text[left]] += 1
missing += 1
left += 1
return "" if best_len > len(text) else text[best_start:best_start + best_len]