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
iandj, and swap theithfruit ofbasket1with thejthfruit ofbasket2. - 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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code