Fruit Into Baskets solution and explanation
9 more videos on this problem
L5. Fruit Into Baskets | 2 Pointers and Sliding Window Playlisttake U forward · 30:02 · 293K views
Fruits into Basket - Leetcode 904 - PythonNeetCodeIO · 10:12 · 35K views
LeetCode Fruit Into Baskets Solution Explained - JavaNick White · 9:07 · 25K views
Fruits in Basket (LeetCode 904) | Solution with diagrams and animations | Simplified explanationNikhil Lohia · 20:24 · 16K views
LeetCode 904. Fruit Into Baskets - Interview Prep Ep 102Fisher Coder · 15:12 · 3K views
904. Fruit Into Baskets | LeetCode Medium | Sliding WindowDeep Tech · 14:46 · 1K views
904. Fruit Into Baskets | Leetcode Daily - PythonLeetcode Daily · 6:58 · 661 views
904. Fruit Into Baskets | LeetCode Feb challenge | MediumPriyanshi Porwal · 15:58 · 661 views
Fruits Into Baskets Leetcode 9045 Minutes Code · 17:30 · 650 views
Leetcode 904 Fruits Into Basket (Java)TheAnalyticGuy · 11:15 · 611 views
The problem
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 <= 1050 <= 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
def totalFruit(fruits):
basket = {}
left = 0
max_fruits = 0
for right, fruit in enumerate(fruits):
basket[fruit] = basket.get(fruit, 0) + 1
while len(basket) > 2:
basket[fruits[left]] -= 1
if basket[fruits[left]] == 0:
del basket[fruits[left]]
left += 1
max_fruits = max(max_fruits, right - left + 1)
return max_fruitsimport java.util.HashMap;
public class Solution {
public int totalFruit(int[] fruits) {
HashMap<Integer, Integer> basket = new HashMap<>();
int left = 0, maxFruits = 0;
for (int right = 0; right < fruits.length; right++) {
basket.put(fruits[right], basket.getOrDefault(fruits[right], 0) + 1);
while (basket.size() > 2) {
basket.put(fruits[left], basket.get(fruits[left]) - 1);
if (basket.get(fruits[left]) == 0) basket.remove(fruits[left]);
left++;
}
maxFruits = Math.max(maxFruits, right - left + 1);
}
return maxFruits;
}
}#include <unordered_map>
#include <vector>
using namespace std;
int totalFruit(vector<int>& fruits) {
unordered_map<int, int> basket;
int left = 0, max_fruits = 0;
for (int right = 0; right < fruits.size(); ++right) {
basket[fruits[right]]++;
while (basket.size() > 2) {
basket[fruits[left]]--;
if (basket[fruits[left]] == 0) basket.erase(fruits[left]);
left++;
}
max_fruits = max(max_fruits, right - left + 1);
}
return max_fruits;
}function totalFruit(fruits) {
const basket = new Map();
let left = 0, maxFruits = 0;
for (let right = 0; right < fruits.length; right++) {
basket.set(fruits[right], (basket.get(fruits[right]) || 0) + 1);
while (basket.size > 2) {
basket.set(fruits[left], basket.get(fruits[left]) - 1);
if (basket.get(fruits[left]) === 0) basket.delete(fruits[left]);
left++;
}
maxFruits = Math.max(maxFruits, right - left + 1);
}
return maxFruits;
}using System.Collections.Generic;
public class Solution {
public int TotalFruit(int[] fruits) {
Dictionary<int, int> basket = new Dictionary<int, int>();
int left = 0, maxFruits = 0;
for (int right = 0; right < fruits.Length; right++) {
if (basket.ContainsKey(fruits[right]))
basket[fruits[right]]++;
else
basket[fruits[right]] = 1;
while (basket.Count > 2) {
basket[fruits[left]]--;
if (basket[fruits[left]] == 0) basket.Remove(fruits[left]);
left++;
}
maxFruits = Math.Max(maxFruits, right - left + 1);
}
return maxFruits;
}
}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.
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.
Approach 2: Two Pointer Technique
def totalFruit(fruits):
n = len(fruits)
if n < 3: return n
left, right = 0, 0
basket = {}
max_fruits = 0
while right < n:
if fruits[right] in basket or len(basket) < 2:
basket[fruits[right]] = right
right += 1
else:
min_index = min(basket.values())
del basket[fruits[min_index]]
left = min_index + 1
max_fruits = max(max_fruits, right - left)
return max_fruitsThis 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.
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.
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.
function totalFruit(fruits: number[]): number {
const n = fruits.length;
const cnt: Map<number, number> = new Map();
let ans = 0;
for (let i = 0, j = 0; i < n; ++i) {
cnt.set(fruits[i], (cnt.get(fruits[i]) || 0) + 1);
for (; cnt.size > 2; ++j) {
cnt.set(fruits[j], cnt.get(fruits[j])! - 1);
if (!cnt.get(fruits[j])) {
cnt.delete(fruits[j]);
}
}
ans = Math.max(ans, i - j + 1);
}
return ans;
}func totalFruit(fruits []int) int {
cnt := map[int]int{}
ans, j := 0, 0
for i, x := range fruits {
cnt[x]++
for ; len(cnt) > 2; j++ {
y := fruits[j]
cnt[y]--
if cnt[y] == 0 {
delete(cnt, y)
}
}
ans = max(ans, i-j+1)
}
return ans
}use std::collections::HashMap;
impl Solution {
pub fn total_fruit(fruits: Vec<i32>) -> i32 {
let mut cnt = HashMap::new();
let mut ans = 0;
let mut j = 0;
for (i, &x) in fruits.iter().enumerate() {
*cnt.entry(x).or_insert(0) += 1;
while cnt.len() > 2 {
let y = fruits[j];
j += 1;
*cnt.get_mut(&y).unwrap() -= 1;
if cnt[&y] == 0 {
cnt.remove(&y);
}
}
ans = ans.max(i - j + 1);
}
ans as i32
}
}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.
function totalFruit(fruits: number[]): number {
const n = fruits.length;
const cnt: Map<number, number> = new Map();
let j = 0;
for (const x of fruits) {
cnt.set(x, (cnt.get(x) || 0) + 1);
if (cnt.size > 2) {
cnt.set(fruits[j], cnt.get(fruits[j])! - 1);
if (!cnt.get(fruits[j])) {
cnt.delete(fruits[j]);
}
++j;
}
}
return n - j;
}func totalFruit(fruits []int) int {
cnt := map[int]int{}
j := 0
for _, x := range fruits {
cnt[x]++
if len(cnt) > 2 {
y := fruits[j]
cnt[y]--
if cnt[y] == 0 {
delete(cnt, y)
}
j++
}
}
return len(fruits) - j
}use std::collections::HashMap;
impl Solution {
pub fn total_fruit(fruits: Vec<i32>) -> i32 {
let mut cnt = HashMap::new();
let mut j = 0;
let n = fruits.len();
for &x in &fruits {
*cnt.entry(x).or_insert(0) += 1;
if cnt.len() > 2 {
let y = fruits[j];
j += 1;
*cnt.get_mut(&y).unwrap() -= 1;
if cnt[&y] == 0 {
cnt.remove(&y);
}
}
}
(n - j) as i32
}
}Complexity comparison
| 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 | – |
Complexity analysis
| 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. |
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.
