15% off all plans & roadmaps Use code

See plans

Fruit Into Baskets

Updated

TL;DR: You need the longest run of neighboring trees that holds at most two fruit types. A window that grows on the right and shrinks on the left whenever a third type appears finds it in one pass.

Problem

You are visiting a farm with a single row of fruit trees, arranged from left to right. The integer array fruits gives the type of fruit that each tree produces. Tree i produces fruits[i].

You want to pick as much fruit as possible, under the owner's strict rules. You have only two baskets. Each basket can hold only a single type of fruit, with no limit on the amount.

Starting from any tree you choose, you must pick exactly one fruit from every tree as you move right. That includes the start tree. The picked fruit must fit in your baskets. When you reach a tree whose fruit does not fit, you must stop.

Return the maximum number of fruits you can pick.

Example 1

Input: fruits = [1,2,1]
Output: 3
Explanation: We can pick from all 3 trees.

Example 2

Input: fruits = [0,1,2,2]
Output: 3
Explanation: We can pick from trees [1,2,2]. If we had started at the first tree, we would only pick from trees [0,1].

Example 3

Input: fruits = [1,2,3,2,2]
Output: 4
Explanation: We can pick from trees [2,3,2,2]. If we had started at the first tree, we would only pick from trees [1,2].

Constraints

  • 1 <= fruits.length <= 10^5
  • 0 <= fruits[i] < fruits.length

Constraints that matter

  • n up to 10^5 rules out the O(n^2) brute force, which can do about 5 * 10^9 pair checks in the worst case.
  • The pick must be contiguous, so every candidate answer is a range of indices [left, right]. Two pointers can describe every candidate.
  • fruits[i] < n means each type value is a small index, so a plain array can replace the map as a counter.
  • Only two baskets means at most two real keys survive between steps. The counter holds at most three keys while it shrinks.

View on LeetCode

Hints

Hint 1

The problem asks for the longest stretch of neighboring trees that holds at most two fruit types.

Hint 2

Start at every tree and walk right, keeping a set of the fruit types seen.

Solution

Intuition

The problem asks for the longest stretch of neighboring trees that holds at most two fruit types. Neighboring means contiguous, so every candidate is a window of indices. A window is fully described by its left edge and its right edge.

Picture two sticky notes on a row of trees, each marking the last tree you saw of one fruit type. When a third fruit shows up, you peel off the older note and start your window right after it.

Look at what breaks the rule. A window only fails when a third type enters on the right, and any smaller window inside a valid one is also valid. So you can grow the window to the right and shrink it from the left only when the rule breaks. This is the variable-size sliding window (condition-based) pattern.

Each tree joins the window once and leaves it at most once. That makes the total work linear. The brute force wastes this by restarting at every tree and rescanning trees it has already read.

Watch the pattern animation

Worked example

Input: fruits = [0, 1, 2, 3, 4, 5]
Output: 2
Explanation: All six trees have different types, so no window can hold three trees. Any two neighboring trees form a valid window, and that is the longest possible. The walk starting at tree 0 stops at tree 2, and every other start does the same.

Approach 1: Brute force

Start at every tree and walk right, keeping a set of the fruit types seen. Stop the walk when the set holds a third type, and record the length of each valid walk. This is the naive version a beginner writes first. It tries every start, so the same trees get read again and again.

Steps

  1. Set best to 0.
  2. For each start index, create an empty set of types.
  3. Walk end from start to the last tree. Add fruits[end] to the set.
  4. If the set has more than two types, stop this walk.
  5. Otherwise update best with end - start + 1.
  6. Return best after all starts have been tried.

Dry run

Use the example fruits = [0, 1, 2, 3, 4, 5].

  • Start 0 adds fruit 0, then fruit 1. The walk length is 2, so best is 2. Adding fruit 2 gives a third type, so the walk stops.
  • Start 1 adds fruit 1, then fruit 2 for length 2. Adding fruit 3 stops the walk.
  • Starts 2 through 5 each give a length of at most 2.

The longest valid walk has length 2, which matches the output.

Complexity

TimeO(n^2)
SpaceO(1)

