Sliding window felt like the right move and it was, but the 'exactly n' constraint tripped me up at first.
Use a sliding window (two-pointer) technique to efficiently find the shortest substring with exactly n unique characters. Expand the right pointer to include characters, and when the window has exactly n unique characters, shrink from the left to find the minimal length. Track the minimum length and return 0 if no such substring exists.
Pro tip: Clarify edge cases upfront, such as n=0, n greater than the number of unique characters in the string, or empty string. Also, discuss how you would handle the case where the window has more than n unique characters—by moving the left pointer until the unique count drops to n.
Confirm the definition of 'substring' (contiguous) and 'unique characters'. Discuss edge cases: n=0, n > total unique characters, empty string, and whether the string contains only lowercase letters or any characters.
Explain that a brute-force check of all substrings would be O(n^2) or worse, so a sliding window with a hash map to count character frequencies achieves O(n) time.
Set left and right pointers to 0, use a hash map to track character counts in the current window, and initialize min_length to infinity.
Move right to include characters. When the window has exactly n unique characters, update min_length and then move left to shrink the window while maintaining exactly n unique characters, updating min_length each time.
After the loop, return min_length if it was updated, otherwise return 0 to indicate no valid substring exists.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.