Medium · At-Most-K Distinct Window
Understand → Visualise → Practice.
Return the longest contiguous run containing at most two distinct values.
Grow the window to the right, counting values. When it holds three distinct values, shrink from the left until only two remain.
Increment its count.
While more than two values are present, decrement the left value and remove it at zero.
The answer is the largest window length seen.
O(n) time and O(1) space (at most three keys).
Restarting from scratch after a third value appears is O(n²).
Read the full guide first: Two Pointers and Sliding Windows.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.