Skip to main content

Fruit Into Baskets - Solution & Explanation

MediumArrayHash TableSliding Window22 min readAsked at: Amazon, Microsoft, Meta +8
Practice this problem

Problem Statement

You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces.

You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:

  • You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold.
  • Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.
  • Once you reach a tree with fruit that cannot fit in your baskets, you must stop.

Given the integer array fruits, 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 <= 105
  • 0 <= fruits[i] < fruits.length

Approach Overview

Problem Overview: You receive an integer array where each value represents a fruit type on a tree. Starting from any index, you can collect fruits moving right, but your baskets can hold only two distinct fruit types. The task is to find the maximum number of fruits you can pick while maintaining this constraint.

Approach 1: Sliding Window with HashMap (O(n) time, O(1) space)

This problem reduces to finding the longest subarray with at most two distinct values. The most reliable method uses a sliding window. Maintain two pointers left and right representing the current window, and a hash map storing fruit counts inside the window. As you iterate with the right pointer, update the map with the current fruit type. If the map grows beyond two types, move the left pointer forward while decrementing counts until only two types remain.

The key insight: every valid window represents a sequence where both baskets hold a fruit type. Expanding the window maximizes collected fruits, while shrinking keeps the constraint valid. Each element enters and leaves the window at most once, giving O(n) time complexity. Because the map stores at most two fruit types, the space complexity is effectively O(1). This technique is a classic application of the sliding window pattern on an array with a frequency hash table.

Approach 2: Two Pointer Technique (O(n) time, O(1) space)

The two pointer variation tracks the last contiguous segment of the second fruit type instead of storing full counts. Use variables to remember the last fruit type, the second last fruit type, and the length of the most recent streak. When you encounter a fruit matching one of the two tracked types, extend the window. If a third type appears, reset the window so it starts from the previous streak of the last fruit type.

This approach eliminates the explicit hash map and relies on pointer movement and state tracking. The algorithm still processes each element once, giving O(n) time and constant O(1) space. It is slightly harder to reason about but performs well when memory overhead must be minimized.

Recommended for interviews: The sliding window with a hash map is the expected solution. It clearly expresses the constraint "at most two distinct values" and generalizes easily to problems like "longest substring with k distinct characters." Showing the brute reasoning first and then implementing the optimal sliding window demonstrates strong problem‑solving skills.

Approach 1: Sliding Window with HashMap

The sliding window technique is effective for problems involving contiguous subarrays. The goal is to maintain two baskets each holding one type of fruit. We'll use a hashmap to track the count of each fruit type in our current window. When encountering a third type of fruit, shrink the window from the left until only two types remain.

This code uses a sliding window approach with a hashmap to keep track of fruit counts. The window expands by incrementing 'right' and shrinks from 'left' when more than two types of fruits are in the window. The 'max_fruits' variable is updated with the size of the largest valid window found.

Code

Python

C++

Java

C#

JavaScript

Complexity

Time Complexity: O(n), where n is the length of the fruits array, as each element is processed at most twice (once added and once removed).
Space Complexity: O(1), as the hashmap will hold at most three entries at any time, which is constant space.

Try this approach in the editor →

Approach 2: Two Pointer Technique

This approach employs two pointers to define the current valid subarray and efficiently manage the types of fruits in each basket. By maintaining direct pointers to the position where the current types of fruits change, the solution dynamically adjusts the size of the valid subarray.

This Python function uses two pointers to dynamically track potential subarrays with at most two different types of fruits. The dict `basket` tracks the latest positions of the current fruit types, allowing direct jumps in the array and optimizing the process of finding a new valid window.

Code

Python

Complexity

Time Complexity: O(n), as we ensure each element is considered just a limited number of times.
Space Complexity: O(1), since the additional storage for control variables is constant.

Try this approach in the editor →

Approach 3: Hash Table + Sliding Window

We use a hash table cnt to maintain the types and corresponding quantities of fruits in the current window, and use two pointers j and i to maintain the left and right boundaries of the window.