Let n be the number of trees. For start index i, the inner loop runs at most n - i times, and it stops early when a third type appears. In the worst case, such as 0, 1, 0, 1, and so on, it never stops early, so the total is n + (n-1) + ... + 1 = n(n+1)/2 steps, which is O(n^2). The set never holds more than three values because the walk breaks on the third one, so the space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def totalFruit(self, fruits: List[int]) -> int:
        n = len(fruits)
        best = 0
        for start in range(n):
            # Fresh set of fruit types for each start
            types = set()
            for end in range(start, n):
                types.add(fruits[end])
                if len(types) > 2:
                    break
                best = max(best, end - start + 1)
        return best

The Variable Size (Condition-Based) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Variable Size (Condition-Based)

Part of Sliding Window

Approach 2: Sliding window with a count mapVariable Size (Condition-Based)

What's slow: the brute force throws away everything it learned when the start moves one tree right. Starting at index 1 rebuilds counts that index 0 already built for the trees from index 1 onward.

The insight that fixes it: keep one window that only moves forward. When a third type enters, drop trees from the left until only two types remain. A count per type tells you exactly when a type has left the window, because its count reaches zero.

Steps

  1. Create an empty count map. Set left and best to 0.
  2. For each index right, add fruits[right] to the map and increase its count.
  3. While the map has more than two keys, decrease the count of fruits[left].
  4. If that count reaches 0, delete the key. Then increase left by 1.
  5. After the shrink loop, update best with right - left + 1.
  6. Return best after the loop.

Dry run

Use the example fruits = [0, 1, 2, 3, 4, 5].

  • right = 0, fruit 0: counts {0:1}, window [0,0], best 1.
  • right = 1, fruit 1: counts {0:1, 1:1}, window [0,1], best 2.
  • right = 2, fruit 2: three keys. Remove index 0. Its count hits 0, so the key goes. Counts {1:1, 2:1}, left = 1, window [1,2], best stays 2.
  • right = 3, fruit 3: three keys. Remove index 1. Counts {2:1, 3:1}, left = 2, window [2,3].
  • right = 4 and right = 5 repeat the pattern. Each window has length 2.

The output is 2.

Complexity

TimeO(n)
SpaceO(1)

Let n be the number of trees, and the right pointer makes n steps. The left pointer only increases and never passes right + 1, so it moves at most n times in total. Each step does one map update that costs O(1) on average, so the work is at most about 2n map operations, which is O(n). The map never holds more than three keys before a shrink, so the space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def totalFruit(self, fruits: List[int]) -> int:
        counts = {}  # fruit type -> how many sit in the window
        left = 0
        best = 0
        for right, f in enumerate(fruits):
            counts[f] = counts.get(f, 0) + 1
            # Shrink until at most two types remain
            while len(counts) > 2:
                g = fruits[left]
                counts[g] -= 1
                if counts[g] == 0:
                    del counts[g]
                left += 1
            best = max(best, right - left + 1)
        return best

Approach 3: Last-seen pair, one passOptimal

What's slow: the count map stores a count for every type, and it spends work deciding when a type has left the window. Look at the window again. It holds at most two types. For each type you only need the index of its last tree.

The insight that fixes it: when a third type arrives, the older of the two window types is the one to drop. Its last tree is the last point where it appears, so the window must start right after that tree. Two slots with two last-seen indices replace the whole map.

Why it is correct. At each index, the window is the longest valid run ending there. When a third type appears, keeping the newer of the two types keeps the most trees in the window. Dropping the older type is the only move that restores two types while losing the fewest trees.

Steps

  1. Keep two type slots, typeA and typeB, with their last-seen indices lastA and lastB. Set all four to -1.
  2. Keep start (the left edge of the window) and best, both starting at 0.
  3. For each index i, if the fruit matches typeA, set lastA = i. Otherwise, if it matches typeB, set lastB = i.
  4. If the fruit matches neither slot, it is a third type. Drop the slot with the smaller last index, set start to that index plus 1, and put the new fruit in that slot with index i.
  5. After each index, update best with i - start + 1.
  6. Return best.

Dry run

Use the example fruits = [0, 1, 2, 3, 4, 5]. Each row shows the state after processing index i.

