Longest Substring with At Most Two Distinct Characters

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

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

Examples

Example 1:

Input: s = "eceba"

Output: 3

Explanation: The substring "ece" has length 3 with two distinct characters ('e' and 'c').

Example 2:

Input: s = "ccaabbb"

Output: 5

Explanation: The substring "aabbb" has length 5 with two distinct characters ('a' and 'b').

Example 3:

Input: s = "a"

Output: 1

Explanation: The entire string has only one distinct character.

Constraints

  • 1 <= s.length <= 10⁵
  • s consists of English letters.
Source: Sliding Window pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle