Shortest Covering Substring
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
You are given two strings of English letters: a source text s and a pattern t. Return the shortest contiguous slice of s that includes every character from t at least as many times as that character appears in t.
def shortest_covering_substring(s: str, t: str) -> str:
Rules for a valid slice:
- Multiplicity matters: Repeated characters in
trequire at least the same count inside the chosen slice ofs. - Order does not matter: Characters inside the slice may appear in any order, with arbitrary extra characters between them.
- Case-sensitive comparison: Uppercase and lowercase letters (such as
'R'and'r') count as distinct characters. - Ties and missing matches: If multiple slices achieve the same shortest length, you may return any one of them. When no slice of
scoverst, return"".
Examples
Example 1
- Input:
s = "PRACXTYRPKCT",t = "PRT" - Output:
"TYRP" - Explanation: Several slices of
scontain'P','R', and'T'— including"PRACXT"(length 6) and"RPKCT"(length 5) — whiles[5:9] = "TYRP"covers all three characters in length 4, which is minimal.
Example 2
- Input:
s = "spark",t = "rrk" - Output:
"" - Explanation: The pattern requires two copies of
'r'plus one'k', whereasscontains only a single'r', so no covering slice exists.
Constraints
1 <= len(s) <= 10^51 <= len(t) <= 10^4- Both
sandtcontain only ASCII English letters ('a'–'z'and'A'–'Z').
Step-by-step walkthrough
Understand the goal and what "covering" means
Given a source string
sand a target stringt, we want the shortest contiguous substring ofsthat contains every character oftat least as many times as it appears int.- Duplicates count: If
t = "AAB", a valid substring must contain at least two'A's and one'B'(so"AB"is not enough, while"BAXA"works). - Order inside the substring does not matter:
"CBA"covers"ABC". - Case matters:
'A'and'a'are distinct characters. - No match / quick exit: If no substring covers
t(for example,len(t) > len(s), orslacks enough copies of a required letter as in Example 2), return"". If several substrings tie for shortest, returning any one of them is valid.
- Duplicates count: If
Why brute force is too slow — and how a sliding window fixes it
A brute-force solution tries every starting index
leftfrom0tolen(s) - 1and scansrightrightward untils[left : right + 1]coverst. Becauselen(s)can be100,000, nested loops take up toO(|s|^2)(~10^10) operations, which is far too slow. Notice why brute force wastes work: whenleftadvances from0to1, it throws away everything it just counted acrosss[1..right]and scans those exact same characters again!Instead, we maintain a single sliding window
s[left : right + 1]controlled by two pointers (leftandright) that only ever move forward:1. EXPAND right until window covers t: [P R A C X T] Y R P K C T ^left ^right (covers "PRT"!) 2. SHRINK left while still covering t: P [R A C X T] Y R P K C T ^left ^right (lost 'P' -> resume step 1)Why does
leftnever need to move backward? Wheneverleftsteps past an indexawhile atright = r, we have already checkeds[a : r + 1](the shortest valid window starting ata). Any future window starting atawith a largerrightwould only be longer, soacan never produce a strictly shorter answer later. Becauseleftandrighteach advance at most|s|times, the entire scan takes linear time!Track coverage in O(1) using `need` and `missing`
How do we tell in
O(1)time whether our window currently coverst, without looping over all 52 uppercase/lowercase letters on every step? We track two pieces of state:need: a dictionary mapping each character intto how many more copies the window still needs. Crucially,need[ch]is allowed to go negative — a negative value like-1simply means the window currently holds1extra (surplus) copy ofch!missing: a single integer counting how many total character copies fromt(duplicates included) are still uncovered. Whenmissing == 0, the window coverst!
Watch how
need['B']andmissingbehave whent = "BC"(need = {'B': 1, 'C': 1},missing = 2) ons = "BBAC":Start: need={'B': 1, 'C': 1}, missing=2 Read 'B' (idx 0): need['B'] was > 0 -> missing becomes 1; need['B'] becomes 0 Read 'B' (idx 1): need['B'] is 0 -> surplus 'B'! missing stays 1; need['B'] becomes -1 Read 'A' (idx 2): 'A' not in need -> ignored Read 'C' (idx 3): need['C'] was > 0 -> missing becomes 0 (VALID!); need['C'] becomes 0 Shrink 'B' (idx 0): need['B'] rises -1 -> 0 (not > 0, so we only dropped a surplus 'B'! missing stays 0!) Shrink 'B' (idx 1): need['B'] rises 0 -> 1 (> 0! We lost our required 'B', so missing becomes 1 -> stop)First, let's write the small helper that counts
t:from typing import Dict def count_required_chars(t: str) -> Dict[str, int]: """Build a frequency map of how many copies of each character `t` requires.""" need: Dict[str, int] = {} for ch in t: need[ch] = need.get(ch, 0) + 1 return needExpand `right`, shrink `left`, and record the shortest window
Now we write the two-pointer loop inside
shortest_covering_substring(s, t):- When
in_char = s[right]enters: ifin_char in need, checkif need[in_char] > 0: missing -= 1before subtracting1fromneed[in_char]. - While
missing == 0:- Compute
window_len = right - left + 1and update(best_start, best_len)before advancingleft(while the window is still valid!). Storing two integers(best_start, best_len)instead of slicings[left : right + 1]on every improvement avoids copying long strings inside the loop, andbest_len == 0cleanly producess[0:0] == ""when no answer exists. - Remove
out_char = s[left]: ifout_char in need, add1toneed[out_char]first, and then checkif need[out_char] > 0: missing += 1.
- Compute
def shortest_covering_substring(s: str, t: str) -> str: # Quick exit: empty inputs or a pattern longer than the text can never be covered. if not s or not t or len(t) > len(s): return "" # need: dict[str, int] mapping each char in t -> how many more copies the window still lacks. # A value < 0 means the current window holds surplus copies of that character. need = count_required_chars(t) # missing: total character copies from t (counting duplicates) still needed for a valid window. missing = len(t) # Track the best window by (start_index, length) to avoid O(N) string slicing inside the loop. # best_len == 0 acts as a sentinel meaning "no valid window found yet" (s[0:0] == ""). best_start = 0 best_len = 0 left = 0 # Phase 1: Expand the window to the right one character at a time. for right in range(len(s)): in_char = s[right] if in_char in need: # Only decrement `missing` if this copy fills an unmet need (not a surplus copy). if need[in_char] > 0: missing -= 1 need[in_char] -= 1 # Phase 2: While s[left : right + 1] covers all of t, record it and shrink from the left. while missing == 0: window_len = right - left + 1 # Strict `<` keeps the earliest shortest window (any shortest window is valid). if best_len == 0 or window_len < best_len: best_start = left best_len = window_len out_char = s[left] if out_char in need: need[out_char] += 1 # Only if need[out_char] rises above 0 did we lose a required copy (not a surplus one). if need[out_char] > 0: missing += 1 left += 1 return s[best_start : best_start + best_len]- When
Walk through Example 1 (`s = "PRACXTYRPKCT"`, `t = "PRT"`)
Initially
need = {'P': 1, 'R': 1, 'T': 1}andmissing = 3:Index: 0 1 2 3 4 5 6 7 8 9 10 11 Char: P R A C X T Y R P K C T 1. right=0..5 -> window "PRACXT" hits missing=0! - Record "PRACXT" (len 6, best="PRACXT"). - Shrink left=0 ('P'): need['P'] becomes 1 -> missing=1 (stop shrinking, left=1). 2. right=6..7 -> at right=7 ('R'), window "RACXTYR" has two 'R's, so need['R'] = -1, missing still 1. 3. right=8 ('P') -> window "RACXTYRP" hits missing=0! - Shrink left=1 ('R'): need['R'] rises -1 -> 0, so missing stays 0! - Shrink left=2..4 ('A', 'C', 'X') down to left=5 ("TYRP", len 4 < 6 -> best="TYRP"). - Dropping left=5 ('T') raises need['T'] from 0 to 1 -> missing=1 (stop shrinking, left=6). 4. right=9..11 ('T') -> window "YRPKCT" hits missing=0! - Shrink left=6 ('Y', len 6) -> left=7 ("RPKCT", len 5, not < 4). - Dropping left=7 ('R') raises need['R'] to 1 -> missing=1 (stop). Final answer: s[5:9] == "TYRP".Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def count_required_chars(t: str) -> Dict[str, int]: """Build a frequency map of how many copies of each character `t` requires.""" need: Dict[str, int] = {} for ch in t: need[ch] = need.get(ch, 0) + 1 return need def shortest_covering_substring(s: str, t: str) -> str: # Quick exit: empty inputs or a pattern longer than the text can never be covered. if not s or not t or len(t) > len(s): return "" # need: dict[str, int] mapping each char in t -> how many more copies the window still lacks. # A value < 0 means the current window holds surplus copies of that character. need = count_required_chars(t) # missing: total character copies from t (counting duplicates) still needed for a valid window. missing = len(t) # Track the best window by (start_index, length) to avoid O(N) string slicing inside the loop. # best_len == 0 means no valid window has been found yet (and s[0:0] returns ""). best_start = 0 best_len = 0 left = 0 # Phase 1: Expand the window to the right one character at a time. for right in range(len(s)): in_char = s[right] if in_char in need: # Only decrement `missing` if this copy fills an unmet need (not a surplus copy). if need[in_char] > 0: missing -= 1 need[in_char] -= 1 # Phase 2: While s[left : right + 1] covers all of t, record it and shrink from the left. while missing == 0: window_len = right - left + 1 # Strict `<` keeps the earliest shortest window (any shortest window is valid). if best_len == 0 or window_len < best_len: best_start = left best_len = window_len out_char = s[left] if out_char in need: need[out_char] += 1 # Only if need[out_char] rises above 0 did we lose a required copy (not a surplus one). if need[out_char] > 0: missing += 1 left += 1 return s[best_start : best_start + best_len]✅ Submit now — all tests should pass.
Intuition & how it works
Imagine stretching a rubber band across s using your left finger (left) and right finger (right) while holding a checklist of every letter required by t. You slide your right finger forward one character at a time, crossing letters off the checklist until every required letter (including duplicates) sits inside the band; then you slide your left finger forward to tighten the band as far as possible until dropping one more character would leave the checklist incomplete, and repeat. This expand-then-tighten scan is called a sliding window (maintaining a contiguous slice bounded by two pointers left and right that never move backward), paired with a hash map (a key-value dictionary counting how many copies of each target character the window still lacks).
Why do simpler ideas fall short? Checking every possible (start, end) substring from scratch takes O(|s|^2) time — around 10^10 checks when |s| = 10^5 — because advancing start by 1 discards all the counts already gathered and rescans the same characters again. Storing t in a plain set instead of a frequency dictionary also breaks whenever t has repeated letters like "aa", because a set cannot tell one 'a' apart from two 'a's.
Let's trace s = "MPPKTM" and t = "MPT" (need = {'M': 1, 'P': 1, 'T': 1}, missing = 3):
1. Expand right=0..4 ("MPPKT"):
- 'M' (0): need['M']=0, missing=2
- 'P' (1): need['P']=0, missing=1
- 'P' (2): extra 'P'! need['P']=-1 (surplus), missing stays 1
- 'K' (3): ignored
- 'T' (4): need['T']=0, missing=0 -> VALID! Record "MPPKT" (len 5).
Shrink left=0 ('M'): need['M'] becomes 1 -> missing=1 (stop, left=1).
2. Expand right=5 ('M') -> window is s[1..5] = "PPKTM":
- 'M' (5): need['M']=0, missing=0 -> VALID! Record "PPKTM" (len 5, not < 5).
- Shrink left=1 ('P'): need['P'] rises -1 -> 0 (still <= 0, so missing stays 0!).
- Window is now s[2..5] = "PKTM": VALID! Record "PKTM" (len 4 < 5 -> new best!).
- Shrink left=2 ('P'): need['P'] rises 0 -> 1 -> missing=1 (stop).
Return "PKTM".
Complexity
Let |s| be the length of s, |t| be the length of t, and k be the number of distinct characters in t (k <= 52 for uppercase and lowercase English letters).
- Time:
O(|s| + |t|). Buildingneedscanstonce inO(|t|)time. In the sliding window,rightadvances|s|times andleftonly ever increments (left <= |s|), so the innerwhileloop executes at most|s|total steps across the entire run — making each pointer step amortizedO(1)(meaning even though onerightstep may trigger manyleftsteps at once, the average work perrightstep over the whole string is constant). Finally, slicing the winning substring once at the end takesO(best_len) <= O(|s|)time. - Space:
O(k)auxiliary memory (at most52entries inneed), plusO(best_len)for the returned substring.
Edge cases
- Pattern longer than text (
len(t) > len(s)): Returns""immediately before allocating the dictionary. - Insufficient character count or absent character (
s = "spark",t = "rrk"as in Example 2, ors = "PRACXTYRPKCT",t = "PRZ"):missingnever reaches0,best_lenstays0, ands[0:0]returns"". - Entire string
sis the sole covering window (s = "cba",t = "abc"): Initializingbest_len = 0(rather thanlen(s)) ensures a window of lengthlen(s)is properly recorded instead of mistaken for "no match". - Duplicate letters in
t(s = "abxxaxb",t = "aab"):missingstarts at3andneed['a'] = 2, so"ab"leavesmissing == 1and scanning continues until"abxxa". - Surplus copies of target letters (
s = "BBBAC",t = "BC"): Extra'B's driveneed['B']negative (-2), allowingleftto discard two'B's while keepingmissing == 0to reach"BAC". - Case sensitivity (
s = "aAbBA",t = "AB"):'a'and'A'hash as distinct keys, returning"BA".
Common mistakes
- Decrementing
missingon every occurrence of a target character: Ift = "AB"ands = "AAB", decrementingmissingtwice on the two'A's hitsmissing == 0on"AA"before'B'ever appears! Only decrementmissingwhenneed[in_char] > 0. - Incrementing
missingwhenever any target character leavesleft: Dropping a surplus'B'(need['B']rising from-1to0) keeps the window valid; only incrementmissingwhenneed[out_char] > 0after adding1. - Recording
best_lenafter incrementingleft(or usingright - leftinstead ofright - left + 1): Off-by-one bugs either chop off the first required character or drop the last character. - Initializing
best_len = len(s)with strict<: Fails whenever the shortest valid substring is all ofsitself (window_len == len(s)is not< len(s)). Usebest_len = 0(orlen(s) + 1) as the "not found" sentinel. - Slicing
best = s[left : right + 1]inside thewhileloop: Turns anO(|s|)algorithm intoO(|s|^2)if many shrinking windows have lengths proportional to|s|.
Alternative approaches
- Two frequency maps (
required+window_counts+formed_unique): Track how many distinct characters havewindow_counts[ch] >= required[ch], and shrink whileformed_unique == len(required). EquivalentO(|s| + |t|)time andO(k)space, using non-negative counts at the cost of a second dictionary. - Filtered index list: Pre-filter
sinto[(index, ch) for index, ch in enumerate(s) if ch in need]and run the sliding window on that compressed list. Helpful when|s|is huge and almost none of its characters appear int.
Follow-up questions
- What changes are needed if both inputs can contain arbitrary Unicode text, including accents and multi-code-point emojis? Because Python dictionaries hash arbitrary strings rather than indexing a fixed 52-slot ASCII array,
needalready handles any Unicode code point (the numeric ID assigned to a symbol, such asU+00E9for'é'). However, visually identical text like'é'can be encoded either as one precomposed code point or as'e'+ a combining acute accent, so first apply Unicode normalization (unicodedata.normalize("NFC", s)and ont— converting canonically equivalent sequences into one standard form). If user-perceived characters like multi-code-point family emojis (👨👩👧) must count as single units, segment both strings into grapheme clusters (user-visible characters that may span multiple code points, e.g., with theregexlibrary's\X) and run the exact same sliding window over the list of clusters. - Why does the two-pointer scan still run in linear time even when a single step of
righttriggers many steps ofleft? BuildingneedtakesO(|t|)time and extra space isO(k)wherek <= |t|is the number of unique characters int. Even though one step ofrightcan trigger nearly|s|increments ofleft— for instance, ons = "bbbb...ba"andt = "a",rightwalks|s| - 1steps doing zero shrinks and then the final step at'a'advancesleftacross all|s| - 1'b's in one burst —leftnever resets or moves backward, so total pointer advances across the entire run are bounded by2 * |s|, givingO(|s| + |t|)total time. - How would you find the shortest valid window if
swere a multi-gigabyte file on disk that cannot fit in RAM? Becauseleftandrightboth move strictly left-to-right, open two sequential buffered file readers on the file — a leading handle at character offsetrightand a trailing handle atleft— while keeping onlyneed,missing,left,right, and(best_start, best_len)inO(k)RAM! Both file handles stream forward sequentially at disk throughput without storing the window text in memory, and once scanning finishes you seek tobest_startto read out thebest_lencharacters (ifsarrives from an unseekable network stream rather than a file on disk, spill the active window[left..right]to a rolling temporary ring buffer on local disk).
Follow-up questions
- What changes are needed if both inputs can contain arbitrary Unicode text, including accents and multi-code-point emojis?
- Why does the two-pointer scan still run in linear time even when a single step of `right` triggers many steps of `left`?
- How would you find the shortest valid window if `s` were a multi-gigabyte file on disk that cannot fit in RAM?
Similar questions
- Character Safety and Engagement Analytics
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One