Longest Substring with At Most Two Distinct Characters - Problem
Given a string s, return the length of the longest substring that contains at most two distinct characters.
A substring is a contiguous sequence of characters within a string. For example, in the string "abcdef", the substring "bcd" starts at index 1 and ends at index 3.
Example: For the string "eceba", the longest substring with at most two distinct characters is "ece" which has length 3.
Input & Output
Example 1 — Basic Case
$
Input:
s = "eceba"
›
Output:
3
💡 Note:
The longest substring with at most 2 distinct characters is "ece" with length 3
Example 2 — All Same Characters
$
Input:
s = "aaaa"
›
Output:
4
💡 Note:
The entire string has only 1 distinct character, so the answer is 4
Example 3 — Two Characters Mixed
$
Input:
s = "abacbc"
›
Output:
4
💡 Note:
The longest substring is "abac" or "acbc", both with 2 distinct characters and length 4
Constraints
- 1 ≤ s.length ≤ 105
- s consists of English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input String
Given string with multiple characters
2
Find Valid Substrings
Identify substrings with ≤ 2 distinct characters
3
Return Maximum Length
Length of the longest valid substring
Key Takeaway
🎯 Key Insight: Use sliding window technique to efficiently maintain a window with at most 2 distinct characters
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code