We traverse the fruits array, add the current fruit x to the window, i.e., cnt[x]++, then judge whether the types of fruits in the current window exceed 2. If it exceeds 2, we need to move the left boundary j of the window to the right until the types of fruits in the window do not exceed 2. Then we update the answer, i.e., ans = max(ans, i - j + 1).

After the traversal ends, we can get the final answer.

1 2 3 2 2 1 4
^   ^
j   i


1 2 3 2 2 1 4
  ^ ^
  j i


1 2 3 2 2 1 4
  ^     ^
  j     i

The time complexity is O(n), and the space complexity is O(1). Here, n is the length of the fruits array.

Code

Python

Java

C++

Go

TypeScript

Rust

C#

Try this approach in the editor →

Approach 4: Monotonic Variable-Length Sliding Window

In Solution 1, we find that the window size sometimes increases and sometimes decreases, which requires us to update the answer each time.

But what this problem actually asks for is the maximum number of fruits, that is, the "largest" window. We don't need to shrink the window, we just need to let the window monotonically increase. So the code omits the operation of updating the answer each time, and only needs to return the size of the window as the answer after the traversal ends.

The time complexity is O(n), and the space complexity is O(n), where n is the length of the fruits array.

Code

Python

Java

C++

Go

TypeScript

Rust

C#

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Sliding Window with HashMap

Time Complexity: O(n), where n is the length of the fruits array, as each element is processed at most twice (once added and once removed).
Space Complexity: O(1), as the hashmap will hold at most three entries at any time, which is constant space.

Two Pointer Technique

Time Complexity: O(n), as we ensure each element is considered just a limited number of times.
Space Complexity: O(1), since the additional storage for control variables is constant.

Hash Table + Sliding Window—
Monotonic Variable-Length Sliding Window—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Sliding Window with HashMapO(n)O(1)General solution for longest subarray with at most two distinct elements. Most readable and common in interviews.
Two Pointer Technique (State Tracking)O(n)O(1)Useful when avoiding hash maps and optimizing constant memory usage.

Video Solution

L5. Fruit Into Baskets | 2 Pointers and Sliding Window Playlist • take U forward • 293,066 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Fruit Into Baskets easy or hard?
Fruit Into Baskets is typically rated Medium because it requires recognizing the sliding window pattern and managing dynamic constraints on distinct elements. Once you know the template for 'at most k distinct elements', the implementation becomes straightforward.
How to solve Fruit Into Baskets in O(n)?
Use the sliding window technique. Track the count of fruit types in the current window using a hash map. Expand the window with the right pointer and update counts. When the map size exceeds two, move the left pointer forward and decrement counts until only two fruit types remain, updating the maximum window length during the process.
What is the best approach for Fruit Into Baskets?
The sliding window approach with a hash map is the most common solution. Maintain a window containing at most two distinct fruit types while expanding the right pointer. If a third type appears, move the left pointer until only two remain. This runs in O(n) time with O(1) space because the map stores at most two keys.
Is Fruit Into Baskets asked at Google/Amazon/Meta?
Fruit Into Baskets is a common sliding window interview problem and appears in preparation lists for companies like Amazon, Google, and Meta. Variants such as 'longest substring with k distinct characters' or 'at most two distinct elements' frequently show up in coding interviews.
What data structure is used in Fruit Into Baskets?
The standard solution uses a hash table (hash map) to store the frequency of fruit types inside the sliding window. Combined with two pointers, this structure allows constant-time updates and quick checks on how many distinct fruit types are currently in the window.
What is the time complexity of Fruit Into Baskets?
The optimal solution runs in O(n) time. Each element is processed at most twice—once when the right pointer expands the window and once when the left pointer shrinks it. The auxiliary space is O(1) since the frequency map holds no more than two fruit types.
Fruit Into Baskets Python or Java solution approach?
Both Python and Java implementations follow the same sliding window pattern. Use two pointers and a dictionary or HashMap to count fruit occurrences. Expand the window while the map has two or fewer keys, and shrink it when a third fruit type appears, keeping track of the maximum length.

Ready to solve this problem?

Practice Fruit Into Baskets with our built-in code editor and test cases.

Practice on FleetCode