#3479

Fruits Into Baskets III

Medium
ArrayBinary SearchSegment TreeOrdered SetBinary SearchGreedy
LeetCode ↗

Approaches

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

Intuition

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

Sort the baskets and use binary search to efficiently find the first suitable basket for each fruit.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the baskets in ascending order.
  2. 2Step 2: For each fruit, use binary search to find the first basket that can hold it.
  3. 3Step 3: Mark the basket as used and continue to the next fruit.
solution.py13 lines
1def unplaced_fruits(fruits, baskets):
2    baskets.sort()
3    used = [False] * len(baskets)
4    unplaced = 0
5    for fruit in fruits:
6        idx = bisect.bisect_left(baskets, fruit)
7        while idx < len(baskets) and used[idx]:
8            idx += 1
9        if idx < len(baskets):
10            used[idx] = True
11        else:
12            unplaced += 1
13    return unplaced

Complexity note: Sorting takes O(n log n) and each fruit uses binary search in O(log n).

  • 1Sorting helps in efficient allocation.
  • 2Binary search reduces search time for baskets.

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