DSA problem
Longest Substring with At Most Two Distinct Characters
Given a string s, return the length of the longest substring that contains at most two distinct characters.
This is a classic constraint-bounded substring problem. A brute-force scan of all substrings would take quadratic time, but the at-most-two-distinct condition has a useful property: if a substring is valid, you can always check validity incrementally as you grow or shrink its boundaries.
The variable-size sliding window handles this elegantly. Use a hash map to count the characters currently inside the window. Advance the right pointer to extend the window, adding the new character to the map. Whenever the map holds more than two distinct characters, advance the left pointer, decrementing counts and removing any character whose count reaches zero, until only two distinct characters remain. The longest window observed during this scan is the answer.
Examples
s = "eceba"3s = "ccaabbb"5s = "abaccc"4Constraints
- 1 <= s.length <= 10^5
- s consists of English letters.
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.