The Fruits Into Baskets II interview question involves assigning baskets of fruit to a series of children. You have an array fruits representing the quantity of fruit in each basket, and an array baskets representing the capacity of each child's basket. You iterate through the fruits array in order. For each fruit basket, you must give it to the first child (lowest index) whose basket has enough capacity to hold it. Once a child's basket is used, it cannot be used again. If no child has enough capacity, the fruit is discarded. You need to return the number of unplaced fruit baskets.
Companies like Microsoft and Amazon ask the Fruits Into Baskets II coding problem to test a candidate's ability to optimize a linear search. A naive approach would be to iterate through all children for every fruit, resulting in time complexity. It evaluates whether you can use advanced data structures like a Segment Tree to find the "first valid element" in time, demonstrating a deep understanding of range queries.
The optimal approach is a Segment Tree.
baskets array, where each node stores the maximum capacity in its range.q in fruits:
q, the fruit cannot be placed.fruits = [4, 2, 5], baskets = [3, 5, 4]
[3, 0, 4].[0, 0, 4].Practice the "find first element " query on a Segment Tree. This is a common variation where you use the max value of the left child to decide whether to search left or right.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Fruits Into Baskets III | Medium | Solve | |
| My Calendar I | Medium | Solve | |
| Minimum Absolute Difference Between Elements With Constraint | Medium | Solve | |
| My Calendar II | Medium | Solve | |
| Falling Squares | Hard | Solve |