Minimum Cost to Equalize Arrays Using Swaps Problem
Description
LeetCode Problem 3868.
You are given two integer arrays nums1 and nums2 of size n.
You can perform the following two operations any number of times on these two arrays:
- Swap within the same array: Choose two indices
iandj. Then, choose either to swapnums1[i]andnums1[j], ornums2[i]andnums2[j]. This operation is free of charge. - Swap between two arrays: Choose an index
i. Then, swapnums1[i]andnums2[i]. This operation incurs a cost of 1.
Return an integer denoting the minimum cost to make nums1 and nums2 identical. If this is not possible, return -1.
Example 1:
Input: nums1 = [10,20], nums2 = [20,10]
Output: 0
Explanation:
- Swap nums2[0] = 20 and nums2[1] = 10.
- nums2 becomes [10, 20].
- This operation is free of charge.
- nums1 and nums2 are now identical. The cost is 0.
Example 2:
Input: nums1 = [10,10], nums2 = [20,20]
Output: 1
Explanation:
- Swap nums1[0] = 10 and nums2[0] = 20.
- nums1 becomes [20, 10].
- nums2 becomes [10, 20].
- This operation costs 1.
- Swap nums2[0] = 10 and nums2[1] = 20.
- nums2 becomes [20, 10].
- This operation is free of charge.
- nums1 and nums2 are now identical. The cost is 1.
Example 3:
Input: nums1 = [10,20], nums2 = [30,40]
Output: -1
Explanation:
It is impossible to make the two arrays identical. Therefore, the answer is -1.
Constraints:
2 <= n == nums1.length == nums2.length <= 8 * 10^41 <= nums1[i], nums2[i] <= 8 * 10^4
Solution
Approach: Counting Values
Swaps inside one array are free, so only the multiset of values in each array matters. Count the values of nums2, then go through nums1 and cancel each value against a matching copy in nums2; the values of nums1 that find no partner are counted in cnt1, and what is left of nums2 is cnt2. Both arrays can only end up equal if every value ends up with an even total count, so if any count in cnt1 or cnt2 is odd the answer is -1. Otherwise every two surplus copies in nums1 can be exchanged with two surplus copies in nums2 by one paid swap, so the cost is the sum of cnt1[v] / 2.
Complexity: O(n) time and O(n) space.
class Solution:
def minCost(self, nums1: List[int], nums2: List[int]) -> int:
cnt2 = Counter(nums2)
cnt1 = Counter()
for x in nums1:
if cnt2[x]:
cnt2[x] -= 1
else:
cnt1[x] += 1
ans = 0
for v in cnt1.values():
if v % 2 == 1:
return -1
ans += v // 2
for v in cnt2.values():
if v % 2 == 1:
return -1
return ans