Taro Logo

Fruit Into Baskets

#115 Most AskedMedium
Topics:
ArraysSliding Windows

You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces.

You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:

  • You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold.
  • Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.
  • Once you reach a tree with fruit that cannot fit in your baskets, you must stop.

Given the integer array fruits, return the maximum number of fruits you can pick.

Example 1:

Input: fruits = [1,2,1]
Output: 3
Explanation: We can pick from all 3 trees.

Example 2:

Input: fruits = [0,1,2,2]
Output: 3
Explanation: We can pick from trees [1,2,2].
If we had started at the first tree, we would only pick from trees [0,1].

Example 3:

Input: fruits = [1,2,3,2,2]
Output: 4
Explanation: We can pick from trees [2,3,2,2].
If we had started at the first tree, we would only pick from trees [1,2].

Constraints:

  • 1 <= fruits.length <= 105
  • 0 <= fruits[i] < fruits.length

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should we return if the input array of fruit trees is empty?
  2. Are the fruit types represented exclusively by characters, or could they also be integers or strings of varying lengths?
  3. Does 'moving continuously to the right' mean we must start at the very beginning of the array, or can we choose any starting tree to maximize our collection?
  4. If the array contains fewer than two unique types of fruit, should we simply return the total length of the array?
  5. Are the two baskets strictly constrained to holding at most two distinct types of fruit in total throughout the entire contiguous subarray, or can the types change dynamically as we move?

Brute Force Solution

Approach

Imagine you are walking down a straight line of fruit trees and can only collect fruits using at most two distinct types of baskets. The brute force approach checks every possible starting tree and every possible ending tree to see how many total fruits you can gather without breaking the two-type limit.

Here's how the algorithm would work step-by-step:

  1. Start by standing at the very first tree in the line.
  2. Look ahead and pick a second tree further down the line to be your stopping point.
  3. Consider the stretch of trees from your starting point to your stopping point as your current collection.
  4. Count all the fruits in this chosen stretch, making sure there are no more than two different types of fruit represented.
  5. If there are more than two types of fruit, this stretch is invalid, so abandon it.
  6. If it is valid, count how many total fruits are in this stretch and remember that number.
  7. Now, pick a new starting point and repeat the process of checking every possible stopping point ahead of it.
  8. Keep track of the largest count of valid fruits you found across every single possible stretch you tested.
  9. Once you have tested every possible starting and stopping combination, the largest count you remembered is your final answer.

Code Implementation

def total_fruit(tree_list):
    max_fruits_collected = 0
    
    # Test every possible starting tree to explore all contiguous subarrays from this point
    for start_position in range(len(tree_list)):
        
        for end_position in range(start_position, len(tree_list)):
            unique_fruit_types = set()
            
            # Scan the current stretch of trees and collect the unique types present
            for current_position in range(start_position, end_position + 1):
                unique_fruit_types.add(tree_list[current_position])
                
            # Verify if the stretch respects the basket limit of at most two fruit types
            if len(unique_fruit_types) <= 2:
                current_fruit_count = (end_position - start_position) + 1
                
                if current_fruit_count > max_fruits_collected:
                    max_fruits_collected = current_fruit_count
                    
    # Return the maximum valid fruit count found across all tested tree stretches
    return max_fruits_collected

Big(O) Analysis

Time Complexity
O(n²) – For each of the n fruit trees acting as a starting point, the brute force approach tests every possible stopping point further down the line. As the outer loop advances through each tree, the inner loop examines varying lengths of subsequent trees while checking for the two-basket limit. This combinatorial checking across all starting and stopping combinations leads to approximately n * n/2 total operations. Simplifying this polynomial yields a final runtime complexity of O(n²).
Space Complexity
O(1) – The brute force approach described relies solely on a few primitive integer variables to track the current starting point, stopping point, fruit types, and running totals. No auxiliary data structures like hash maps or temporary lists scaling with the input size N are created. Because the memory consumption remains constant regardless of how many fruit trees are in the line, the space complexity simplifies to O(1).

Optimal Solution

Approach

