KatInterview

940. Fruit Into Baskets

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the maximum number of fruits we can pick from a row of trees, following a specific set of rules. We have two baskets, each can hold only one type of fruit. We must pick one fruit from every tree consecutively, starting from any tree and moving right. We stop when we encounter a fruit type that doesn't fit in our two baskets.

Solution

Fruit Into Baskets in Python

class Solution:
    def totalFruit(self, fruits: List[int]) -> int:
        # Use a dictionary (hash map) to store the count of fruit types in the current window.
        basket = defaultdict(int)
        left = 0  # Left pointer of the sliding window.
        maxLength = 0  # Stores the maximum number of fruits collected.

        # Iterate through the fruits with the right pointer of the window.
        for right, fruit in enumerate(fruits):
            # Add the current fruit to the basket.
            basket[fruit] += 1

            # If the basket contains more than 2 types of fruit,
            # shrink the window from the left.
            while len(basket) > 2:
                # Get the fruit at the left pointer.
                left_fruit = fruits[left]
                # Decrement its count in the basket.
                basket[left_fruit] -= 1
                # If the count becomes zero, remove the fruit type from the basket.
                if basket[left_fruit] == 0:
                    del basket[left_fruit]
                # Move the left pointer to the right.
                left += 1

            # Update the maximum length with the size of the current valid window.
            maxLength = max(maxLength, right - left + 1)

        return maxLength

Fruit Into Baskets in Java

class Solution {
    public int totalFruit(int[] fruits) {
        // Use a HashMap to store the count of fruit types in the current window.
        Map<Integer, Integer> basket = new HashMap<>();
        int left = 0; // Left pointer of the sliding window.
        int maxLength = 0; // Stores the maximum number of fruits collected.

        // Iterate through the fruits with the right pointer of the window.
        for (int right = 0; right < fruits.length; right++) {
            // Add the current fruit to the basket.
            int rightFruit = fruits[right];
            basket.put(rightFruit, basket.getOrDefault(rightFruit, 0) + 1);

            // If the basket contains more than 2 types of fruit,
            // shrink the window from the left.
            while (basket.size() > 2) {
                // Get the fruit at the left pointer.
                int leftFruit = fruits[left];
                // Decrement its count in the basket.
                basket.put(leftFruit, basket.get(leftFruit) - 1);
                // If the count becomes zero, remove the fruit type from the basket.
                if (basket.get(leftFruit) == 0) {
                    basket.remove(leftFruit);
                }
                // Move the left pointer to the right.
                left++;
            }

            // Update the maximum length with the size of the current valid window.
            maxLength = Math.max(maxLength, right - left + 1);
        }

        return maxLength;
    }
}

Fruit Into Baskets in C++

class Solution {
public:
    int totalFruit(vector<int>& fruits) {
        // Use a hash map to store the count of fruit types in the current window.
        std::unordered_map<int, int> basket;
        int left = 0; // Left pointer of the sliding window.
        int maxLength = 0; // Stores the maximum number of fruits collected.

        // Iterate through the fruits with the right pointer of the window.
        for (int right = 0; right < fruits.size(); ++right) {
            // Add the current fruit to the basket.
            basket[fruits[right]]++;

            // If the basket contains more than 2 types of fruit,
            // shrink the window from the left.
            while (basket.size() > 2) {
                // Get the fruit at the left pointer.
                int leftFruit = fruits[left];
                // Decrement its count in the basket.
                basket[leftFruit]--;
                // If the count becomes zero, remove the fruit type from the basket.
                if (basket[leftFruit] == 0) {
                    basket.erase(leftFruit);
                }
                // Move the left pointer to the right.
                left++;
            }

            // Update the maximum length with the size of the current valid window.
            maxLength = std::max(maxLength, right - left + 1);
        }

        return maxLength;
    }
};

Fruit Into Baskets in TypeScript

function totalFruit(fruits: number[]): number {
    // Use a Map to store the count of fruit types in the current window.
    const basket = new Map<number, number>();
    let left = 0; // Left pointer of the sliding window.
    let maxLength = 0; // Stores the maximum number of fruits collected.

    // Iterate through the fruits with the right pointer of the window.
    for (let right = 0; right < fruits.length; right++) {
        const rightFruit = fruits[right];
        // Add the current fruit to the basket.
        basket.set(rightFruit, (basket.get(rightFruit) || 0) + 1);

        // If the basket contains more than 2 types of fruit,
        // shrink the window from the left.
        while (basket.size > 2) {
            const leftFruit = fruits[left];
            // Decrement its count in the basket.
            // The '!' non-null assertion is safe as we know leftFruit is in the basket.
            basket.set(leftFruit, basket.get(leftFruit)! - 1);
            // If the count becomes zero, remove the fruit type from the basket.
            if (basket.get(leftFruit) === 0) {
                basket.delete(leftFruit);
            }
            // Move the left pointer to the right.
            left++;
        }

        // Update the maximum length with the size of the current valid window.
        maxLength = Math.max(maxLength, right - left + 1);
    }

    return maxLength;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.