Rearranging Fruits - Problem

You have two fruit baskets containing n fruits each. You are given two 0-indexed integer arrays basket1 and basket2 representing the cost of fruit in each basket.

You want to make both baskets equal. To do so, you can use the following operation as many times as you want:

  • Choose two indices i and j, and swap the ith fruit of basket1 with the jth fruit of basket2.
  • The cost of the swap is min(basket1[i], basket2[j]).

Two baskets are considered equal if sorting them according to the fruit cost makes them exactly the same baskets.

Return the minimum cost to make both the baskets equal or -1 if impossible.

Input & Output

Example 1 — Impossible Case
$ Input: basket1 = [4,1,2,1], basket2 = [1,4,3,2]
Output: -1
💡 Note: Fruit 1 appears 3 times total (2+1) and fruit 3 appears 1 time total. Since these are odd counts, equal distribution is impossible.
Example 2 — Single Swap
$ Input: basket1 = [1,2,3,4], basket2 = [1,2,3,4]
Output: 0
💡 Note: Baskets are already equal, no swaps needed.
Example 3 — Optimal Swaps
$ Input: basket1 = [4,1,2,1], basket2 = [1,4,1,2]
Output: 1
💡 Note: Both baskets have same fruit counts: 1 appears 2+2=4 times, 2 appears 1+1=2 times, 4 appears 1+1=2 times. Need to swap one element with cost min(any pair) = 1.

Constraints

  • 1 ≤ basket1.length, basket2.length ≤ 105
  • basket1.length == basket2.length
  • 1 ≤ basket1[i], basket2[i] ≤ 109

Visualization

Tap to expand
Rearranging Fruits - Optimal Solution INPUT basket1 4 1 2 1 basket2 1 4 3 2 Combined multiset: {1,1,1,2,2,3,4,4} 4 1 2 3 n = 4 fruits per basket Total: 8 fruits Note: 3 appears only once! ALGORITHM STEPS 1 Count Frequencies Count each fruit in both baskets combined 2 Check Divisibility Each fruit must appear EVEN number of times 3 Find Excess Fruits Identify fruits to swap from each basket 4 Calculate Min Cost Use greedy: swap cheapest or use min as mediator Frequency Analysis: Fruit 1: 3 times (ODD!) Fruit 2: 2 times (OK) Fruit 3: 1 time (ODD!) Fruit 4: 2 times (OK) X FINAL RESULT Output: -1 IMPOSSIBLE! Why -1? Fruit 3 appears exactly ONCE in total (in basket2). For equal baskets, each fruit needs EVEN count (to split equally: n/2 each) Cannot split 3 evenly: 3 / 2 = 1.5 (not integer) Same for fruit 1: 3/2 = 1.5 Key Insight: For two baskets to be equal after sorting, the COMBINED multiset of all fruits must have each fruit appearing an EVEN number of times. This is because each basket must end up with exactly half of each fruit. If any fruit has an odd count, it's impossible to split equally --> return -1. Otherwise, use greedy swaps! TutorialsPoint - Rearranging Fruits | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
25.4K Views
Medium Frequency
~35 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