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: Leftmost-Fit AllocationFruits: [4, 2, 1]421Baskets: [5, 1, 3]513Allocation: 4→5 (leftmost fit), 2→3 (skip used basket), 1→1 (last available)Result: 0 unplaced fruits
Understanding the Visualization
1
Input
Arrays of fruit quantities and basket capacities
2
Process
Match each fruit to leftmost suitable basket
3
Output
Count of unplaced fruits
Key Takeaway
🎯 Key Insight: Always choose the leftmost available basket that can accommodate each fruit
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