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⁵
  • s consists 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 Map to track the frequency of each character in the current window.
  • Set left to 0 and maxLen to 0.

3. Expand the Window

  • Iterate right from 0 to s.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 maxLen with right - 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]
e0c1e2b3a4

Press ▶ or use ← → to step through

Left (L)Right (R)WindowDone
14 steps

Solution Code