mediumSliding WindowSliding Window

Fruit Into Baskets

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

Recognize the pattern

longest subarray with at most 2 distinct valuescontiguous elementsvariable window

Brute force idea

The naive version of Fruit Into Baskets sounds like this: 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.

Better approach

A calmer way to see Fruit Into Baskets is this: 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.

Key invariant

The truth you want to protect throughout Fruit Into Baskets is this: 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.

Watch out for

The trap in Fruit Into Baskets usually looks like this: 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