ifruittypeA (lastA)typeB (lastB)startbestaction
00-1 (-1)0 (0)01Neither slot matches. Both last indices are -1, so slot B takes the fruit. start = -1 + 1 = 0.
111 (1)0 (0)02Neither slot matches. lastA = -1 is older than lastB = 0, so slot A takes the fruit. start = 0.
221 (1)2 (2)12Neither slot matches. lastA = 1 is not older than lastB = 0, so slot B takes the fruit. start = 0 + 1 = 1.
333 (3)2 (2)22lastA = 1 is older than lastB = 2, so slot A takes the fruit. start = 1 + 1 = 2.
443 (3)4 (4)32lastA = 3 is not older than lastB = 2, so slot B takes the fruit. start = 2 + 1 = 3.
555 (5)4 (4)42lastA = 3 is older than lastB = 4, so slot A takes the fruit. start = 3 + 1 = 4.

The final best is 2, which matches the output.

Complexity

TimeO(n)
SpaceO(1)

Let n be the number of trees, and the loop runs once for each index. Each branch does a fixed number of comparisons and assignments, so each step costs O(1), and the total is O(n). The state is two types, two last indices, start, best and i. None of these grows with n, so the space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def totalFruit(self, fruits: List[int]) -> int:
        type_a, type_b = -1, -1  # the two fruit types in the window
        last_a, last_b = -1, -1  # index where each type last appeared
        start = 0
        best = 0
        for i, f in enumerate(fruits):
            if f == type_a:
                last_a = i
            elif f == type_b:
                last_b = i
            elif last_a < last_b:
                # Drop type_a: the window starts after its last tree
                start = last_a + 1
                type_a, last_a = f, i
            else:
                start = last_b + 1
                type_b, last_b = f, i
            best = max(best, i - start + 1)
        return best

Common mistakes

  • Using if where the shrink needs while. One new fruit can force several removals. In [1,1,1,2,3], adding 3 needs three left moves before only two types remain. Fix: loop with while len(counts) > 2.
  • Leaving zero-count keys in the map, as in counts[g] -= 1 with no delete. The map size stays at 3, so the window shrinks too far. Fix: delete the key the moment its count reaches 0.
  • Recording best before the shrink loop. That counts a window that still holds three types. Fix: update best only after the window is valid again.
  • In the last-seen version, writing start = lastA + 1 without comparing last indices. That can drop the more recent type. Fix: drop the slot with the smaller last index.
  • Skipping lastA = i when the fruit matches typeA. The stored index goes stale, so start falls too far left and the window keeps a dropped type. Fix: refresh the last index on every match.
  • In the brute force, sharing one set across all starts. The set keeps types from the previous start, so the walk stops too early or counts wrong types. Fix: create a fresh set for each start.

Edge cases

  • [0] returns 1. A single tree is a valid window of length 1.
  • [0, 0, 0, 0] returns 4. One type never breaks the rule, so the window never shrinks.
  • [0, 1, 0, 1, 0] returns 5. Two alternating types fit in the window, so the whole array is valid.
  • [0, 1, 2] returns 2. Three types cannot all fit, so the answer is a two-tree window at either end.
  • [1, 1, 1, 2, 3] returns 4. The window [1,1,1,2] is valid, and the shrink must remove three 1s after adding 3.
  • Maximum size with n = 10^5 and all values distinct returns 2. The window never grows past two trees, so the code must still run in linear time.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Fruit Into Baskets, with how to answer them.

Unlock the follow-ups

Fruit Into Baskets FAQ

What is the time complexity of Fruit Into Baskets?

The sliding window and last-seen approaches run in O(n) time, where n is the number of trees. The brute force runs in O(n^2) time because it can rescan almost the whole array from every start. The O(n) approaches visit each index a constant number of times.

Why use a sliding window for Fruit Into Baskets?

The answer is the longest contiguous range with a simple condition. The condition only breaks when a new type enters on the right, so a window that moves forward handles every candidate in one pass. Restarting at each tree repeats work the window already did.

Can Fruit Into Baskets be solved in O(1) extra space?

Yes. The last-seen version stores two types, two last indices, the start index and the best length. The count map is also O(1) here because it never holds more than three keys. Both answers are constant in space regardless of n.

Can I use a queue or deque for Fruit Into Baskets?

A deque can store the window's positions in order, and popping the front shrinks the window from the left. It still needs per-type counts to know when a type has left, so the deque adds steps without saving work. The count map or the last-seen pair is the simpler choice.

Is this the same as longest substring with at most two distinct characters?

Yes. The window logic is identical, and only the values change from fruit types to characters. A character version uses the same count map or last-seen pair.

Asked at

See which companies ask this — Pro

Practise it