Coding · should-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix
Longest Substring with At Most Two Distinct Characters
Problem
Given a string s, return the length of the longest contiguous substring that contains at most two different characters.
- The string has at most 200,000 characters and may be empty (return 0 in that case).
- Any printable character can appear, including spaces and digits.
Examples
s = "abbcbbba"→6. The substring"bbcbbb"uses onlybandc.s = "xxyyyzzzz"→7."yyyzzzz"usesyandz.s = "mmmm"→4. A single distinct character satisfies "at most two."
Hints
- If a substring has at most two distinct characters, so does every substring inside it. What does that property let you do with a growing window?
- Keep a window
[left, right]and a count of each character inside it. When a third character enters, which side must shrink, and by how much? - Advance
rightone step at a time; while the window has more than two distinct characters, advanceleftand decrement counts, dropping a character from the map when its count reaches zero.
Last reviewed 8 September 2026
Locked
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Secure payment by Stripe · instant access · refund questions: [email protected]
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.