Fruits Into Baskets II - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: fruits = [3,1,2], baskets = [2,3,1]
Output: 0
💡 Note: Fruit 3 goes to basket 3 (capacity 3), fruit 1 goes to basket 1 (capacity 2), fruit 2 goes to basket 2 (capacity 3). All fruits placed successfully.
Example 2 — Some Unplaced
$ Input: fruits = [4,2,1], baskets = [1,2,3]
Output: 1
💡 Note: Fruit 4 cannot fit in any basket (max capacity is 3), fruit 2 goes to basket 2 (capacity 2), fruit 1 goes to basket 1 (capacity 1). One fruit remains unplaced.
Example 3 — All Unplaced
$ Input: fruits = [5,6,7], baskets = [1,2,3]
Output: 3
💡 Note: All fruits are too large for any basket. All 3 fruits remain unplaced.

Constraints

  • 1 ≤ fruits.length, baskets.length ≤ 103
  • 1 ≤ fruits[i], baskets[i] ≤ 109

Visualization

Tap to expand
Fruits Into Baskets II: Leftmost Placement StrategyInputFruits:312Baskets:231ProcessingFor each fruit:1. Scan left to right2. Find suitable basket3. Mark as usedResultUnplaced Count0Fruit 3 → Basket 2 (capacity 3)Fruit 1 → Basket 1 (capacity 2)Fruit 2 → Basket 3 (capacity 1) ❌ → Basket 2 already used → Basket 3 too smallActually: Fruit 2 → Basket 2 has capacity 3 but used → No placement
Understanding the Visualization
1
Input
Arrays of fruit quantities and basket capacities
2
Process
Place each fruit in leftmost suitable basket
3
Output
Count of unplaceable fruits
Key Takeaway
🎯 Key Insight: Always process fruits in order and select the leftmost available basket with sufficient capacity
Asked in
Google 25 Amazon 20 Microsoft 15
12.0K Views
Medium Frequency
~15 min Avg. Time
580 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