Fruit Into Baskets
Fruit Into Baskets is LeetCode 904 (Medium). Trees stand in a row, and fruits[i] is the type of fruit on tree i. You have two baskets. Each basket holds any amount of fruit, but only one type.
- Choose any starting tree, then take one fruit from every tree as you walk right.
- Stop at the first tree whose fruit fits neither basket.
- Return the most fruit you can collect.
With up to 10⁵ trees, the scan has to be about O(n).
- 1 <= fruits.length <= 10⁵
- 0 <= fruits[i] < fruits.length
Intuition
Drop the story and the question is: what is the longest stretch of neighbouring trees that holds at most two fruit types? You never skip a tree, so whatever you pick is one unbroken stretch, and it is allowed exactly when it has two types or fewer.
That is a sliding window. Grow it one tree at a time on the right. When a third type gets in, give up trees on the left until only two types remain, keeping a count per type so you know when a type has fully left. Both ends only move right, so each tree joins the window once and leaves it at most once.
"Longest contiguous stretch with at most k different values" is a sliding window with a count per value. Here k is 2 and the values are fruit types.
Approach
Before reading on, pick a right end and ask: which left end gives the longest legal stretch ending here? When the right end moves one step, can that left end ever move back? Then write it in one pass.
Count the types inside the window
Keep a map from fruit type to how many of its trees are in the window. The number of keys is the number of types you are holding, so the window is legal while the map has at most two keys.
Add the next tree on the right
Move right one tree on and add 1 to its type's count. A new type adds a new key, and if that makes three keys, the window is no longer legal.
Give up trees on the left until two types remain
While the map has three keys, subtract 1 from the count of the tree at left, delete that key once its count hits 0, and move left one tree on. Removing trees from the left is the only way to get rid of a type and keep the trees contiguous.
Measure the legal window
After the shrink, the window from left to right holds at most two types. Its length, right - left + 1, is a fruit count you could really collect, so keep the largest one.
Why `left` never needs to move back
left passes a tree only when the window starting at that tree has three types. Any window that starts there and ends further right contains those same trees, so it has three types too. Moving left forward never throws away a window that could have won.
Code in Python, C++ and Java
Common pitfalls
Leaving a type in the map at count 0
count[out] -= 1 left += 1
count[out] -= 1
if count[out] == 0:
del count[out]
left += 1The map's size is the number of types held, so a key left at 0 still counts as a type. On [1, 2, 3] the map keeps three keys after every count reaches 0, the loop never stops, and left runs past the end of the array.
Reading two baskets as two fruits
while right - left + 1 > 2:
while len(count) > 2:
Each basket takes any amount of one type, so the limit is on types, not on fruit. On [1, 1, 1] the wrong test caps the window at 2 trees and returns 2; the answer is 3.
Measuring the window as right − left
best = max(best, right - left)
best = max(best, right - left + 1)
Both ends are inside the window, so it holds right - left + 1 trees. On [1, 2, 1] the wrong formula returns 2 instead of 3.
Edge cases
[4, 4, 4]The map never gets past one key, the window never shrinks, and the answer is every tree, 3. Code that insists on exactly two types would wrongly return 0 here.
Complexity
right moves n times and left moves at most n times in total, so the inner loop adds at most n steps overall. The map never holds more than three keys.Fruit Into Baskets FAQ
Why not try every starting tree?
That works, but each start can walk up to n trees, so it is O(n²): about 10¹⁰ steps for 10⁵ trees. The window reuses the work, because the best window ending at one tree tells you where the next one can start.
What changes with k baskets instead of two?
Only the test: shrink while the map has more than k keys. That general form is Longest Substring with At Most K Distinct Characters (LeetCode 340), and the same proof applies.
Can it be done without a hash map?
Yes. Remember the last two types, the current window length, and how many trees at the end of the window are the newest type. When a third type arrives, the new window is that end run plus the new tree. On [1, 2, 2, 3] the end run is the two 2s, so the window restarts at length 3. It still runs in O(n), but each step is a bit harder to get right.