Find Minimum Substring with K Distinct Characters
StringsAuto-graded · 21 test casesLast updated
Determine the length of the shortest contiguous substring that contains a target count of unique lowercase letters using a sliding window technique.
Given a string s consisting of lowercase English letters and an integer k, find the length of the shortest contiguous substring in s that contains exactly k unique characters.
If no contiguous substring with exactly k unique characters exists, return -1.
Constraints
- $1 \le \text{len}(s) \le 10^5$
sconsists exclusively of lowercase English characters ('a'to'z').- $1 \le k \le 26$
Examples
Example 1
Input: shortest_substring_with_n_unique_letters('aabcbcdbca', 3)
Output: 3
Hints
Hint 1
Consider using a sliding window approach with two pointers (left and right).
Hint 2
As you expand the right boundary, track character frequencies and total unique characters inside the window.
Hint 3
When the number of unique characters reaches or exceeds k, shrink the window from the left while maintaining or checking valid states to find the minimum possible length.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
We can solve this problem efficiently using a sliding window (two-pointer) approach.
- Maintain a frequency array of size 26 (or a hash map) for character counts within the active window, alongside a counter for the current number of unique characters.
- Iterate the
rightpointer over the string from start to end, adding each characters[right]to the frequency counts. - Whenever the count of unique characters in the window reaches or exceeds
n:- If the count of unique characters is exactly
n, consider the current window size (right - left + 1) to update our minimum length tracker (best). - Remove
s[left]from the window by decrementing its frequency and incrementingleft. If its frequency drops to 0, decrement the count of unique characters.
- If the count of unique characters is exactly
- Continue this process until
rightreaches the end ofs. - If
bestwas never updated (meaning no valid window was found), return-1. Otherwise, returnbest.
Why It Is Correct
Because we want the shortest substring with exactly n distinct characters:
- Any window with more than
ndistinct characters is invalid, so shrinking from the left is necessary. - Any valid window with exactly
ndistinct characters might be shrinkable from the left if the leftmost character is redundant (occurs multiple times in the window) or if dropping it yields another state to explore. - Incrementally moving
leftforward wheneverdistinct >= nensures that every minimal valid window ending atrightis evaluated without missing potential shortest substrings.
Complexity
- Time Complexity: $\mathcal{O}(L)$, where $L$ is the length of
s. Both therightandleftpointers traverse the string at most once. Character lookup and updates take $\mathcal{O}(1)$ time. - Space Complexity: $\mathcal{O}(1)$ auxiliary space, since the frequency map size is bounded by the constant alphabet size of 26 lowercase English letters.
def shortest_substring_with_n_unique_letters(s: str, n: int) -> int:
counts = [0] * 26
distinct = 0
left = 0
best = len(s) + 1
for right, ch in enumerate(s):
index = ord(ch) - ord('a')
if counts[index] == 0:
distinct += 1
counts[index] += 1
while distinct >= n:
if distinct == n:
best = min(best, right - left + 1)
left_index = ord(s[left]) - ord('a')
counts[left_index] -= 1
if counts[left_index] == 0:
distinct -= 1
left += 1
return best if best <= len(s) else -1