Minimum Window Containing All K Most-Frequent Characters
Arrays & HashingAuto-graded · 17 test casesLast updated
Tests ability to combine hash-counting (frequency maps) with a sliding window to find the shortest contiguous subarray satisfying a dynamic frequency-based constraint.
Minimum Window Containing All K Most-Frequent Characters
You are given a list of lowercase-letter strings words and a positive integer k.
Step 1 – Identify the target set.
Count the global frequency of every distinct string across all of words. Take the k most-frequent strings as your target set. If two strings have the same frequency, break ties lexicographically (earlier in alphabet = higher priority), so the target set is always uniquely determined. If k is greater than the number of distinct strings, the target set is simply all distinct strings.
Step 2 – Find the shortest subarray.
Find the shortest contiguous subarray (a window) of words such that, for every string in the target set, the window contains at least as many occurrences of that string as its global frequency.
Return the length of that shortest window. If no such window exists (which can only happen when words is empty), return 0.
Constraints
1 ≤ len(words) ≤ 2 000- Each string in
wordsconsists of 1–10 lowercase English letters. 1 ≤ k ≤ 50- The target set always has exactly
min(k, number of distinct strings)members. - A valid window always exists when
len(words) ≥ 1(because the whole array is always a valid candidate).
Examples
Example 1
Input: min_window_k_most_frequent(['a', 'b', 'a', 'c', 'b', 'a'], 2)
Output: 6
Example 2
Input: min_window_k_most_frequent(['x', 'y', 'x', 'y', 'z', 'x', 'y'], 1)
Output: 6
Example 3
Input: min_window_k_most_frequent(['p', 'q', 'p', 'r', 'q', 'p', 'q', 'r'], 3)
Output: 8
Hints
Hint 1
First make a single pass to compute global frequencies, then select the k most-frequent strings (with lexicographic tie-breaking) to form the target set and record how many times each must appear in any valid window.
Hint 2
Use a classic two-pointer (left/right) sliding window: expand right to include new words, shrink left once all targets are satisfied; track how many distinct target strings are currently 'satisfied' (window count ≥ required count) with a counter variable so the check is O(1).
Hint 3
When you move the left pointer past a target word, decrement its window count and—if it drops below the required threshold—decrement your 'satisfied' counter, forcing you to expand right again before recording a new minimum.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Phase 1 — Build the target set (hash counting)
Make one pass over words with a Counter to get the global frequency of every distinct string. Then sort the distinct strings by (-frequency, word) so that higher-frequency strings come first and lexicographic order breaks ties deterministically. The first min(k, len(distinct)) strings form the target set, each carrying its global frequency as a required count.
Phase 2 — Sliding window
Use two pointers left and right over words. Maintain:
window_count: a hash map counting occurrences of target strings only in the current window.satisfied: the number of target strings whose window count has reached (≥) the required count.
Expand right: if words[right] is a target, increment its window count; if it just hit the required threshold, increment satisfied.
Shrink left while satisfied == num_targets (all targets met): record the window length, then advance left. If the word leaving the window is a target and its count was exactly at threshold, decrement satisfied.
The minimum recorded length is the answer. Because the entire array is always a valid window (it contains every string's full global frequency by definition), the answer always exists for non-empty input.
Correctness
The full array trivially satisfies the requirement, so the window loop will always find at least one valid window. The two-pointer approach is correct because once all targets are satisfied, moving right further can only keep or improve the window—so we greedily shrink left first before expanding again.
The tie-breaking in target selection is deterministic (lex order), which makes the output uniquely defined.
Complexity
| Complexity | |
|---|---|
| Time | O(n + d log d) where n = len(words), d = number of distinct strings |
| Space | O(d) for the frequency maps |
The dominant term is the O(n) sliding window; the sort is over at most d ≤ n distinct strings.
from typing import List
from collections import Counter
def min_window_k_most_frequent(words: List[str], k: int) -> int:
if not words:
return 0
# Step 1: global frequency count
global_freq = Counter(words)
# Step 2: select k most-frequent strings with lex tie-break
ranked = sorted(global_freq.keys(), key=lambda w: (-global_freq[w], w))
target_keys = ranked[:k]
required = {w: global_freq[w] for w in target_keys}
num_targets = len(required)
# Step 3: sliding window
window_count = {}
satisfied = 0
left = 0
min_len = len(words)
for right in range(len(words)):
word = words[right]
if word in required:
window_count[word] = window_count.get(word, 0) + 1
if window_count[word] == required[word]:
satisfied += 1
while satisfied == num_targets:
min_len = min(min_len, right - left + 1)
left_word = words[left]
left += 1
if left_word in required:
if window_count[left_word] == required[left_word]:
satisfied -= 1
window_count[left_word] -= 1
return min_len