Shortest Subarray With All K Distinct Characters Present
Arrays & HashingAuto-graded · 19 test casesLast 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 0001 ≤ k ≤ len(s)scontains 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Observations
-
Global requirement: The set of characters we must satisfy is fixed — it is the set of all distinct characters in the entire string
s. Every character in that set must appear at leastktimes in any valid window. -
Early exit: If any character's total frequency in
sis less thank, it is impossible to build a valid window, so we return-1immediately. -
Sliding window + hash count: We maintain a frequency map for the current window and a counter
satisfiedthat tracks how many required characters have reached the thresholdkin the current window. We expandrightone step at a time, and wheneversatisfied == total_requiredwe have a valid window. At that point we greedily shrink fromleftas much as possible (recording the minimum length each time before shrinking) to find the tightest valid window.
Correctness
- Every time we shrink, we first record the current length, so we never miss the optimum.
- We only decrement
satisfiedwhen a character's count in the window falls belowk, correctly tracking validity. - The two-pointer invariant ensures every candidate window is examined exactly once.
Complexity
- Time: O(n) — each character is added to and removed from the window at most once.
- Space: O(Σ) = O(26) for the frequency map and the required-character set, effectively O(1).
from collections import defaultdict, Counter
def shortest_balanced_window(s: str, k: int) -> int:
required_chars = set(s)
total_required = len(required_chars)
full_count = Counter(s)
for ch in required_chars:
if full_count[ch] < k:
return -1
window_count = defaultdict(int)
satisfied = 0
best = len(s) + 1
left = 0
for right in range(len(s)):
ch = s[right]
window_count[ch] += 1
if window_count[ch] == k:
satisfied += 1
while satisfied == total_required:
best = min(best, right - left + 1)
left_ch = s[left]
window_count[left_ch] -= 1
if window_count[left_ch] < k:
satisfied -= 1
left += 1
return best if best <= len(s) else -1