Home
DSA Patterns
Sliding Window
Fruit Into Baskets
Fruit Into Baskets (LeetCode 904)
Fruit Into Baskets (LeetCode 904): pick the most fruit with two baskets from consecutive trees: the longest sliding window with at most two distinct values.
Problem Understanding
Fruit Into Baskets: trees stand in a row and fruits[i] is the kind of fruit on tree i. You have two baskets, each holding any amount of a single kind. Starting at any tree, you pick one fruit from each tree moving right, and stop when a fruit fits neither basket. Return the most fruit you can pick.
Example: [1, 2, 3, 2, 2] returns 4: start at tree 1 and pick 2, 3, 2, 2.
The Intuition: At Most Two Kinds in the Window
Strip away the story: you want the longest run of consecutive trees with at most two distinct kinds. That is a variable-size sliding window with a count per kind, the same tool as Longest Substring Without Repeating Characters:
- Move
rightforward and countfruits[right]. - If the window now has three kinds, move
leftforward, decreasing counts, until one kind drops to zero and is removed. - Record
right − left + 1.
Each tree enters and leaves the window once, so the whole pass is O(n), and the map never holds more than three kinds.
Fruit Into Baskets Visualization
EACH CELL IS A TREE, LABELLED BY ITS FRUIT KIND · AT MOST 2 KINDS
EMPTY BASKETS
0
1
2
3
4
kinds
0
best
:
Answer
:
baskets (kind × count)
Empty
Two empty baskets. Find the longest run of trees with at most two kinds of fruit
Next
Pick tree 0 (kind 1): 1 kind in the window
fruits
Each cell is a tree labelled with its fruit kind. The shaded window is what the baskets hold, and the panel beside it shows each kind's count. Watch a third kind arrive and push the window forward until one basket empties.
Fruit Into Baskets Dry Run
Input: [1, 2, 3, 2, 2]
| right | Window | Baskets | Length |
|---|---|---|---|
| 0 | 0..0 | 1×1 | 1 |
| 1 | 0..1 | 1×1, 2×1 | 2 |
| 2 | 1..2 after dropping tree 0 | 2×1, 3×1 | 2 |
| 3 | 1..3 | 2×2, 3×1 | 3 |
| 4 | 1..4 | 2×3, 3×1 | 4 |
Fruit Into Baskets LeetCode Solution
Longest window with at most two distinct values. The C snippet counts kinds in an array, since kinds are below n.
Fruit Into Baskets Code
1var totalFruit = function(fruits) {2 const count = new Map();3 let left = 0, best = 0;4 for (let right = 0; right < fruits.length; right++) {5 count.set(fruits[right], (count.get(fruits[right]) || 0) + 1);6 while (count.size > 2) {7 const f = fruits[left++];8 count.set(f, count.get(f) - 1);9 if (count.get(f) === 0) count.delete(f);10 }11 best = Math.max(best, right - left + 1);12 }13 return best;14};
Fruit Into Baskets in Python, Java, C++, TypeScript and C
Fruit Into Baskets in Python
class Solution:
def totalFruit(self, fruits: List[int]) -> int:
count = defaultdict(int)
left = best = 0
for right, f in enumerate(fruits):
count[f] += 1
while len(count) > 2:
count[fruits[left]] -= 1
if count[fruits[left]] == 0:
del count[fruits[left]]
left += 1
best = max(best, right - left + 1)
return bestFruit Into Baskets in Java
class Solution {
public int totalFruit(int[] fruits) {
Map<Integer, Integer> count = new HashMap<>();
int left = 0, best = 0;
for (int right = 0; right < fruits.length; right++) {
count.merge(fruits[right], 1, Integer::sum);
while (count.size() > 2) {
int f = fruits[left++];
if (count.merge(f, -1, Integer::sum) == 0) count.remove(f);
}
best = Math.max(best, right - left + 1);
}
return best;
}
}Fruit Into Baskets in C++
class Solution {
public:
int totalFruit(vector<int>& fruits) {
unordered_map<int, int> count;
int left = 0, best = 0;
for (int right = 0; right < (int)fruits.size(); right++) {
count[fruits[right]]++;
while (count.size() > 2) {
int f = fruits[left++];
if (--count[f] == 0) count.erase(f);
}
best = max(best, right - left + 1);
}
return best;
}
};Fruit Into Baskets in TypeScript
function totalFruit(fruits: number[]): number {
const count = new Map<number, number>();
let left = 0, best = 0;
for (let right = 0; right < fruits.length; right++) {
count.set(fruits[right], (count.get(fruits[right]) || 0) + 1);
while (count.size > 2) {
const f = fruits[left++];
count.set(f, count.get(f)! - 1);
if (count.get(f) === 0) count.delete(f);
}
best = Math.max(best, right - left + 1);
}
return best;
}Fruit Into Baskets in C
int totalFruit(int* fruits, int fruitsSize) {
int* count = calloc(fruitsSize, sizeof(int));
int left = 0, best = 0, kinds = 0;
for (int right = 0; right < fruitsSize; right++) {
if (count[fruits[right]]++ == 0) kinds++;
while (kinds > 2) {
if (--count[fruits[left++]] == 0) kinds--;
}
if (right - left + 1 > best) best = right - left + 1;
}
free(count);
return best;
}Edge Cases & Common Mistakes
- Only one or two kinds: the whole row fits; return n.
- Not deleting zero counts: the map size stays too large and the window shrinks too far.
- Resetting the window to the last tree on a third kind: the right restart point is after the last tree of the kind being dropped, not always one tree back.
- Every tree a different kind: the answer is 2 (or 1 for a single tree).
Summary
Two single-kind baskets on consecutive trees means the longest window with at most two distinct values. Count kinds in a map, add on the right, drop from the left until only two kinds remain, and track the longest window. O(n) time, O(1) space.
More practice: DSA interview questions with answers · patterns cheat sheet
