Rearranging Fruits

Minimum cost to equalize two baskets by swapping — sort the symmetric-difference half and use the global min as a "courier".

Hard
Time O((n + m) log (n + m)) Space O(n + m)
LeetCode
5 min read
greedy sorting hash-map

Problem#

Two baskets basket1, basket2. Multiset equal means same frequencies. In one swap, exchange one element from each at cost min(a, b). Return minimum total cost to equalize, or -1.

Examples#

  • basket1 = [4,2,2,2], basket2 = [1,4,1,2]1
  • basket1 = [2,3,4,1], basket2 = [3,2,5,1]-1

Constraints#

  • 1 <= n <= 10^5.

Hints#

Hint 1
Each fruit’s count must be even between the two baskets; else -1. Then split each basket’s excess into the “to-swap” pool.

Approach#

Count frequency differences diff[v] = count1(v) - count2(v). If any |diff[v]| is odd, return -1. Build two lists: items where diff > 0 (excess in 1) and diff < 0 (excess in 2), each appearing |diff|/2 times. Sort both. Pair smallest-with-largest greedily — direct swap cost is min(a, b). Alternative: use the global minimum as a “courier” — cost 2 * globalMin per swap if cheaper. Take the min across all pairings.

Solution#

Rearranging Fruits
class Solution {
public:
long long minCost(vector<int>& basket1, vector<int>& basket2) {
unordered_map<int,int> diff;
for (int x : basket1) ++diff[x];
for (int x : basket2) --diff[x];
int globalMin = INT_MAX;
vector<int> excess;
for (auto& [v, d] : diff) {
if (d % 2 != 0) return -1;
int half = abs(d) / 2;
for (int i = 0; i < half; ++i) excess.push_back(v);
globalMin = min(globalMin, v);
}
sort(excess.begin(), excess.end());
long long cost = 0;
int half = excess.size() / 2;
for (int i = 0; i < half; ++i) {
cost += min((long long)excess[i], 2LL * globalMin);
}
return cost;
}
};

Editorial#

The “courier” trick: instead of swapping a and b directly (cost min(a, b)), swap each with the global minimum m and use m as intermediary — total cost 2m. Whenever 2m < min(a, b), the courier wins. Sorting the bottom half of the excess pool gives the cheapest pairings.

Complexity#

  • Time: O((n + m) log (n + m)).
  • Space: O(n + m).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.