Fruit Into Baskets

Longest subarray with at most two distinct values — variable window with a small frequency map.

Medium
Time O(n) Space O(1)
LeetCode
3 min read
sliding-window hash-map

Problem#

fruits[i] is the fruit type at tree i. You can carry two baskets; each basket only takes one type. Walk down the row picking one fruit per tree, in order, never skipping. Return the maximum number of fruits.

Examples#

  • [1,2,1]3
  • [0,1,2,2]3
  • [1,2,3,2,2]4

Constraints#

  • 1 <= fruits.length <= 10^5.

Approach#

Longest subarray with at most 2 distinct values. Variable window with a frequency map; shrink while the map has 3 entries.

Solution#

Fruit Into Baskets
class Solution {
public:
int totalFruit(vector<int>& fruits) {
unordered_map<int,int> freq;
int left = 0, best = 0;
for (int right = 0; right < (int)fruits.size(); ++right) {
++freq[fruits[right]];
while (freq.size() > 2) {
if (--freq[fruits[left]] == 0) freq.erase(fruits[left]);
++left;
}
best = max(best, right - left + 1);
}
return best;
}
};

Editorial#

Generic “at most K distinct” template — replace the > 2 constant with > K. The frequency map’s size is the distinct count, so checking it directly is a one-line invariant. Erasing on zero count keeps the map tight; not erasing also works but inflates map size and confuses the distinct count.

Complexity#

  • Time: O(n).
  • Space: O(1) (at most 3 keys live).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.