KatInterview

Shortest Substring Containing All Required Characters

StringsAuto-graded · 21 test cases
MediumAuto-gradedStringssliding-windowhash-maptwo-pointers

Last 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.