KatInterview

Minimum Window Containing All Required Characters

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

Last updated

Tests sliding window technique with character frequency tracking to find the smallest substring that satisfies multiplicity constraints.

You are given two strings source and target. Find the shortest contiguous substring within source that includes every character from target with at least the required frequency.

If multiple substrings of the same minimum length exist, return the one that appears first. If no valid substring exists, return an empty string.

Constraints:

  • 0 <= len(source), len(target) <= 10^5
  • Both strings consist of printable ASCII characters
  • Characters are case-sensitive: 'A' and 'a' are distinct
  • If target is empty, return ""
  • Character frequency matters: if target contains 'a' twice, the result must contain at least two 'a' characters

Examples

Example 1

Input: min_window_substring('ADOBECODEBANC', 'ABC')

Output: 'BANC'

Example 2

Input: min_window_substring('a', 'a')

Output: 'a'

Example 3

Input: min_window_substring('a', 'aa')

Output: ''

Hints

Hint 1

Use two pointers to maintain a window that expands to include required characters and contracts to find the minimum length.

Hint 2

Track how many of each required character you still need rather than rescanning the window each time.

Hint 3

Once a valid window is found, try shrinking from the left by removing characters that appear more times than needed.