#2561
Rearranging Fruits
HardArrayHash TableGreedySortHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses frequency maps to count occurrences of each fruit cost in both baskets. This allows us to determine if it's possible to make the baskets equal and calculate the minimum cost efficiently.
⚙️
Algorithm
4 steps- 1Step 1: Create frequency maps for both baskets to count occurrences of each fruit cost.
- 2Step 2: Check if the sum of frequencies for each unique fruit cost is odd; if so, return -1 (impossible to balance).
- 3Step 3: Calculate the minimum fruit cost from both baskets to use in swap calculations.
- 4Step 4: For each unique fruit cost, calculate the total number of swaps needed and the associated costs.
solution.py15 lines
1from collections import Counter
2
3def minCost(basket1, basket2):
4 count1 = Counter(basket1)
5 count2 = Counter(basket2)
6 total_cost = 0
7 min_fruit = min(min(basket1), min(basket2))
8
9 for fruit in set(count1.keys()).union(set(count2.keys())):
10 total_count = count1[fruit] + count2[fruit]
11 if total_count % 2 != 0:
12 return -1
13 total_cost += abs(count1[fruit] - count2[fruit]) // 2 * min_fruit
14
15 return total_costℹ
Complexity note: This complexity is efficient because we only traverse each basket a limited number of times to create frequency maps and calculate costs.
- 1Both baskets must have the same total count of each fruit type for them to be rearranged into identical baskets.
- 2The minimum fruit cost is crucial for calculating the cost of swaps effectively.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.