Rearranging Fruits - Problem
Fruit Basket Equalizer - The Great Swap Challenge!

Imagine you're a fruit vendor with two baskets, each containing n fruits of different costs. Your goal is to make both baskets identical by swapping fruits between them.

You're given two arrays basket1 and basket2 representing the cost of each fruit. You can perform swaps where:
• Choose any fruit from basket1 and any fruit from basket2
• Swap them with a cost equal to min(cost1, cost2)
• Two baskets are equal when sorted arrays are identical

Return the minimum total cost to equalize the baskets, or -1 if impossible.

Example: basket1=[4,2,2,2], basket2=[1,4,1,2] → After optimal swaps, both become [1,2,2,4] with minimum cost.

Input & Output

example_1.py — Basic Case
$ Input: basket1 = [4,2,2,2], basket2 = [1,4,1,2]
Output: 2
💡 Note: We need to swap fruits to make both baskets [1,2,2,4]. Swap basket1[0]=4 with basket2[0]=1 (cost=1), then swap basket1[1]=2 with basket2[2]=1 (cost=1). Total cost = 2.
example_2.py — Impossible Case
$ Input: basket1 = [4,79,32], basket2 = [91,2,105]
Output: -1
💡 Note: Each fruit appears exactly once across both baskets, so each has an odd frequency. Since we can't split odd numbers evenly, it's impossible to make the baskets equal.
example_3.py — Already Equal
$ Input: basket1 = [1,2,3], basket2 = [1,2,3]
Output: 0
💡 Note: The baskets are already equal when sorted, so no swaps are needed. Total cost = 0.

Constraints

  • 1 ≤ basket1.length == basket2.length ≤ 105
  • 1 ≤ basket1[i], basket2[i] ≤ 109
  • Both baskets have equal number of fruits

Visualization

Tap to expand
🍎 Fruit Market Trading StrategyVendor 1 Inventory$4$2$2$2Excess: $4 apple, $2 orangeVendor 2 Inventory$1$4$1$2Need: $1 banana, $1 banana🤝 Optimal Trading$4$1Trade Cost: min($4, $1) = $1🎯 Final ResultBoth vendors end with: [$1, $2, $2, $4]Total Trading Cost: $2
Understanding the Visualization
1
Inventory Check
Count all fruit types across both vendors - if any fruit type has odd total quantity, balancing is impossible
2
Identify Imbalances
Find which fruits each vendor has too many of and needs to trade away
3
Strategic Sorting
Sort excess inventory: expensive fruits first for vendor 1, cheap fruits first for vendor 2
4
Optimal Trading
Execute greedy trades: pair most expensive excess with cheapest needed, or use indirect trades through cheapest fruit
Key Takeaway
🎯 Key Insight: The greedy approach works because we always want to minimize the cost of each trade. By pairing the most expensive excess items with the cheapest available options, we ensure the lowest total trading cost while achieving perfect balance.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 22
38.5K Views
Medium-High Frequency
~25 min Avg. Time
1.3K 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