LeetCode #904 Medium

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).

Constraints
  • 1 <= fruits.length <= 10⁵
  • 0 <= fruits[i] < fruits.length
sliding-windowarrayhashing
Open on LeetCode ↗
02

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.

How to spot this pattern

"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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1from typing import List
▶2 
▶3 
▶4class Solution:
▶5 def totalFruit(self, fruits: List[int]) -> int:
▶6 count = {}
▶7 left = best = 0
▶8 for right, fruit in enumerate(fruits):
▶9 count[fruit] = count.get(fruit, 0) + 1
▶10 while len(count) > 2:
▶11 out = fruits[left]
▶12 count[out] -= 1
▶13 if count[out] == 0:
▶14 del count[out]
▶15 left += 1
▶16 best = max(best, right - left + 1)
▶17 return best
trees1021322324basketsemptyempty0besttwo empty baskets, no trees picked yet
left0
best0
The window is the stretch of trees you are picking from. It starts empty. Each basket will hold one fruit type, any number of fruits of it.
trees10left right21322324basketstype 11 treeempty1besttype 1 takes a free basket → best 1
right0
types held1
window1
best1
Tree 0 has type 1, which is new, but a basket is still empty, so it fits. The window from tree 0 to tree 0 holds 1 tree and only 1 type, so it is a real way to pick 1 fruits. That beats the old best.
trees10left21right322324basketstype 11 treetype 21 tree2besttype 2 takes a free basket → best 2
right1
types held2
window2
best2
Tree 1 has type 2, which is new, but a basket is still empty, so it fits. The window from tree 0 to tree 1 holds 2 trees and only 2 types, so it is a real way to pick 2 fruits. That beats the old best.
trees10left2132right2324basketstype 11 treetype 21 treetype 3no basket2besttype 3 needs a third basket → shrink
right2
types held3
Tree 2 brings type 3, a third type. Picking cannot skip a tree, so the only way to keep tree 2 is to give up trees from the left end until one of the old types is gone completely.
trees1021left32right2324basketstype 31 treetype 21 tree2bestdrop tree 0 → no type 1 left, basket freed
left1
type 10
Tree 0 was the last type 1 tree in the window, so its count reaches 0 and the type is removed. That empties a basket, and type 3 moves into it.
trees1021left32right2324basketstype 31 treetype 21 tree2bestwindow 2 trees → best stays 2
window2
best2
Two types again, so the window from tree 1 to tree 2 is legal. It is the longest legal stretch that ends at tree 2: starting any further left would keep the type that was just removed. It does not beat 2.
trees1021left3223right24basketstype 31 treetype 22 trees3besttype 2 goes in its basket → best 3
right3
types held2
window3
best3
Tree 3 has type 2, which already has a basket, so it fits for free. The window from tree 1 to tree 3 holds 3 trees and only 2 types, so it is a real way to pick 3 fruits. That beats the old best.
trees1021left322324rightbasketstype 31 treetype 23 trees4besttype 2 goes in its basket → best 4
right4
types held2
window4
best4
Tree 4 has type 2, which already has a basket, so it fits for free. The window from tree 1 to tree 4 holds 4 trees and only 2 types, so it is a real way to pick 4 fruits. That beats the old best.
trees1021322324basketstype 31 treetype 23 trees4bestanswer: 4 fruits, trees 1 to 4
answer4
Every tree has joined the window once and left it at most once. The longest legal stretch was trees 1 to 4, so the most fruit you can collect is 4.
05

Common pitfalls

Leaving a type in the map at count 0

✗ Wrong
count[out] -= 1
left += 1
✓ Right
count[out] -= 1
if count[out] == 0:
    del count[out]
left += 1

The 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

✗ Wrong
while right - left + 1 > 2:
✓ Right
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

✗ Wrong
best = max(best, right - left)
✓ Right
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.

06

Edge cases

Only one fruit type, e.g. [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.

07

Complexity

Time
O(n)
Space
O(1)
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.
08

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.