Fruit Into Baskets

medium

You are walking along a row of fruit trees; fruits[i] is the type of fruit tree i. You have two baskets, each of which can hold only a single type of fruit (but any amount). Starting from any tree, you pick exactly one fruit from every tree, moving right, and must stop as soon as you'd need a third basket.

Return the maximum number of fruits you can pick — i.e. the length of the longest contiguous subarray containing at most two distinct values.

Hints

Two baskets that each hold one type — what does that limit about your picked run?
It's the longest contiguous subarray with at most two distinct values.
Slide a window with a count map; when a third type enters, shrink from the left.

Common doubts

You need to know when a type fully leaves the window as you shrink. Counting occurrences lets you delete a type exactly when its count hits zero.
It's the number of keys in the map. Growing may push it to three; shrinking brings it back to two.
No — the sliding window implicitly considers every start; you only ever move both pointers forward.

Interview follow-ups

Identical template with the condition 'map size > k' — that's the next problem, Longest Substring with At Most K Distinct.
When you update the best length, snapshot the current map's keys (there are at most two).

Fun facts

  • Fruit Into Baskets is just 'at most 2 distinct' dressed up — recognizing the disguise is half the interview.
  • The count-map-size-as-distinct-count trick generalizes directly to any 'at most k distinct' window.

Asked at

GoogleAmazonMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: fruits = [1,2,1]
Output: 3
Only two types (1 and 2), so all three fruits can be picked.
Example 2
Input: fruits = [1,2,3,2,2]
Output: 4
Pick [2,3,2,2] — two types — for four fruits.
Constraints

- 1 <= fruits.length <= 10^5 - 0 <= fruits[i] < fruits.length

Solve this problem →