KatInterview

Minimum Window Containing All Target Characters

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

Last updated

Tests the ability to efficiently find the smallest substring containing all required characters using sliding window and hash tables.

You are given two strings source and target. Your task is to locate the smallest contiguous portion of source that includes every character from target, respecting duplicate occurrences.

When multiple substrings share the minimum length, you may return any of them. If no valid substring exists, return an empty string.

Constraints:

  • 1 <= len(source) <= 10^5
  • 1 <= len(target) <= 10^4
  • Both strings consist of uppercase and lowercase English letters
  • Character comparison is case-sensitive

Examples

Example 1

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

Output: 'BANC'

Example 2

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

Output: ''

Hints

Hint 1

Consider using two pointers to define a window that expands and contracts as you scan the source string.

Hint 2

Track how many distinct characters in your current window satisfy the target's requirements—this avoids repeatedly comparing full frequency maps.

Hint 3

Once your window becomes valid, try shrinking it from the left while maintaining validity to find the smallest possible window.