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 t require at least the same count inside the chosen slice of s.
  • 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 s covers t, return "".

Examples

Example 1

  • Input: s = "PRACXTYRPKCT", t = "PRT"
  • Output: "TYRP"
  • Explanation: Several slices of s contain 'P', 'R', and 'T' — including "PRACXT" (length 6) and "RPKCT" (length 5) — while s[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', whereas s contains only a single 'r', so no covering slice exists.

Constraints

  • 1 <= len(s) <= 10^5
  • 1 <= len(t) <= 10^4
  • Both s and t contain only ASCII English letters ('a'–'z' and 'A'–'Z').

Step-by-step walkthrough

  1. Understand the goal and what "covering" means

    Given a source string s and a target string t, we want the shortest contiguous substring of s that contains every character of t at least as many times as it appears in t.

    • 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), or s lacks enough copies of a required letter as in Example 2), return "". If several substrings tie for shortest, returning any one of them is valid.
  2. Why brute force is too slow — and how a sliding window fixes it

    A brute-force solution tries every starting index left from 0 to len(s) - 1 and scans right rightward until s[left : right + 1] covers t. Because len(s) can be 100,000, nested loops take up to O(|s|^2) (~10^10) operations, which is far too slow. Notice why brute force wastes work: when left advances from 0 to 1, it throws away everything it just counted across s[1..right] and scans those exact same characters again!

    Instead, we maintain a single sliding window s[left : right + 1] controlled by two pointers (left and right) 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 left never need to move backward? Whenever left steps past an index a while at right = r, we have already checked s[a : r + 1] (the shortest valid window starting at a). Any future window starting at a with a larger right would only be longer, so a can never produce a strictly shorter answer later. Because left and right each advance at most |s| times, the entire scan takes linear time!

  3. Track coverage in O(1) using `need` and `missing`

    How do we tell in O(1) time whether our window currently covers t, without looping over all 52 uppercase/lowercase letters on every step? We track two pieces of state:

    1. need: a dictionary mapping each character in t to how many more copies the window still needs. Crucially, need[ch] is allowed to go negative — a negative value like -1 simply means the window currently holds 1 extra (surplus) copy of ch!
    2. missing: a single integer counting how many total character copies from t (duplicates included) are still uncovered. When missing == 0, the window covers t!

    Watch how need['B'] and missing behave when t = "BC" (need = {'B': 1, 'C': 1}, missing = 2) on s = "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 need
    
  4. Expand `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: if in_char in need, check if need[in_char] > 0: missing -= 1 before subtracting 1 from need[in_char].
    • While missing == 0:
      1. Compute window_len = right - left + 1 and update (best_start, best_len) before advancing left (while the window is still valid!). Storing two integers (best_start, best_len) instead of slicing s[left : right + 1] on every improvement avoids copying long strings inside the loop, and best_len == 0 cleanly produces s[0:0] == "" when no answer exists.
      2. Remove out_char = s[left]: if out_char in need, add 1 to need[out_char] first, and then check if need[out_char] > 0: missing += 1.
    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]
    
  5. Walk through Example 1 (`s = "PRACXTYRPKCT"`, `t = "PRT"`)

    Initially need = {'P': 1, 'R': 1, 'T': 1} and missing = 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".
    
  6. 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|). Building need scans t once in O(|t|) time. In the sliding window, right advances |s| times and left only ever increments (left <= |s|), so the inner while loop executes at most |s| total steps across the entire run — making each pointer step amortized O(1) (meaning even though one right step may trigger many left steps at once, the average work per right step over the whole string is constant). Finally, slicing the winning substring once at the end takes O(best_len) <= O(|s|) time.
  • Space: O(k) auxiliary memory (at most 52 entries in need), plus O(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, or s = "PRACXTYRPKCT", t = "PRZ"): missing never reaches 0, best_len stays 0, and s[0:0] returns "".
  • Entire string s is the sole covering window (s = "cba", t = "abc"): Initializing best_len = 0 (rather than len(s)) ensures a window of length len(s) is properly recorded instead of mistaken for "no match".
  • Duplicate letters in t (s = "abxxaxb", t = "aab"): missing starts at 3 and need['a'] = 2, so "ab" leaves missing == 1 and scanning continues until "abxxa".
  • Surplus copies of target letters (s = "BBBAC", t = "BC"): Extra 'B's drive need['B'] negative (-2), allowing left to discard two 'B's while keeping missing == 0 to reach "BAC".
  • Case sensitivity (s = "aAbBA", t = "AB"): 'a' and 'A' hash as distinct keys, returning "BA".

Common mistakes

  • Decrementing missing on every occurrence of a target character: If t = "AB" and s = "AAB", decrementing missing twice on the two 'A's hits missing == 0 on "AA" before 'B' ever appears! Only decrement missing when need[in_char] > 0.
  • Incrementing missing whenever any target character leaves left: Dropping a surplus 'B' (need['B'] rising from -1 to 0) keeps the window valid; only increment missing when need[out_char] > 0 after adding 1.
  • Recording best_len after incrementing left (or using right - left instead of right - 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 of s itself (window_len == len(s) is not < len(s)). Use best_len = 0 (or len(s) + 1) as the "not found" sentinel.
  • Slicing best = s[left : right + 1] inside the while loop: Turns an O(|s|) algorithm into O(|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 have window_counts[ch] >= required[ch], and shrink while formed_unique == len(required). Equivalent O(|s| + |t|) time and O(k) space, using non-negative counts at the cost of a second dictionary.
  • Filtered index list: Pre-filter s into [(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 in t.

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, need already handles any Unicode code point (the numeric ID assigned to a symbol, such as U+00E9 for 'é'). 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 on t — 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 the regex library'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 right triggers many steps of left? Building need takes O(|t|) time and extra space is O(k) where k <= |t| is the number of unique characters in t. Even though one step of right can trigger nearly |s| increments of left — for instance, on s = "bbbb...ba" and t = "a", right walks |s| - 1 steps doing zero shrinks and then the final step at 'a' advances left across all |s| - 1 'b's in one burst — left never resets or moves backward, so total pointer advances across the entire run are bounded by 2 * |s|, giving O(|s| + |t|) total time.
  • How would you find the shortest valid window if s were a multi-gigabyte file on disk that cannot fit in RAM? Because left and right both move strictly left-to-right, open two sequential buffered file readers on the file — a leading handle at character offset right and a trailing handle at left — while keeping only need, missing, left, right, and (best_start, best_len) in O(k) RAM! Both file handles stream forward sequentially at disk throughput without storing the window text in memory, and once scanning finishes you seek to best_start to read out the best_len characters (if s arrives 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

Similar questions

More Character.AI interview questions

All 2 Character.AI questions →