mediumSliding WindowSliding Window

Fruit Into Baskets

mediumTime: O(n)Space: O(1)

Signals to notice

longest subarray with at most 2 distinct valuescontiguous elementsvariable window

Brute force first

Check every subarray for at most 2 distinct values. Each subarray is checked independently. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

Sliding window with a frequency map tracking distinct values. Expand right; when distinct count exceeds 2, shrink left until it's back to 2. Track the maximum window size. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

What must stay true

The window always contains at most 2 distinct values. When a third enters, shrink from the left until one value is completely removed from the window. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Easy way to go wrong

Not correctly tracking when a value leaves the window — decrement its count and remove from the map when count hits 0. Otherwise the distinct count stays wrong. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Sliding Window Pattern