Problem Description
Given a string s, find the length of the longest substring that contains at most two distinct characters.
Key Insights
- Use a sliding window to maintain a contiguous substring.
- Keep track of character frequencies within the current window using a hash map or dictionary.
- When the window contains more than two distinct characters, shrink the window from the left until only two remain.
- Update the maximum length each time the window satisfies the condition.
Space and Time Complexity
Time Complexity: O(n) where n is the length of the string, since each character is processed at most twice. Space Complexity: O(1) because the hash map holds at most 3 entries (usually up to 2 distinct characters).
Solution
We use the sliding window technique with two pointers (left and right) to represent the current window. A hash table/dictionary records the count of each character inside the window. As we extend the right pointer, we update the count. If the hash table contains more than two distinct characters, we start moving the left pointer to reduce the number of distinct characters until we have at most two distinct keys. The length of the current valid window is then used to update our maximum length answer.