Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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:
i and j, and swap the ith fruit of basket1 with the jth fruit of basket2.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.
Example 1:
Input: basket1 = [4,2,2,2], basket2 = [1,4,1,2] Output: 1 Explanation: Swap index 1 of basket1 with index 0 of basket2, which has cost 1. Now basket1 = [4,1,2,2] and basket2 = [2,4,1,2]. Rearranging both the arrays makes them equal.
Example 2:
Input: basket1 = [2,3,4,1], basket2 = [3,2,5,1] Output: -1 Explanation: It can be shown that it is impossible to make both the baskets equal.
Constraints:
basket1.length == basket2.length1 <= basket1.length <= 1051 <= basket1[i], basket2[i] <= 109Problem summary: 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 i and j, and swap the ith fruit of basket1 with the jth fruit of basket2. 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Greedy
[4,2,2,2] [1,4,1,2]
[2,3,4,1] [3,2,5,1]
the-latest-time-to-catch-a-bus)minimum-number-of-operations-to-make-arrays-similar)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2561: Rearranging Fruits
class Solution {
public long minCost(int[] basket1, int[] basket2) {
int n = basket1.length;
Map<Integer, Integer> cnt = new HashMap<>();
for (int i = 0; i < n; ++i) {
cnt.merge(basket1[i], 1, Integer::sum);
cnt.merge(basket2[i], -1, Integer::sum);
}
int mi = 1 << 30;
List<Integer> nums = new ArrayList<>();
for (var e : cnt.entrySet()) {
int x = e.getKey(), v = e.getValue();
if (v % 2 != 0) {
return -1;
}
for (int i = Math.abs(v) / 2; i > 0; --i) {
nums.add(x);
}
mi = Math.min(mi, x);
}
Collections.sort(nums);
int m = nums.size();
long ans = 0;
for (int i = 0; i < m / 2; ++i) {
ans += Math.min(nums.get(i), mi * 2);
}
return ans;
}
}
// Accepted solution for LeetCode #2561: Rearranging Fruits
func minCost(basket1 []int, basket2 []int) (ans int64) {
cnt := map[int]int{}
for i, a := range basket1 {
cnt[a]++
cnt[basket2[i]]--
}
mi := 1 << 30
nums := []int{}
for x, v := range cnt {
if v%2 != 0 {
return -1
}
for i := abs(v) / 2; i > 0; i-- {
nums = append(nums, x)
}
mi = min(mi, x)
}
sort.Ints(nums)
m := len(nums)
for i := 0; i < m/2; i++ {
ans += int64(min(nums[i], mi*2))
}
return
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
# Accepted solution for LeetCode #2561: Rearranging Fruits
class Solution:
def minCost(self, basket1: List[int], basket2: List[int]) -> int:
cnt = Counter()
for a, b in zip(basket1, basket2):
cnt[a] += 1
cnt[b] -= 1
mi = min(cnt)
nums = []
for x, v in cnt.items():
if v % 2:
return -1
nums.extend([x] * (abs(v) // 2))
nums.sort()
m = len(nums) // 2
return sum(min(x, mi * 2) for x in nums[:m])
// Accepted solution for LeetCode #2561: Rearranging Fruits
use std::collections::HashMap;
impl Solution {
pub fn min_cost(basket1: Vec<i32>, basket2: Vec<i32>) -> i64 {
let n = basket1.len();
let mut cnt: HashMap<i32, i32> = HashMap::new();
for i in 0..n {
*cnt.entry(basket1[i]).or_insert(0) += 1;
*cnt.entry(basket2[i]).or_insert(0) -= 1;
}
let mut mi = i32::MAX;
let mut nums = Vec::new();
for (x, v) in cnt {
if v % 2 != 0 {
return -1;
}
for _ in 0..(v.abs() / 2) {
nums.push(x);
}
mi = mi.min(x);
}
nums.sort();
let m = nums.len();
let mut ans = 0;
for i in 0..(m / 2) {
ans += nums[i].min(mi * 2) as i64;
}
ans
}
}
// Accepted solution for LeetCode #2561: Rearranging Fruits
function minCost(basket1: number[], basket2: number[]): number {
const n = basket1.length;
const cnt: Map<number, number> = new Map();
for (let i = 0; i < n; i++) {
cnt.set(basket1[i], (cnt.get(basket1[i]) || 0) + 1);
cnt.set(basket2[i], (cnt.get(basket2[i]) || 0) - 1);
}
let mi = Number.MAX_SAFE_INTEGER;
const nums: number[] = [];
for (const [x, v] of cnt.entries()) {
if (v % 2 !== 0) {
return -1;
}
for (let i = 0; i < Math.abs(v) / 2; i++) {
nums.push(x);
}
mi = Math.min(mi, x);
}
nums.sort((a, b) => a - b);
const m = nums.length;
let ans = 0;
for (let i = 0; i < m / 2; i++) {
ans += Math.min(nums[i], mi * 2);
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.