KatInterview

Shortest Subarray With All K Distinct Characters Present

Arrays & HashingAuto-graded · 19 test cases
MediumAuto-gradedArrays & Hashingarrayshash mapsliding window

Last updated

Tests ability to use a sliding window with a hash-count map to find the minimum-length contiguous subarray that contains every distinct character appearing in a string at least a given number of times.

Shortest Balanced Window

You are given a string s consisting of lowercase English letters, and a positive integer k.

A subarray (contiguous substring) is called k-balanced if, for every distinct character that appears anywhere in s, that character appears at least k times within the subarray.

Return the length of the shortest k-balanced subarray of s. If no such subarray exists, return -1.

Constraints

  • 1 ≤ len(s) ≤ 2 000
  • 1 ≤ k ≤ len(s)
  • s contains only lowercase English letters ('a'–'z').
  • The "distinct characters" set is determined by the entire string s, not by the subarray alone.
  • If multiple subarrays share the minimum length, any of them is acceptable (only the length is returned).

Examples

Example 1

Input: shortest_balanced_window('aabbcc', 2)

Output: 6

Example 2

Input: shortest_balanced_window('aabbc', 2)

Output: -1

Example 3

Input: shortest_balanced_window('abcabc', 1)

Output: 3

Hints

Hint 1

First compute the set of distinct characters across the whole string; your window must satisfy every one of them.

Hint 2

Maintain a frequency hash map for the current window and a counter of how many required characters have already reached the threshold k — you only need to shrink when that counter equals the total number of distinct characters.

Hint 3

When the window is fully satisfied, try to shrink from the left as long as it stays satisfied, recording the minimum length each time before you shrink.