Solution: Rearranging Fruits

Let’s solve the Rearranging Fruits problem using the Greedy Techniques pattern.

Statement

Given two 0-indexed integer arrays, basket1 and basket2, representing the cost of each fruit in the basket. Each basket contains nn fruits. Make the two baskets identical, i.e., both arrays should have the same weights.

To achieve this, perform the following operation as many times as necessary:

  1. Select two indexes, ii and jj, and swap the fruit at index ii in basket1 with the fruit at index jj in basket2.

  2. The cost of this swap is min(basket1[i], basket2[j]).

The two baskets are considered identical if, after sorting the fruits by cost, both baskets contain exactly the same costs.

Return the minimum cost required to make the baskets identical, or 1-1 if it is impossible.

Constraints:

  • basket1.length == basket2.length

  • 11 \leq basket1.length 103\leq 10^3

  • 11 \leq basket1[i], basket2[i] 104\leq 10^4

Solution

The idea behind this problem is to ensure that both baskets, basket1 and basket2, contain the same number of each type of fruit. A simple approach can be to just swap the excess elements from both baskets until both baskets have the same number of occurrences of those elements.

Here’s how the approach will work:

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.