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: Balance Two BasketsBasket 1: [4,1,2,1]4121Basket 2: [1,4,3,2]1432Check frequency: 1→3 times, 2→2 times, 3→1 time, 4→2 timesImpossible! Fruits 1 and 3 have odd total countsFor equal distribution:Each fruit must appear even number of times totalOutput: -1
Understanding the Visualization
1
Input Baskets
Two baskets with different fruit distributions
2
Frequency Check
Verify if equal distribution is mathematically possible
3
Optimal Swaps
Find minimum cost swaps to balance baskets
Key Takeaway
🎯 Key Insight: Use frequency analysis to check feasibility, then greedily match excess elements for minimum swap cost
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