Problem
You are given two 0-indexed integer arrays nums1
and nums2
, of equal length n
.
In one operation, you can swap the values of any two indices of nums1
. The
cost of this operation is the sum of the indices.
Find the minimum total cost of performing the given operation any number of times such that nums1[i] != nums2[i]
for all 0 <= i <= n - 1
after performing all the operations.
Return _theminimum total cost such that _nums1
and nums2
satisfy the above condition. In case it is not possible, return -1
.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
n == nums1.length == nums2.length
1 <= n <= 10^5
1 <= nums1[i], nums2[i] <= n
Solution
Method 1 – Greedy Counting and Swapping
Intuition
We need to ensure that for every index, nums1[i] != nums2[i]
. The main challenge is when the same value appears at the same index in both arrays. We count the frequency of such conflicts and greedily swap with other indices to minimize cost, prioritizing swaps with the lowest indices.
Approach
- Count the frequency of values where
nums1[i] == nums2[i]
. - Track the most frequent conflicting value and its count.
- Collect indices where
nums1[i] != nums2[i]
and neither value is the most frequent conflict. - If the number of available indices is not enough to resolve all conflicts, return -1.
- Otherwise, select the smallest indices to swap and sum their costs.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
— We scan the arrays and count frequencies in linear time. - 🧺 Space complexity:
O(n)
— For frequency maps and extra indices.