Minimum Window with K Distinct Characters
StringsAuto-graded · 23 test casesLast 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 lettersk: 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^51 <= k <= 26textcontains 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The optimal solution uses a sliding window technique with a hash map to track character frequencies.
We maintain a window defined by two pointers, left and right, and expand it by moving right forward through the string. For each position:
- Expand the window: Add the character at
rightto our frequency map - Contract when oversized: If the window contains more than
kdistinct characters, advanceleftuntil we have exactlykor fewer distinct characters, removing characters from the frequency map as we go - Optimize the valid window: When we have exactly
kdistinct characters, further shrink from the left by removing duplicate characters (characters that appear more than once). This ensures we find the shortest valid window ending at the currentrightposition - Track the minimum: Compare the current window length against our best result and update if smaller
The key insight is that for any ending position right, there is a unique shortest valid substring ending at that position. By checking all possible ending positions and maintaining the minimum, we find the global optimum.
Why It Works
At each step where we have exactly k distinct characters after optimization, the window [left, right] represents the shortest valid substring ending at right. We never skip a potentially optimal solution because:
- When contracting from the left, we only remove positions that would create invalid windows (too many distinct characters)
- When optimizing by removing duplicates, we find the true minimum for that ending position
- By considering all ending positions, we examine all possible optimal substrings
Complexity
- Time: O(n) where n is the length of
text. Therightpointer makes n iterations, and theleftpointer only moves forward, making at most n total moves across all iterations. Each operation on the hash map is O(1). - Space: O(min(k, 26)) for the character frequency map. Since we only track up to
kdistinct characters (or 26 for the full alphabet), the space is bounded and effectively O(1) for this problem.
Solution Code
def min_window_k_distinct(text: str, k: int) -> str:
if k <= 0:
return ""
char_count = {}
left = 0
min_start = 0
min_len = len(text) + 1
for right in range(len(text)):
char = text[right]
char_count[char] = char_count.get(char, 0) + 1
while len(char_count) > k:
left_char = text[left]
char_count[left_char] -= 1
if char_count[left_char] == 0:
del char_count[left_char]
left += 1
if len(char_count) == k:
while char_count[text[left]] > 1:
char_count[text[left]] -= 1
left += 1
window_len = right - left + 1
if window_len < min_len:
min_start = left
min_len = window_len
return "" if min_len == len(text) + 1 else text[min_start:min_start + min_len]