Find shortest substring with n unique letters
MicrosoftSoftware Engineer · OnsiteLast updated
This question evaluates proficiency in string processing, frequency management, and algorithmic optimization for locating constrained contiguous substrings. Commonly asked in the coding & algorithms domain because it reveals how candidates reason about character distinctness and efficiency trade-offs, it targets practical application of algorithmic techniques rather than purely conceptual theory.
Problem
You are given a string s consisting of lowercase English letters and an integer n (1 ≤ n ≤ 26).
Find the length of the shortest contiguous substring of s that contains exactly n distinct characters.
If no such substring exists, return -1.
Example
- Input:
s = "aabcbcdbca",n = 3 - One shortest substring with exactly 3 distinct characters is
"bca"(length 3), so the output should be3.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.