LeetCode 159, Medium. Topics: Hash Table, String, Sliding Window. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 19 parametrized pytest cases, and a playground notebook:
Problem
Given a string s, return the length of the longest substring that contains at most two distinct characters.
Examples
Constraints
- 1 <= s.length <= 10^5
- s consists of English letters
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026