Instead of checking every single starting point, we can use a moving window to keep track of the fruit types we collect along our path. Whenever we stumble upon a third type of fruit, we slide our collection area forward until we are back down to just two types, always keeping track of the longest stretch we managed to cover.

Here's how the algorithm would work step-by-step:

  1. Imagine walking down a long row of fruit trees where each tree has a label telling you what kind of fruit it bears.
  2. You carry two empty baskets, and each basket can hold an unlimited amount of only one specific type of fruit.
  3. Begin walking forward and pick the fruit from each tree you pass, dropping it into the correct basket based on its type.
  4. Keep track of how many trees you have visited so far in this current continuous stretch.
  5. If you encounter a tree with a fruit type that does not match either of the two types already in your baskets, you have a problem because you only have two baskets.
  6. To fix this, step backward mentally and drop fruits from the very beginning of your journey until your oldest fruit type is completely cleared out and one basket becomes free.
  7. Now assign that newly emptied basket to the fresh fruit type you just found.
  8. As you continue walking down the line, constantly measure the length of your current stretch and remember the highest number you reach.
  9. When you finally reach the end of the line of trees, the highest number you saved will be the maximum amount of fruit you could possibly collect.

Code Implementation

def total_fruit(tree_fruit_types):
    fruit_frequency_map = {}
    window_start_index = 0
    maximum_fruits_collected = 0

    for window_end_index, current_fruit_type in enumerate(tree_fruit_types):
        fruit_frequency_map[current_fruit_type] = fruit_frequency_map.get(current_fruit_type, 0) + 1

        # Shrink the window from the left if we exceed two distinct fruit types.
        while len(fruit_frequency_map) > 2:
            left_fruit_type = tree_fruit_types[window_start_index]
            fruit_frequency_map[left_fruit_type] -= 1
            if fruit_frequency_map[left_fruit_type] == 0:
                del fruit_frequency_map[left_fruit_type]
            window_start_index += 1

        # Track the maximum length of valid trees visited with at most two fruit types.
        current_stretch_length = window_end_index - window_start_index + 1
        if current_stretch_length > maximum_fruits_collected:
            maximum_fruits_collected = current_stretch_length

    return maximum_fruits_collected

Big(O) Analysis

Time Complexity
O(n) – As we walk down the row of n fruit trees represented by the array, the right pointer iterates through each tree exactly once. The left pointer also moves forward monotonically, never retreating as we shrink the window to remove the extra fruit type. Each tree is thus added to our tracking structure and removed at most once. This results in roughly 2n total operations across the entire traversal, which simplifies to a linear time complexity of O(n).
Space Complexity
O(1) – To track the types of fruit in our two baskets during the sliding window process, we use a hash map or frequency array. Because the problem strictly limits us to at most two distinct fruit types at any given time, this data structure will never hold more than three key-value pairs regardless of how long the row of trees is. Therefore, the extra memory required remains constant as the input size N grows, leading to an optimal auxiliary space complexity of O(1).

Edge Cases

Empty or null fruit array
How to Handle:
Return zero immediately as no fruits can be collected from an empty orchard
Array with length one or two
How to Handle:
Return the exact length of the array since all elements fit within the two available baskets
Orchard with all trees producing the exact same fruit type
How to Handle:
The sliding window expands to encompass the entire array and returns the total length
Orchard with alternating fruit types
How to Handle:
The window will incorporate all elements seamlessly because the distinct fruit count never exceeds two
Massive input array scaling up to maximum constraints
How to Handle:
An optimized sliding window with a hash map achieves linear time complexity to prevent time limit exceeded errors
Fruit types represented by extreme integer values or characters
How to Handle:
Using a hash map or frequency array allows handling arbitrary fruit identifiers without relying on contiguous indexing
Frequently changing fruit types requiring constant basket eviction
How to Handle:
The left pointer of the sliding window shrinks efficiently until the distinct fruit count drops back to two
Long sequence of unique fruits preventing large windows
How to Handle:
The algorithm correctly resets and tracks the maximum length found across multiple valid subsegments
0/245 completed