Longest Substring with At Most Two Distinct Characters

Medium · Sliding Window · Hash Table · String · Sliding Window

Problem

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

A substring is a contiguous run of characters. Upper- and lowercase letters count as different characters.

Examples

Input: s = "eceba"
Output: 3

"ece" uses only e and c. Adding b would make three.

Input: s = "ccaabbb"
Output: 5

"aabbb" uses only a and b.

Input: s = "abcabcabc"
Output: 2

Any three neighbors are a, b and c, so the best is two letters.

Constraints

Approaches

Follow-up

With at most k distinct characters the same window works unchanged: shrink while the map has more than k keys. For a stream too long to keep, the last-position version needs only the current window's last positions, and the answer's length.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…