Coding · should-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix

Longest Substring with At Most Two Distinct Characters

mediumsliding-windowhash-map

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 only b and c.
  • s = "xxyyyzzzz" → 7. "yyyzzzz" uses y and z.
  • s = "mmmm" → 4. A single distinct character satisfies "at most two."

Hints

  1. 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?
  2. 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?
  3. Advance right one step at a time; while the window has more than two distinct characters, advance left and decrement counts, dropping a character from the map when its count reaches zero.

Last reviewed 8 September 2026