KatInterview

Tightest Segment Covering a Required Letter Multiset

StringsAuto-graded · 27 test cases
MediumAuto-gradedStringssliding-windowtwo-pointershash-map

Last 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 text covers target (for instance, when target is longer than text), return the empty string "".

Constraints

  • 1 <= len(text) <= 10^5
  • 1 <= len(target) <= 10^5
  • text and target contain 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.