157/670

157. Longest Substring with At Most Two Distinct Characters

Medium

You are given a string s of lowercase letters. Among all of its substrings (contiguous runs of characters), consider only those built from at most two different letters. Return the length of the longest one.

For instance, in "ccaabbb" the run "aabbb" uses only a and b and has length 5 — nothing longer qualifies, so the answer is 5. A substring made of a single repeated letter also counts, since one distinct letter is at most two.

The function receives the string and returns a single integer, the maximum length.

Example 1:

Input: s = "eceba"

Output: 3

Explanation: "ece" uses only e and c, length 3. Adding the b would introduce a third distinct letter, and no other window does better.

Example 2:

Input: s = "ccaabbb"

Output: 5

Explanation: "aabbb" uses only a and b, length 5. The full string would need c, a and b — three distinct letters.

Constraints:

  • 1 ≤ s.length ≤ 10⁴
  • s consists of lowercase English letters only.

Hints:

Checking every substring works but repeats the same counting over and over. Notice that if a window already breaks the two-letter rule, every larger window containing it breaks it too.

Grow a window rightward, tracking how many times each letter appears inside it. The moment a third distinct letter enters, shrink from the left until some letter's count hits zero.

Each index enters the window once and leaves at most once, so the whole scan is linear — record the best window length as you go.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: s = "eceba"

Expected output: 3