Fruit Into Baskets (LeetCode 904): Solution and Explanation

Medium
Array
Hash Table
Sliding Window

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

  1. Keep count, a map from fruit type to how many of it are in the window, plus left = 0 and best = 0.
  2. For each right, add one to count[fruits[right]].
  3. While count holds more than two types, subtract one from count[fruits[left]], remove that type if it reaches zero, and move left one step right.
  4. The window [left, right] now has at most two types. Set best = max(best, right - left + 1).
  5. Return best.

Step-by-step example

fruits = [1,2,1]
  1. right = 0: type 1 takes the first basket. The window is [0, 0], length 1, so best = 1.
  2. right = 1: type 2 takes the second basket. The window is [0, 1], length 2, so best = 2.
  3. right = 2: type 1 already has a basket, so its count becomes 2. The window is [0, 2], length 3, so best = 3.
  4. 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 best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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 left only 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 left to right - 1 on a new type. The window should keep the whole final run of the previous type, not just one tree.
  • Recording best inside 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.