Facebook Pixel

Longest Substring with At Most Two Distinct Characters

Medium
LeetCode ↗

Given a string s, return the length of the longest substring that contains at most two distinct characters.

Example 1:

Input: s = "eceba"
Output: 3
Explanation: The substring is "ece" which its length is 3.

Example 2:

Input: s = "ccaabbb"
Output: 5
Explanation: The substring is "aabbb" which its length is 5.

Constraints:

  • 1 <= s.length <= 105
  • s consists of English letters.

Explanation

We use a flexible sliding window template because the best window length is not known in advance. Let l be the left boundary and let last_occurrence[ch] store the most recent index of each character in the current window. As we move r from left to right, we update last_occurrence[s[r]] = r.

The window is valid when it contains at most two distinct characters. If adding s[r] makes the map size 3, the window is invalid and we must remove one character type completely. The best character type to remove is the one with the smallest last occurrence, because it appears farthest to the left. So we set l = min(last_occurrence.values()) + 1 and delete that character from the map. After this update, the window is valid again and still as large as possible.

On each step, update max_len with r - l + 1.

Implementation

def lengthOfLongestSubstringTwoDistinct(self, s):
    last_occurrence = dict()
    max_len, l = 0, 0
    for r in range(len(s)):
        last_occurrence[s[r]] = r
        r += 1
        if len(last_occurrence) == 3:
            l = min(last_occurrence.values())+1
            del last_occurrence[s[l-1]]
        max_len = max(max_len, r - l)
    return max_len

Intuition

We want to use a sliding window to find the substrings with two distint characters.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator
Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

How does merge sort divide the problem into subproblems?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More