KatInterview

Minimum Window with K Distinct Characters

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

Last updated

Tests sliding window technique with character frequency tracking to find the smallest substring containing exactly k distinct characters.

You are given a string text and a positive integer k.

Your task is to find the shortest contiguous substring of text that contains exactly k distinct characters.

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

Input

  • text: a non-empty string containing only lowercase English letters
  • k: a positive integer representing the target number of distinct characters

Output

Return the shortest substring containing exactly k distinct characters, or "" if none exists.

Constraints

  • 1 <= len(text) <= 10^5
  • 1 <= k <= 26
  • text contains only lowercase English letters ('a' to 'z')

Examples

Example 1

Input: min_window_k_distinct('aabcbc', 2)

Output: 'ab'

Example 2

Input: min_window_k_distinct('abac', 3)

Output: 'bac'

Example 3

Input: min_window_k_distinct('aaaa', 2)

Output: ''

Hints

Hint 1

Use a sliding window approach with two pointers to track the current substring being examined.

Hint 2

Maintain a frequency map to count occurrences of each character in the current window and track how many distinct characters you have.

Hint 3

When you have exactly k distinct characters, try shrinking the window from the left by removing duplicate characters to find the minimum length ending at the current position.