Introduction
LeetCode 904: Fruit Into Baskets is a classic sliding window problem that tests your ability to track a limited number of distinct elements in a subarray.
The problem can be rephrased as:
Find the longest subarray containing at most 2 distinct types of elements.
This is a great example of using HashMap + sliding window to efficiently track counts of elements while expanding and shrinking the window.
If you’d like to try solving the problem first, you can attempt it here:
Try the problem on LeetCode:
https://leetcode.com/problems/fruit-into-baskets/
Problem Understanding
You are given:
- An array
fruitswherefruits[i]represents the type of fruit from treei - Two baskets, each can hold only one type of fruit
Rules:
- Start at any tree and move only to the right
- Pick exactly one fruit from each tree while moving
- Stop when a tree’s fruit cannot fit in your baskets
Goal: Return the maximum number of fruits you can pick.
Examples:
A naive approach would check all subarrays, count distinct fruits, and pick the max →
- Time Complexity: O(n²) → too slow for
fruits.lengthup to 10⁵
Key Idea: Sliding Window with At Most Two Types
Instead of brute-force:
- Track the number of each fruit type in the current window using a HashMap
- Use two pointers
iandjfor the window - Expand
jby addingfruits[j]to the map - If the number of distinct types
mp.size()exceeds 2: - Shrink the window from the left (
i) untilmp.size() <= 2 - The window length
j - i + 1gives the max fruits collected so far
Intuition:
- Only two baskets → window can contain at most 2 distinct fruits
- The sliding window efficiently finds the longest subarray with ≤ 2 distinct elements
Approach (Step-by-Step)
- Initialize
i = 0,j = 0for window pointers - Initialize HashMap
mpto store fruit counts - Initialize
co = 0→ maximum fruits collected - Iterate
joverfruits: - Add
fruits[j]to the map - Check
mp.size(): - If ≤ 2 → update
co = max(co, j - i + 1) - If > 2 → shrink window from
iuntilmp.size() <= 2 - Continue expanding the window
- Return
coas the maximum fruits collected
Optimization:
- HashMap keeps track of counts → no need to scan subarray repeatedly
- Sliding window ensures linear traversal
Implementation (Java)
Dry Run Example
Input:
Execution:
Window [i, j] | Fruit counts mp | Distinct Types | Valid? | Max co |
| [0,0] → [1] | {1:1} | 1 | Yes | 1 |
| [0,1] → [1,2] | {1:1,2:1} | 2 | Yes | 2 |
| [0,2] → [1,2,3] | {1:1,2:1,3:1} | 3 | No → shrink | 2 |
| [1,2] → [2,3] | {2:1,3:1} | 2 | Yes | 2 |
| [1,3] → [2,3,2] | {2:2,3:1} | 2 | Yes | 3 |
| [1,4] → [2,3,2,2] | {2:3,3:1} | 2 | Yes | 4 |
Output:
Complexity Analysis
- Time Complexity: O(n) → Each element is added and removed at most once
- Space Complexity: O(1) → HashMap stores at most 2 types of fruits
Edge Cases Considered
- Array with ≤ 2 types → entire array can be picked
- Array with all same type → window length = array length
- Zeros or non-continuous fruit types → handled by sliding window
- Large arrays up to 10⁵ elements → O(n) solution works efficiently
Sliding Window Pattern Importance
This problem demonstrates the sliding window + frequency map pattern:
- Track limited number of distinct elements
- Expand/shrink window dynamically
- Efficiently compute max subarray length with constraints
It’s directly related to problems like:
- Max consecutive ones with flips
- Longest substring with k distinct characters
- Fruit collection / subarray problems with type limits
Conclusion
By tracking fruit counts with a HashMap in a sliding window, we efficiently find the maximum fruits collectible in O(n) time.
Mastering this pattern allows solving many array and string problems with constraints on distinct elements in a linear and elegant way.




