↓Skip to main content
  1. LeetCode/

LeetCode 2561: Rearranging Fruits

·2 mins· ·
LeetCode Hard Greedy Hash-Table Sorting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: hard First Attempt: 2026-09-15

  • Submissions: Wrong Answer → Accepted ×2

Approach
#

  1. Feasibility: the baskets must end up equal, so every value’s total count must be even, half in each. Any odd count means -1.
  2. What to swap: each value is over or under in basket 1 by |count1 - total / 2|. List the excess from both sides (need); its length is 2 × swaps, and each swap exchanges one excess item from each side.
  3. Cheapest pairing: a swap costs the smaller of the two values. Sort need and pair each item in the cheap half with an expensive one, paying the cheap value.
  4. Use the minimum as a go-between: the globally cheapest fruit m can be swapped back and forth twice to exchange a pair for 2m. So each swap costs min(need[i], 2m).

This is the pairing idea from Greedy Template 4.

My Attempts
#

Attempt 1 tried pairing from both ends with two deques, but the while that cancels the common part used v from for k, v in ...items(). v never changes inside the loop, so the counts kept dropping until the other side reached zero and went negative. For basket1 = [3, 3, 1], basket2 = [1, 1, 1] the answer is 1 (swap a 3 for a 1); this version drove the count of 1 to -2 and returned 0. It also ignored the go-between trick.

Switching to the approach above passed.

Solution
#

class Solution:
    def minCost(self, basket1: List[int], basket2: List[int]) -> int:
        c1, total = Counter(basket1), Counter(basket1) + Counter(basket2)
        need = []
        for v, c in total.items():
            if c % 2:
                return -1
            need += [v] * abs(c // 2 - c1[v])
        need.sort()
        m = min(total)
        return sum(min(x, 2 * m) for x in need[:len(need) // 2])

Complexity
#

Time O(n log n), space O(n).

Mistakes to Avoid
#

  • Do not put a value read before the loop, and never updated, in the loop condition.
  • Remember the global minimum as a go-between; it can be cheaper than a direct swap.

Interview Explanation
#

It is only possible if every value’s total is even. I list each basket’s excess fruits and sort them; each item in the cheap half swaps with an expensive one for its own value, or through the global minimum for twice that minimum, whichever is less. Time O(n log n).

Related

LeetCode 2141: Maximum Running Time of N Computers
·3 mins
LeetCode Hard Greedy Binary-Search Sorting
LeetCode 2141 note: a battery longer than the average can only serve one computer, so remove it with that computer and average the rest, using strict greater-than
LeetCode 3684: Maximize Sum of At Most K Distinct Elements
·1 min
LeetCode Easy Greedy Sorting Hash-Table
LeetCode 3684 note: all values are positive, so deduplicate and take the k largest in descending order
LeetCode 2122: Recover the Original Array
·3 mins
LeetCode Hard Two-Pointers Sorting Hash-Table Enumeration Array
LeetCode 2122 note: the smallest number is always in lower, so enumerating its partner fixes k; after sorting, two pointers pair each smallest unmatched number with the number 2k above it
LeetCode 1782: Count Pairs Of Nodes
·3 mins
LeetCode Hard Two-Pointers Graph Sorting Hash-Table Counting
LeetCode 1782 note: count pairs with deg[a] + deg[b] > q using sorted degrees and converging pointers, then correct the over-count for pairs that share edges
LeetCode 2357: Make Array Zero by Subtracting Equal Amounts
·1 min
LeetCode Easy Array Hash-Table Greedy Sorting
LeetCode 2357 note: each operation zeroes the group of the smallest positive value, so the answer is the number of distinct positive values
LeetCode 1402: Reducing Dishes
·2 mins
LeetCode Hard Dynamic-Programming Greedy Sorting Array
LeetCode 1402 note: sort and take dishes from most satisfying down; each new dish goes first and shifts the chosen ones one slot later, adding the current chosen sum, so keep going while that sum is positive