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:
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 <= 1050 <= fruits[i] < fruits.lengthProblem 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.
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.
Python
C++
Java
C#
JavaScript
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.
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.
Python
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.
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.
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.
| Approach | Complexity |
|---|---|
| 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). |
| Two Pointer Technique | Time Complexity: O(n), as we ensure each element is considered just a limited number of times. |
| Hash Table + Sliding Window | — |
| Monotonic Variable-Length Sliding Window | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Sliding Window with HashMap | O(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. |
L5. Fruit Into Baskets | 2 Pointers and Sliding Window Playlist • take U forward • 256,144 views views
Watch 9 more video solutions →Practice Fruit Into Baskets with our built-in code editor and test cases.
Practice on FleetCode