Sliding window was the right move and I knew it pretty quickly.
Use a sliding window (two pointers) 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 (e.g., n <= 0, n > distinct characters in string) and mention that the sliding window approach runs in O(N) time and O(1) space for a fixed alphabet, which is optimal for this problem.
Confirm the definition of 'substring' (contiguous), handle cases like n <= 0, n greater than the number of distinct characters in the string, and empty string. Discuss return value -1 when no such substring exists.
Explain that a brute-force check of all substrings would be O(N^2) or worse, so a two-pointer sliding window 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 shrink the window until the distinct count is at most n. Whenever the distinct count equals n, update the minimum length.
Keep a variable for the minimum length found, initialized to infinity. After processing, return the minimum length if it was updated, otherwise return -1.
State that the time complexity is O(N) because each character is visited at most twice, and space is O(1) for a fixed alphabet (or O(k) where k is the number of distinct characters). 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.