Find Minimum Window Containing All Distinct Characters
Arrays & HashingAuto-graded · 18 test casesLast updated
Tests ability to use a sliding window combined with hash counting to find the shortest substring that contains every distinct character appearing in the input string.
Minimum Window With All Distinct Characters
Given a string s, find the length of the shortest contiguous substring (window) that contains every distinct character that appears anywhere in s, with each such character appearing at least once in the window.
Formally, let D be the set of all distinct characters in s. Find the minimum length of any substring of s that contains every character in D at least once.
Because every character in D comes from s itself, a valid window always exists (the whole string is always a valid window).
Tie-breaking / uniqueness: return the integer length only; the position of the window does not matter.
Constraints
1 <= len(s) <= 2000sconsists of lowercase English letters only ('a'–'z').- The answer is always at least
len(D)(the number of distinct characters ins). - If
shas only one distinct character (e.g."aaaa"), the answer is1.
Examples
Example 1
Input: min_window_all_distinct('aabcbcdbca')
Output: 4
Example 2
Input: min_window_all_distinct('aaaa')
Output: 1
Example 3
Input: min_window_all_distinct('abcde')
Output: 5
Hints
Hint 1
Count how many distinct characters exist in s — that is your target; you need a window that satisfies all of them.
Hint 2
Use two pointers (left and right). Expand right to include new characters; once all distinct characters are covered, try shrinking from the left to minimize the window length.
Hint 3
Track a hash map of character counts inside the current window and a counter of how many distinct characters are currently 'satisfied' (count >= 1). Update the counter as you move the pointers.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
The set of "required" characters is exactly the set of distinct characters in s. We need the shortest window that satisfies all of them — a classic sliding window / two-pointer problem made precise with hash counting.
Algorithm
-
Compute the target. Let
required = len(set(s)). This is the number of distinct characters every valid window must contain. -
Sliding window with hash map.
- Maintain
window_counts, a dict mapping each character to its count in the current window[left, right]. - Maintain
satisfied, an integer counting how many distinct characters currently have count ≥ 1 in the window. - Expand: move
rightforward one step at a time, addings[right]towindow_counts. If its count just became 1, incrementsatisfied. - Shrink: while
satisfied == required(window is valid), record the window length as a candidate for the minimum, then removes[left]from the window (decrement its count; if it hits 0, decrementsatisfied), and advanceleft.
- Maintain
-
Return the best (minimum) length found.
Correctness
Every valid window is visited at least once: when right first reaches a position that completes the requirement and before left is pushed past the tightest valid start. The shrinking loop guarantees we find the tightest left boundary for each right endpoint. Since we check all right endpoints, the global minimum is found.
Complexity
- Time: O(n) — each character is added and removed from the window at most once.
- Space: O(1) — the hash map has at most 26 entries (lowercase English letters only).
Reference Solution
from typing import List
def min_window_all_distinct(s: str) -> int:
required = len(set(s)) # number of distinct chars to satisfy
window_counts = {} # char -> count inside current window
satisfied = 0 # how many distinct chars are satisfied
left = 0
best = len(s) # worst case: whole string
for right, ch in enumerate(s):
# Expand window to include s[right]
window_counts[ch] = window_counts.get(ch, 0) + 1
if window_counts[ch] == 1: # first occurrence of ch in window
satisfied += 1
# Shrink from the left while all distinct chars are covered
while satisfied == required:
best = min(best, right - left + 1)
left_ch = s[left]
window_counts[left_ch] -= 1
if window_counts[left_ch] == 0:
satisfied -= 1
left += 1
return best