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.
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.
s = "aabcbcdbca"
,
n = 3
"bca"
(length 3), so the output should be
3
.