HardArrayHash TableGreedySortingUpdated Sep 2026

2561. Rearranging Fruits

Asked at Atlassian

Difficulty

Hard

Time

O(n log n)

Space

O(n)

Pattern

Array

Companies

1

Problem

You are given two baskets of fruit, basket1 and basket2, each holding the same number of fruits. Each fruit has a cost, given as an integer. You want both baskets to hold the same multiset of costs — that is, after sorting each basket, the two sorted lists must be identical.

You may repeat this operation any number of times: pick one fruit from basket1 and one fruit from basket2, and swap them. The cost of that swap is the smaller of the two fruit costs involved. Swaps are independent, so the total cost is the sum of the individual swap costs.

Return the minimum total cost to make the baskets equal, or -1 if it cannot be done at all.

Swap one fruit from each basket

basket142220123basket1 has an extra 2 that basket2 does not needbasket214120123basket2 has an extra 1 that basket1 does not needswap cost = min(2, 1) = 1after swap both baskets match
Each swap picks one fruit from each side and costs the smaller of the two values.

Constraints

  • ●basket1.length == basket2.length
  • ●1 <= basket1.length <= 10^5
  • ●1 <= basket1[i], basket2[i] <= 10^9

Examples

Example 1
Inputbasket1 = [4,2,2,2], basket2 = [1,4,1,2]
Output1
WhySwap the 2 at index 1 of basket1 with the 1 at index 0 of basket2. The swap costs min(2,1) = 1. Now basket1 is [4,1,2,2] and basket2 is [2,4,1,2], which are the same multiset. No cheaper option exists, so the answer is 1.
Example 2
Inputbasket1 = [2,3,4,1], basket2 = [3,2,5,1]
Output-1
WhyThe value 4 appears once in total and the value 5 appears once in total. A value with an odd total count can never be split evenly between the two baskets, so it is impossible.

Asked At

1 companies
CompanyDifficulty
AtlassianHardView all Atlassian questions →

How to Think About It

1

Check feasibility first: both baskets must have the same total number of elements, and each fruit value must appear an even number of times across both baskets combined.

2

Count the frequency of each value across both baskets. Values with odd counts make the problem impossible.

3

Identify mismatched elements: for each value, find the excess in one basket that needs to be swapped to the other.

4

Greedy strategy: for each pair of mismatched elements, swap the smaller pair directly if possible. Otherwise, use the globally smallest element as a swap intermediary.

5

Optimal: O(n log n) time using counting and sorting. The key insight is that you only need to consider the smaller of each mismatched pair or twice the global minimum.

Optimal Approach

First check if a solution is possible: both baskets must have the same length, and every fruit value must have an even total count across both baskets. Count frequencies of each value across both baskets. For each value, compute the excess in basket1 versus basket2 — this gives a list of values that need to be swapped. Split these into two groups: values that need to go from basket1 to basket2, and values that need to go the other way. Sort both lists. The minimum cost is the sum of min(directSwapCost, 2 * globalMin) for each pair, where directSwapCost is the smaller element in each mismatched pair. Use O(n log n) time for sorting.

Collect mismatches, then pair them cheaply

swaps1201Only one value must leave each basket: 1 and 2count both basketsodd total count → -1collect excess valuessort thempair smallest with largestThe algorithm in five stepscost += min(swaps[i], 2 * globalMin)globalMin = 1, so 2 * globalMin = 2min(1, 2) = 1 → total cost 1
Sort the values that must move, then pay min(value, 2 × global minimum) for each pair.
ComplexityTime O(n log n)Space O(n)The cost comes from counting values and sorting the list of mismatched values; the final pairing pass is linear.

What Trips People Up in Real Interviews

1

Start by stating the impossibility conditions clearly — this shows you think about edge cases.

2

Explain the frequency counting approach: if a value appears an odd total number of times, return -1.

3

Describe the greedy swap strategy: always try to swap the smaller element directly.

4

Discuss the role of the global minimum element: it serves as a swap intermediary when direct swap is suboptimal.

5

Walk through an example where the global minimum is needed to reduce total swap cost.

Solution Code

O(n log n) time
def minCost(basket1, basket2):
    from collections import Counter
    total = Counter(basket1) + Counter(basket2)
    for v in total.values():
        if v % 2 != 0:
            return -1
    c1 = Counter(basket1)
    c2 = Counter(basket2)
    swaps = []
    for v in total:
        diff = c1.get(v, 0) - c2.get(v, 0)
        swaps.extend([v] * abs(diff // 2))
    if not swaps:
        return 0
    swaps.sort()
    global_min = min(min(basket1), min(basket2))
    result = 0
    for i in range(len(swaps) // 2):
        result += min(swaps[i], 2 * global_min)
    return result

Pro at DSA?

Test your skills with a real FAANG-style mock interview.

Start a Mock Interview →

Frequently Asked Questions

What is the Rearranging Fruits problem?

You have two baskets of fruits, basket1 and basket2, each represented as an integer array. You can swap one fruit from basket1 with one fruit from basket2 at a cost equal to the minimum of the two fruit values. The goal is to make both baskets contain the same multiset of fruits (same elements with same frequencies). Return the minimum total cost to achieve this, or return -1 if it is impossible.

How do you solve Rearranging Fruits?

The optimal approach runs in O(n log n) time and O(n) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.

What companies ask Rearranging Fruits?

Rearranging Fruits is asked at Atlassian. It is a hard difficulty problem.

What are common mistakes on Rearranging Fruits?
  • Start by stating the impossibility conditions clearly — this shows you think about edge cases.
  • Explain the frequency counting approach: if a value appears an odd total number of times, return -1.
  • Describe the greedy swap strategy: always try to swap the smaller element directly.
  • Discuss the role of the global minimum element: it serves as a swap intermediary when direct swap is suboptimal.
  • Walk through an example where the global minimum is needed to reduce total swap cost.