Coding Interview PatternsLongest Substring with At Most Two Distinct Characters
MediumSliding Window
Longest Substring with At Most Two Distinct Characters
Explanation & Solution
Description
Given a string s, return the length of the longest substring that contains at most two distinct characters.
Input: s = "eceba"
Output: 3
Explanation: The substring "ece" has length 3 with two distinct characters ('e' and 'c').
Constraints
1 <= s.length <= 10⁵sconsists of English letters.
Approach
Sliding Window pattern
1. Handle Small Inputs
- If the string has 2 or fewer characters, the entire string is already a valid substring — return its length.
2. Initialize the Sliding Window
- Create a
Mapto track the frequency of each character in the current window. - Set
leftto 0 andmaxLento 0.
3. Expand the Window
- Iterate
rightfrom 0 tos.length - 1. - Add
s[right]to the frequency map, incrementing its count.
4. Shrink When Invalid
- If the map has more than 2 distinct characters, the window is invalid.
- Shrink from the left: decrement the count of
s[left]. If its count reaches 0, remove it from the map entirely. - Continue shrinking until the map size is at most 2.
5. Update the Maximum
- After ensuring the window is valid, update
maxLenwithright - left + 1.
6. Return the Result
- After the loop, return
maxLen— the length of the longest substring with at most two distinct characters.
Key Insight
The Map tracks exactly which characters are in the window and their counts. By deleting characters whose count drops to 0, the map size always reflects the true number of distinct characters. This lets us efficiently maintain the sliding window constraint with O(n) time complexity.
Visualization
Input:
[e, c, e, b, a]
—
Press ▶ or use ← → to step through
Left (L)Right (R)WindowDone
14 steps