Algo-Sim › Sliding Window

Fruit Into Baskets

Medium · Sliding Window · step through it in Java, Python and C++ on your own input

Longest window with at most two distinct values: grow on the right, shrink from the left while a third type is inside.

Problem

A row of trees is given as fruits, where fruits[i] is the type of fruit on tree i. You have two baskets, each holding any amount of a single type. Starting at any tree, you pick one fruit from every tree moving right, and stop at the first tree whose fruit fits in neither basket. Return the most fruit you can pick.

Constraints

Edge cases to test

Follow-up questions

What if you have k baskets?
The same window with at most k distinct values in a count map: O(n) time, O(k) space (LC 340).
Can the map be avoided for k = 2?
Track the last two types and how long the latest one has run: O(1) space.

Solution

Java

public int totalFruit(int[] fruits) {
    Map<Integer, Integer> basket = new HashMap<>();
    int left = 0, best = 0;
    for (int right = 0; right < fruits.length; right++) {
        basket.merge(fruits[right], 1, Integer::sum);
        while (basket.size() > 2) {
            int out = fruits[left++];
            basket.merge(out, -1, Integer::sum);
            if (basket.get(out) == 0) {
                basket.remove(out);
            }
        }
        best = Math.max(best, right - left + 1);
    }
    return best;
}

Python

def total_fruit(fruits):
    basket = {}
    left = best = 0
    for right in range(len(fruits)):
        basket[fruits[right]] = basket.get(fruits[right], 0) + 1
        while len(basket) > 2:
            out = fruits[left]
            left += 1
            basket[out] -= 1
            if basket[out] == 0:
                del basket[out]
        best = max(best, right - left + 1)
    return best

C++

#include <bits/stdc++.h>
using namespace std;

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

More Sliding Window problems