Given a string s, return the length of the longest substring that contains at most two distinct characters.
This is a classic sliding window problem where you need to find the optimal window that satisfies the constraint. For example, in the string "eceba", the longest substring with at most two distinct characters is "ece" with length 3.
Goal: Find the maximum length of any substring containing โค 2 unique characters
Input: A string s consisting of lowercase English letters
Output: An integer representing the length of the longest valid substring
Input & Output
Visualization
Time & Space Complexity
Each character is visited at most twice (once by right pointer, once by left pointer)
HashMap stores at most 3 characters (2 valid + 1 being removed)
Constraints
- 0 โค s.length โค 104
- s consists of lowercase English letters only
- Follow-up: Can you solve it in O(n) time?