I knew it was a sliding window problem pretty fast, which felt good, but then I fumbled the shrink condition for longer than I'd like to admit.
Use the sliding window technique with two pointers to maintain a window that contains at most K distinct characters. Expand the right pointer to include new characters, and when the distinct count exceeds K, shrink the window from the left until it's valid again. Track the maximum window length throughout.
Pro tip: Clarify edge cases upfront (e.g., K=0, empty string) and mention that the algorithm runs in O(n) time with O(K) space, which is optimal. Also, briefly discuss how you would test the solution with examples.
Confirm the definition of 'substring' (contiguous) and 'distinct characters'. Ask about edge cases: empty string, K=0, K >= number of distinct characters in the string.
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.
Expand the right pointer to include a new character. If the number of distinct characters exceeds K, move the left pointer forward, updating the frequency map, until the window is valid again.
After each expansion (and contraction if needed), update the maximum length if the current window size is larger. Continue until the right pointer reaches the end of the string.
State that the time complexity is O(n) because each character is processed at most twice, and space is O(K) for the frequency map. 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.