Find the Longest Substring with at Most Two Distinct Characters
Company: TikTok
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: Find the longest contiguous substring containing at most two distinct characters. This portable version of the standard referenced problem defines empty input, an ASCII character domain, exact return semantics, and two examples for later cross-language console verification.
Read the full TikTok Software Engineer interview experience this question came from
Constraints
- 0 <= len(s) <= 200,000
- s contains printable ASCII characters.
- A substring is contiguous.
- Return 0 when s is empty.
Examples
Input: ('eceba',)
Expected Output: 3
Explanation: ece is a longest substring with two distinct characters.
Input: ('ccaabbb',)
Expected Output: 5
Explanation: aabbb has length five and uses only a and b.
Hints
- Track character counts inside a sliding window.
- When a third distinct character appears, advance the left edge until one character count reaches zero.