Skip to main content

Fruits Into Baskets II - Solution & Explanation

EasyArrayBinary SearchSegment TreeSimulation8 min readAsked at: Amazon, Microsoft, Meta +2
Practice this problem

Problem Statement

You are given two arrays of integers, fruits and baskets, each of length n, where fruits[i] represents the quantity of the ith type of fruit, and baskets[j] represents the capacity of the jth basket.

From left to right, place the fruits according to these rules:

  • Each fruit type must be placed in the leftmost available basket with a capacity greater than or equal to the quantity of that fruit type.
  • Each basket can hold only one type of fruit.
  • If a fruit type cannot be placed in any basket, it remains unplaced.

Return the number of fruit types that remain unplaced after all possible allocations are made.

 

Example 1:

Input: fruits = [4,2,5], baskets = [3,5,4]

Output: 1

Explanation:

  • fruits[0] = 4 is placed in baskets[1] = 5.
  • fruits[1] = 2 is placed in baskets[0] = 3.
  • fruits[2] = 5 cannot be placed in baskets[2] = 4.

Since one fruit type remains unplaced, we return 1.

Example 2:

Input: fruits = [3,6,1], baskets = [6,4,7]

Output: 0

Explanation:

  • fruits[0] = 3 is placed in baskets[0] = 6.
  • fruits[1] = 6 cannot be placed in baskets[1] = 4 (insufficient capacity) but can be placed in the next available basket, baskets[2] = 7.
  • fruits[2] = 1 is placed in baskets[1] = 4.

Since all fruits are successfully placed, we return 0.

 

Constraints:

  • n == fruits.length == baskets.length
  • 1 <= n <= 100
  • 1 <= fruits[i], baskets[i] <= 1000

Approach Overview

Problem Overview: You are given two arrays: fruits and baskets. Each fruit must be placed in the leftmost basket that has capacity greater than or equal to the fruit size. Every basket can hold only one fruit. If no valid basket exists, the fruit remains unplaced. The task is to count how many fruits cannot be placed.

Approach 1: Brute Force Simulation (O(n * m) time, O(1) space)

The most direct strategy is to simulate the placement process exactly as described. Iterate through each fruit and scan the baskets from left to right. The first unused basket whose capacity is >= fruit gets assigned to that fruit, and the basket is marked as used. If the scan reaches the end without finding a valid basket, increment the unplaced fruit count. This approach works well for small input sizes and mirrors the problem statement closely. Since you simply iterate over arrays and track used baskets, the extra space stays constant.

Approach 2: Ordered Set / Balanced Structure (O(n log m) time, O(m) space)

Instead of scanning all baskets every time, maintain a structure that tracks available baskets. One option is an ordered structure that stores basket indices along with their capacities. For each fruit, you search for the earliest basket whose capacity satisfies the requirement and remove it from the set once used. This avoids repeatedly checking baskets that are already filled. The main benefit appears when the basket count grows large, because each lookup becomes logarithmic instead of linear. Problems involving placement with constraints like this often benefit from ordered containers.

Approach 3: Segment Tree for First Valid Basket (O(n log m) time, O(m) space)

A more algorithmic solution uses a segment tree built over the baskets array. Each node stores the maximum capacity in its range. For every fruit, query the tree to find the leftmost index where the stored maximum is at least the fruit size. Once found, update that position to zero (or negative infinity) to mark the basket as used. The segment tree allows you to skip entire ranges that cannot fit the fruit, making the search efficient. This technique is common in allocation problems where you must find the first position satisfying a constraint.

Conceptually, this problem combines simple array traversal with efficient searching techniques such as binary search structures or trees. The key insight is that the basket must be both unused and the leftmost valid position.

Recommended for interviews: Start with the simulation approach because it demonstrates clear understanding of the rules and edge cases. If the interviewer pushes for scalability, transition to the segment tree or ordered-set approach that reduces repeated scanning. Showing both the straightforward simulation and the optimized search structure signals strong problem‑solving depth.

Solution

We use a boolean array vis of length n to record the baskets that have already been used, and a variable ans to record the number of fruits that have not been placed, initially ans = n.

Next, we traverse each fruit x. For the current fruit, we traverse all the baskets to find the first unused basket i with a capacity greater than or equal to x. If found, we decrement ans by 1.

After traversing, we return the answer.

The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the array fruits.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force SimulationO(n * m)O(1)Best when constraints are small and the goal is clarity and quick implementation
Ordered Set / Balanced TreeO(n log m)O(m)Useful when many baskets exist and repeated scanning becomes expensive
Segment Tree SearchO(n log m)O(m)Preferred for large inputs when you must find the leftmost basket meeting a capacity constraint

Video Solution

3477 & 3479. Fruits Into Baskets III & II | Segment Tree • Aryan Mittal • 7,134 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Fruits Into Baskets II easy or hard?
Fruits Into Baskets II is classified as an Easy problem with an acceptance rate around 70%. The base solution relies on straightforward simulation, but the problem can also introduce advanced data structures like segment trees when discussing optimized approaches.
Fruits Into Baskets II Python/Java solution
A Python or Java solution typically simulates the process: iterate through fruits, scan baskets from left to right, and mark the first basket with sufficient capacity as used. The same logic translates directly across Python, Java, C++, Go, and TypeScript implementations.
How to solve Fruits Into Baskets II in O(n log m)?
Build a segment tree over the baskets array where each node stores the maximum basket capacity in its range. For each fruit, query the tree to find the leftmost basket with capacity >= fruit size. After placing the fruit, update that basket's value to mark it as used. Each query and update takes O(log m).
What is the best approach for Fruits Into Baskets II?
The most practical approach is direct simulation: iterate through each fruit and place it into the first unused basket with enough capacity. This runs in O(n*m) time and O(1) space and is sufficient for typical constraints. For larger inputs, a segment tree or ordered set can reduce the search cost to O(log m) per fruit.
Is Fruits Into Baskets II asked at Google/Amazon/Meta?
Problems involving allocation, greedy placement, and segment trees appear frequently in interviews at companies like Google, Amazon, and Meta. While this exact problem may come from coding platforms, the underlying pattern of finding the first valid position using efficient data structures is a common interview theme.
What data structure is used in Fruits Into Baskets II?
The simplest solution uses arrays and simulation. Optimized approaches often rely on segment trees, ordered sets, or balanced binary search trees to efficiently locate the leftmost basket that satisfies the capacity requirement.
What is the time complexity of Fruits Into Baskets II?
The straightforward simulation runs in O(n * m) time because each fruit may scan all baskets to find the first valid placement. Optimized solutions using a segment tree or balanced ordered set reduce this to O(n log m) by quickly locating the leftmost basket with enough capacity.

Ready to solve this problem?

Practice Fruits Into Baskets II with our built-in code editor and test cases.

Practice on FleetCode