Fruit Into Baskets (LeetCode 904): Solution and Explanation
Walk right along a row of fruit trees with two baskets, each limited to one fruit type, and pick one fruit per tree. Return the most fruit you can collect before a third type forces you to stop.
Intuition
Strip away the story and the task is: find the longest contiguous stretch of the array that contains at most two different values. Each basket stands for one allowed value, and the number of fruits is the length of the stretch.
Trying every starting tree and walking right until a third type appears works, but it repeats a lot of walking and costs O(n^2) in the worst case.
Notice that when a third type shows up at right, the next valid stretch that includes right can only start later. So instead of restarting, keep the window and move its left edge forward, putting fruit back, until one of the old types is gone entirely. Then the newcomer has a free basket.
A small count map tells you when a type is gone: its count hits zero. The left edge only moves forward and the right edge only moves forward, so each tree enters and leaves the window at most once.
Approach: Sliding window with a type count
- Keep
count, a map from fruit type to how many of it are in the window, plusleft = 0andbest = 0. - For each
right, add one tocount[fruits[right]]. - While
countholds more than two types, subtract one fromcount[fruits[left]], remove that type if it reaches zero, and moveleftone step right. - The window
[left, right]now has at most two types. Setbest = max(best, right - left + 1). - Return
best.
Step-by-step example
fruits = [1,2,1]
right = 0: type 1 takes the first basket. The window is[0, 0], length 1, sobest = 1.right = 1: type 2 takes the second basket. The window is[0, 1], length 2, sobest = 2.right = 2: type 1 already has a basket, so its count becomes 2. The window is[0, 2], length 3, sobest = 3.- No third type ever appears, so the answer is 3.
Code: Python, Java, C++
1class Solution:
2 def totalFruit(self, fruits: List[int]) -> int:
3 count = {}
4 left = best = 0
5 for right, f in enumerate(fruits):
6 count[f] = count.get(f, 0) + 1
7 while len(count) > 2:
8 out = fruits[left]
9 count[out] -= 1
10 if count[out] == 0:
11 del count[out]
12 left += 1
13 best = max(best, right - left + 1)
14 return best1class Solution {
2 public int totalFruit(int[] fruits) {
3 Map<Integer, Integer> count = new HashMap<>();
4 int left = 0, best = 0;
5 for (int right = 0; right < fruits.length; right++) {
6 count.merge(fruits[right], 1, Integer::sum);
7 while (count.size() > 2) {
8 int out = fruits[left];
9 count.put(out, count.get(out) - 1);
10 if (count.get(out) == 0) {
11 count.remove(out);
12 }
13 left++;
14 }
15 best = Math.max(best, right - left + 1);
16 }
17 return best;
18 }
19}1class Solution {
2public:
3 int totalFruit(vector<int>& fruits) {
4 unordered_map<int, int> count;
5 int left = 0, best = 0;
6 for (int right = 0; right < (int)fruits.size(); right++) {
7 count[fruits[right]]++;
8 while (count.size() > 2) {
9 int out = fruits[left];
10 if (--count[out] == 0) {
11 count.erase(out);
12 }
13 left++;
14 }
15 best = max(best, right - left + 1);
16 }
17 return best;
18 }
19};Time and space complexity
O(n)
right visits each tree once and left moves forward at most n times in total, so the inner loop adds O(n) across the whole run.
O(1)
The count map never holds more than three types at once.
Other approaches
Track the last run (time O(n), space O(1))
Instead of a map, remember the two current types and the length of the final run of the most recent type. When a third type arrives, the new window is that last run plus the new fruit. This avoids hashing but is easier to get wrong.
Restart from every tree (time O(n^2), space O(1))
For each starting tree, walk right collecting types in a set until a third appears. Simple to reason about but quadratic on long two-type stretches.
Common mistakes
- Moving
leftonly once when a third type arrives. You must keep moving it until one old type's count reaches zero, which can take many steps. - Forgetting to delete a type whose count reaches zero, so the map size never drops back to two and the loop runs too long.
- Jumping
lefttoright - 1on a new type. The window should keep the whole final run of the previous type, not just one tree. - Recording
bestinside the shrinking loop, where the window still has three types.
Frequently asked questions
Is this the same as Longest Substring with At Most K Distinct Characters?
Yes, with k = 2 and integers instead of characters. The same sliding window solves both.
Why is the inner while loop still O(n) overall?
Each iteration moves left one step right, and left never moves back. Across the whole run it moves at most n times, no matter how the iterations are spread over the outer loop.
Does it matter where I start picking?
The window handles that for you. Every possible start is represented by some position of left, and the window keeps the longest valid one ending at each right.