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
Longest Substring with At Most Two Distinct Characterseceba01234Input: "eceba"Longest valid substring: "ece" (length 3)Output: 3Contains exactly 2 distinct characters: e and c
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
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
78.4K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen