KatInterview

Minimum Window Containing All K Most-Frequent Characters

Arrays & HashingAuto-graded · 17 test cases
HardAuto-gradedArrays & Hashingarrayshash mapsliding window

Last 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 words consists 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.