Problem 337
Smallest Window with All Distinct Characters
Medium · 20 pts · String, Sliding Window, Hash Table
Problem
Find the length of the shortest substring of S that contains every distinct character of S at least once. For example, the distinct characters of 'aabcbcdbca' are a, b, c and d, and the shortest substring containing all four is 'dbca' with length 4. The window can be found with two pointers: expand to the right until all characters are present, then shrink from the left as far as possible.
Input
A single string S of lowercase letters.
Output
Print the length of the smallest such window.
Constraints
1 <= |S| <= 100000
Example input
aabcbcdbca
Example output
4
Explanation
The string 'aabcbcdbca' uses the letters a, b, c and d. The substring 'dbca' near the end contains all four and has length 4; no shorter substring does.