KatInterview

Find Minimum Substring with K Distinct Characters

StringsAuto-graded · 21 test cases
MediumAuto-gradedStringssliding-windowstringstwo-pointers

Last 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$
  • s consists 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.