Longest Substring with At Most Two Distinct Characters
Medium · Sliding Window · Hash Table · String · Sliding Window
Problem
Given a string s, return the length of the longest substring that contains at most two distinct characters.
A substring is a contiguous run of characters. Upper- and lowercase letters count as different characters.
Examples
Input: s = "eceba" Output: 3
"ece" uses only e and c. Adding b would make three.
Input: s = "ccaabbb" Output: 5
"aabbb" uses only a and b.
Input: s = "abcabcabc" Output: 2
Any three neighbors are a, b and c, so the best is two letters.
Constraints
- 1 <= len(s) <= 10^5
- s consists of English letters
Approaches
- Extend from every start — time O(n²), space O(1)
Follow-up
With at most k distinct characters the same window works unchanged: shrink while the map has more than k keys. For a stream too long to keep, the last-position version needs only the current window's last positions, and the answer's length.
Related problems
Start free on Cariara · Coding problems · System design studio