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.

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

example_1.py โ€” Basic case
$ Input: s = "eceba"
โ€บ Output: 3
๐Ÿ’ก Note: The longest substring with at most 2 distinct characters is "ece" with length 3. Other valid substrings include "ec" (length 2), "ceb" (length 3), but "ece" and "ceb" both have maximum length.
example_2.py โ€” All same characters
$ Input: s = "ccaabbb"
โ€บ Output: 5
๐Ÿ’ก Note: The longest substring is "aabbb" with 2 distinct characters ('a' and 'b') and length 5. We could also have "ccaa" with length 4, but "aabbb" is longer.
example_3.py โ€” Single character
$ Input: s = "a"
โ€บ Output: 1
๐Ÿ’ก Note: With only one character, the longest substring with at most 2 distinct characters is the entire string with length 1.

Visualization

Tap to expand
Sliding Window VisualizationString: "eceba"ecebaCurrent WindowleftrightCharacter Counte: 2c: 1Distinct: 2 โ‰ค 2 โœ“Length: 3Algorithm Flow:1Expand right pointer, add character to HashMap2Check if distinct characters > 23If yes, shrink left pointer until valid4Update maximum window size
Understanding the Visualization
1
Initialize
Start with an empty window and HashMap at the beginning of the string
2
Expand
Move right pointer and add characters to HashMap while constraint is satisfied
3
Contract
When more than 2 distinct characters exist, shrink from left until valid
4
Track Maximum
Continuously update the maximum valid window size encountered
Key Takeaway
๐ŸŽฏ Key Insight: The sliding window technique allows us to solve this problem in O(n) time by maintaining a valid window that expands greedily and contracts only when necessary.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Each character is visited at most twice (once by right pointer, once by left pointer)

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

HashMap stores at most 3 characters (2 valid + 1 being removed)

n
2n
โœ“ Linear Space

Constraints

  • 0 โ‰ค s.length โ‰ค 104
  • s consists of lowercase English letters only
  • Follow-up: Can you solve it in O(n) time?
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 22
41.3K 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