Fruit Into Baskets

Medium

Topics
ArrayHash TableSliding Window

A row of fruit trees stands along a path, and fruits[i] is the kind of fruit tree i bears. You carry two baskets, and each basket may only ever hold one kind of fruit (any amount of it).

Pick any tree to start at, then walk right, taking exactly one fruit from every tree you pass, including the first. You must stop as soon as you reach a tree whose fruit fits in neither basket. Return the largest number of fruits you can collect.

Put plainly: return the length of the longest contiguous stretch of fruits that contains at most two distinct values.

Example 1

4041724394length 4
Two baskets means at most two distinct values in the window. The braced run is the longest such stretch, 4 fruit. Counting kinds in a map lets the left edge advance only as far as needed instead of restarting.
Cells are the array values; the small numbers underneath are indices.
Input:  fruits = [4,4,7,4,9]
Output: 4
Explanation: Trees 0 to 3 hold only kinds 4 and 7.

Example 2

10213233242516length 5
Input:  fruits = [1,2,3,3,2,2,1]
Output: 5
Explanation: Trees 1 to 5: [2,3,3,2,2].

Example 3

60length 1
Input:  fruits = [6]
Output: 1

Constraints

  • 1 <= fruits.length <= 10^5
  • 0 <= fruits[i] <= 10^5
Editorial — intuition, approach, complexity and pitfalls

Intuition

Strip the story away and you need the longest window with at most two distinct values. Windows with that property are closed under shrinking, so a sliding window with a count per value fits exactly.

Approach

  1. Keep a map from fruit kind to its count inside the window [l, r].
  2. Add fruits[r]. While the map has more than two keys, decrement fruits[l], delete it at zero, and advance l.
  3. Record r - l + 1 and return the maximum.

Dry Run

fruits = [1, 2, 3, 3, 2, 2, 1]   --  "at most 2 kinds" is the window condition
  r=0 add 1   counts {1:1}          left=0  len 1   best 1
  r=1 add 2   counts {1:1, 2:1}     left=0  len 2   best 2
  r=2 add 3   three kinds, shrink: 1 evicted
              counts {2:1, 3:1}     left=1  len 2   best 2
  r=3 add 3   counts {2:1, 3:2}     left=1  len 3   best 3
  r=4 add 2   counts {2:2, 3:2}     left=1  len 4   best 4
  r=5 add 2   counts {2:3, 3:2}     left=1  len 5   best 5
  r=6 add 1   three kinds, shrink: 2 down to 2, then 3 down to 1, then 3 evicted
              counts {2:2, 1:1}     left=4  len 3   best 5
answer 5   --  the run 2 3 3 2 2 at indices 1..5
The left pointer never moves backwards, which is what makes this O(n) rather than
O(n^2): each index is added once and evicted at most once, so the total work is
linear even though the inner while loop looks nested.
Row r=6 is the one to follow. Three evictions happen but only the third removes a
KEY -- 2 and 3 are decremented first and only 3 reaches zero. The count is what
tells you when a kind has genuinely left the window, which is why the map holds
counts rather than just the two kinds.
Delete on the first decrement instead of at zero and the window can lose a kind
it still contains. This input does not show it, but [4,4,4,2,1,4,1,4] does: the
answer is 4 and the broken version reports 5. Across 20000 random inputs the two
disagree 6059 times.

Complexity

  • Time — O(n): each index enters and leaves the window once.
  • Space — O(1): the map never holds more than three keys.

Common Pitfalls

  • Remembering only the last two kinds without counts fails on inputs like [1,2,1,3], where shrinking must stop at the right place.
  • Delete a kind from the map only when its count reaches zero, not on the first decrement. The page's example does not expose this; [4,4,4,2,1,4,1,4] does, answering 4 where the broken version reports 5. Across 20000 random inputs the two disagree 6059 times.

Full Solution — all languages

class Solution:
    def totalFruit(self, fruits):
        counts = {}
        left = 0
        best = 0
        for right, kind in enumerate(fruits):
            counts[kind] = counts.get(kind, 0) + 1
            while len(counts) > 2:
                drop = fruits[left]
                counts[drop] -= 1
                if counts[drop] == 0:
                    del counts[drop]
                left += 1
            best = max(best, right - left + 1)
        return best
Asked at Expedia Netflix
SensAI
Beta
Tap the mic to stop voice mode