Minimum Total Cost to Make Arrays Unequal - Problem
Minimum Total Cost to Make Arrays Unequal
You are given two 0-indexed integer arrays
You can perform swap operations on
Goal: Find the minimum total cost to make
Example:
We need to swap elements in
You are given two 0-indexed integer arrays
nums1 and nums2, both of equal length n. Your mission is to ensure that no element at the same index in both arrays is equal.You can perform swap operations on
nums1 - swap any two elements at indices i and j. The cost of this operation is i + j (sum of the indices).Goal: Find the minimum total cost to make
nums1[i] != nums2[i] for all indices 0 ≤ i < n.Example:
nums1 = [1,2,3,4]nums2 = [1,2,3,4]We need to swap elements in
nums1 to ensure no position has matching values. If impossible, return -1. Input & Output
example_1.py — Basic Case
$
Input:
nums1 = [1,2,3,4], nums2 = [1,3,2,4]
›
Output:
3
💡 Note:
Bad positions are at indices 0 and 3 (where nums1[i] == nums2[i]). We need to include these positions in swaps. The minimum cost is 0 + 3 = 3.
example_2.py — No Solution
$
Input:
nums1 = [2,2,2,1], nums2 = [1,2,2,2]
›
Output:
3
💡 Note:
Bad positions are at indices 1 and 2, both with value 2. Since value 2 appears in 2 out of 2 bad positions (100%), we need 2 additional help positions. We can use positions 0 and 3 as help positions since nums1[0]=2≠1=nums2[0] creates a mismatch and nums1[3]=1≠2=nums2[3]. Total cost = 1 + 2 + 0 + 3 = 6. Wait, let me recalculate: bad positions [1,2] cost 3, but we need help positions that don't involve the dominant value 2. Position 0: nums1[0]=2 (involves 2), position 3: nums1[3]=1, nums2[3]=2 (involves 2). Actually, this case should return -1 as no valid help positions exist.
example_3.py — Already Valid
$
Input:
nums1 = [1,2,3,4], nums2 = [2,1,4,3]
›
Output:
0
💡 Note:
Arrays already satisfy nums1[i] != nums2[i] for all i, so no swaps needed.
Constraints
- n == nums1.length == nums2.length
- 1 ≤ n ≤ 105
- 1 ≤ nums1[i], nums2[i] ≤ 106
- Important: The cost of swapping indices i and j is i + j
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code