← Microsoft Interview Insights
My first instinct was sliding window and that was right, but I kept second-guessing the 'exactly n' part vs 'at least n'.
Use a sliding window (two-pointer) technique to maintain a window with at most n distinct characters, expanding the right pointer and shrinking the left pointer when the distinct count exceeds n. Track the minimum length whenever the window contains exactly n distinct characters. If no such window is found, return -1.
Pro tip: Clarify edge cases upfront, such as when n is greater than the number of distinct characters in the string or n <= 0, and mention that the algorithm runs in O(N) time with O(1) space for the character frequency map (since lowercase letters are limited to 26).
Restate the problem to ensure clarity: find the shortest contiguous substring with exactly n distinct characters. Discuss edge cases: n <= 0, n > total distinct characters, empty string, and no valid substring.
Explain that a brute-force check of all substrings would be O(N^2) or worse, so a sliding window with two pointers is optimal. Maintain a frequency map of characters in the current window and a count of distinct characters.
Move the right pointer to include new characters. When the distinct count exceeds n, move the left pointer to reduce distinct characters. Whenever the distinct count equals n, update the minimum length.
Continue until the right pointer reaches the end of the string. If a valid window was found, return the minimum length; otherwise, return -1.
State that the time complexity is O(N) because each character is visited at most twice, and space is O(1) since the frequency map has at most 26 entries. Walk through a small example to verify correctness.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.