#3477

Fruits Into Baskets II

Easy
ArrayBinary SearchSegment TreeSimulationOrdered SetTwo PointersSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal solution sorts both arrays first, allowing us to efficiently match fruits to baskets using a two-pointer technique. This reduces unnecessary checks and speeds up the placement process.

⚙️

Algorithm

5 steps
  1. 1Step 1: Sort both the fruits and baskets arrays.
  2. 2Step 2: Initialize two pointers, one for fruits and one for baskets.
  3. 3Step 3: Iterate through the fruits, and for each fruit, move the basket pointer until a suitable basket is found or all baskets are checked.
  4. 4Step 4: If a suitable basket is found, mark it as used and move to the next fruit. If not, increment the unplaced counter.
  5. 5Step 5: Return the count of unplaced fruits.
solution.py19 lines
1# Full working Python code
2fruits = [4, 2, 5]
3baskets = [3, 5, 4]
4
5fruits.sort()
6baskets.sort()
7
8unplaced = 0
9j = 0
10
11for fruit in fruits:
12    while j < len(baskets) and baskets[j] < fruit:
13        j += 1
14    if j < len(baskets):
15        j += 1  # Use this basket
16    else:
17        unplaced += 1
18
19print(unplaced)

Complexity note: The time complexity is O(n log n) due to sorting both arrays. The subsequent placement of fruits is O(n), making the overall complexity dominated by the sorting step. The space complexity is O(1) since we only use a few extra variables.

  • 1Sorting allows for efficient matching of fruits to baskets.
  • 2Using two pointers minimizes unnecessary checks and speeds up the process.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.