Fruits Into Baskets III - Problem

You are given two arrays of integers, fruits and baskets, each of length n, where fruits[i] represents the quantity of the i-th type of fruit, and baskets[j] represents the capacity of the j-th 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.

Input & Output

Example 1 — Basic Case
$ Input: fruits = [4,2,1], baskets = [5,1,3]
Output: 0
💡 Note: Fruit 4 goes to basket 5 (index 0), fruit 2 goes to basket 3 (index 2), fruit 1 goes to basket 1 (index 1). All fruits are placed.
Example 2 — Some Unplaced
$ Input: fruits = [3,3,3], baskets = [3,1,1]
Output: 2
💡 Note: First fruit 3 goes to basket 3 (index 0). Second and third fruits cannot be placed as remaining baskets have capacity 1 < 3.
Example 3 — All Unplaced
$ Input: fruits = [5,5], baskets = [1,2]
Output: 2
💡 Note: No basket has sufficient capacity (5) for any fruit, so both remain unplaced.

Constraints

  • 1 ≤ n ≤ 105
  • 1 ≤ fruits[i], baskets[i] ≤ 109

Visualization

Tap to expand
Fruits Into Baskets III INPUT fruits[] array 4 i=0 2 i=1 1 i=2 baskets[] array cap 5 j=0 cap 1 j=1 cap 3 j=2 Input Values: fruits = [4, 2, 1] baskets = [5, 1, 3] n = 3 ALGORITHM STEPS 1 Process fruit[0]=4 Find leftmost basket with cap >= 4 basket[0]=5 OK 2 Process fruit[1]=2 Skip basket[0] (used) basket[1]=1 < 2, skip basket[2]=3 OK 3 Process fruit[2]=1 Skip basket[0,2] (used) basket[1]=1 >= 1 basket[1]=1 OK 4 Count Unplaced All fruits placed! unplaced = 0 Final Allocation: B[0]=5 --> F[0]=4 B[2]=3 --> F[1]=2, B[1]=1 --> F[2]=1 FINAL RESULT Baskets After Placement 4 B[0]=5 1 B[1]=1 2 B[2]=3 OUTPUT 0 Result Confirmed All 3 fruit types successfully placed Unplaced count = 0 Key Insight: The greedy left-to-right approach ensures optimal placement. For each fruit, scan baskets from left to right to find the first available basket with sufficient capacity. Using a Segment Tree or similar data structure enables O(n log n) time complexity for finding the leftmost valid basket. TutorialsPoint - Fruits Into Baskets III | Optimal Solution
Asked in
Google 45 Amazon 38 Microsoft 32
23.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen