Medium dsa sliding-window

Fruit Into Baskets

The 30 second answer

The problem is the longest subarray that contains at most two distinct values. I grow a window and count the fruits inside it. While more than two types are in the window I drop from the left, and I keep the longest valid length. One pass, and the map holds at most three keys.

Could you say this in an interview?

Problem You walk along a row of trees, each bearing one type of fruit, and you have two baskets that can each hold only one type. Starting at any tree, you must pick every tree from then on, and you stop when you would need a third type. Return the maximum number of fruits you can collect. Original: LeetCode 904: Fruit Into Baskets.

Understanding the prompt The story hides a clean constraint: longest contiguous subarray with at most two distinct numbers. You cannot skip a tree in the middle of the window.

Pattern recognition A variable-size window with an 'at most k distinct' condition, here k = 2.

Brute force For every start index, extend right until a third type appears: O(n²).

Optimal A HashMap of value to count. Add fruits[hi], then while the map has more than two keys, decrement fruits[lo] and remove it when its count hits zero, advancing lo. The window length hi − lo + 1 is a candidate after each step.

Alternatives The same structure with k as a parameter is the general 'at most k distinct' window, which also underlies Subarrays with K Distinct Integers.

Java solution

import java.util.HashMap;

public class FruitIntoBaskets {
    static int totalFruit(int[] fruits) {
        var count = new HashMap<Integer, Integer>();
        int lo = 0, best = 0;
        for (int hi = 0; hi < fruits.length; hi++) {
            count.merge(fruits[hi], 1, Integer::sum);
            while (count.size() > 2) {
                int x = fruits[lo++];
                if (count.merge(x, -1, Integer::sum) == 0) count.remove(x);
            }
            best = Math.max(best, hi - lo + 1);
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(totalFruit(new int[] {1, 2, 1}));       // 3
        System.out.println(totalFruit(new int[] {0, 1, 2, 2}));    // 3
        System.out.println(totalFruit(new int[] {1, 2, 3, 2, 2})); // 4
    }
}

Complexity O(n) time, O(1) extra space because the map holds at most three keys.

Edge cases

  • Only one or two types in the whole array, as in [1,2,1], returns the full length 3.
  • A third type that forces a shrink, as in [0,1,2,2], whose best window is [1,2,2] of length 3.
  • [1,2,3,2,2] returns 4, the suffix [2,3,2,2].

Follow-ups

  • At most k distinct characters in a string is the same window.
  • Exactly k distinct is atMost(k) minus atMost(k − 1).

Tests [1,2,1] returns 3. [0,1,2,2] returns 3. [1,2,3,2,2] returns 4.

How to say it in the interview "Under the story this is the longest subarray with at most two distinct values. I grow a window, count the types, and shrink from the left whenever a third type appears. The longest valid window is the number of fruits I can pick."

Sources (2)
  1. LeetCode 904: Fruit Into Basketsleetcode.com
  2. Java SE 17 API: Map.mergedocs.oracle.com