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 the minimum total cost such that nums1 and nums2 satisfy the above condition. In case it is not possible, return -1.
Example 1:
Input: nums1 = [1,2,3,4,5], nums2 = [1,2,3,4,5] Output: 10 Explanation: One of the ways we can perform the operations is: - Swap values at indices 0 and 3, incurring cost = 0 + 3 = 3. Now, nums1 = [4,2,3,1,5] - Swap values at indices 1 and 2, incurring cost = 1 + 2 = 3. Now, nums1 = [4,3,2,1,5]. - Swap values at indices 0 and 4, incurring cost = 0 + 4 = 4. Now, nums1 =[5,3,2,1,4]. We can see that for each index i, nums1[i] != nums2[i]. The cost required here is 10. Note that there are other ways to swap values, but it can be proven that it is not possible to obtain a cost less than 10.
Example 2:
Input: nums1 = [2,2,2,1,3], nums2 = [1,2,2,3,3] Output: 10 Explanation: One of the ways we can perform the operations is: - Swap values at indices 2 and 3, incurring cost = 2 + 3 = 5. Now, nums1 = [2,2,1,2,3]. - Swap values at indices 1 and 4, incurring cost = 1 + 4 = 5. Now, nums1 = [2,3,1,2,2]. The total cost needed here is 10, which is the minimum possible.
Example 3:
Input: nums1 = [1,2,2], nums2 = [1,2,2] Output: -1 Explanation: It can be shown that it is not possible to satisfy the given conditions irrespective of the number of operations we perform. Hence, we return -1.
Constraints:
n == nums1.length == nums2.length1 <= n <= 1051 <= nums1[i], nums2[i] <= nProblem Overview: You are given two arrays nums1 and nums2. You may swap any two elements in nums1, paying a cost equal to the sum of the swapped indices. The goal is to ensure nums1[i] != nums2[i] for every index while minimizing the total swap cost.
The difficulty comes from positions where nums1[i] == nums2[i]. Those indices already violate the rule and must be involved in swaps. The optimal solution relies on identifying these problematic indices and carefully choosing additional swap positions to avoid creating new conflicts.
Approach 1: Greedy with Counting (O(n) time, O(n) space)
Scan the arrays once and collect indices where nums1[i] == nums2[i]. These indices must participate in swaps, so their indices automatically contribute to the cost. While collecting them, maintain a frequency map of the values appearing at those positions using a hash table. The key observation: if a value appears more than half the time among these bad positions, swapping only among them may still leave conflicts.
Let k be the number of bad indices and track the value with the highest frequency. If the most frequent value occurs more than k / 2 times, you must include extra indices where nums1[i] != nums2[i] and neither value equals the dominant one. Greedily add the smallest valid indices to keep the cost minimal. This strategy ensures every conflicting pair can be resolved without reintroducing equality. The algorithm runs in linear time using a frequency map and index scanning.
This approach heavily relies on greedy reasoning: always add the smallest possible index that breaks the majority conflict. Because indices represent cost, selecting smaller ones guarantees the minimum total.
Approach 2: Two Pointers Candidate Selection (O(n log n) time, O(n) space)
An alternative implementation separates indices into two groups: conflicting indices (nums1[i] == nums2[i]) and safe indices. Store candidate indices and sort them so cheaper swaps appear first. Using a two‑pointer style iteration over these lists, pair conflicting positions and track the dominant value frequency.
If a majority value dominates the conflicting set, move the second pointer through the safe list to add indices that break the majority condition. Sorting and pointer traversal ensure you always consider the lowest cost positions first. The core idea is similar to the greedy solution but expressed through explicit candidate ordering and pointer movement.
This implementation is useful when you want clearer control over which indices are selected during swaps, though the extra sorting step increases complexity slightly.
Recommended for interviews: The greedy counting solution is the expected answer. It runs in O(n) time and demonstrates strong reasoning about majority conflicts and minimal index cost. Interviewers often want to see how you track the dominant value and detect when additional indices are required. Mentioning the two-pointer candidate strategy shows deeper understanding, but the linear greedy solution is the cleanest and most optimal.
This approach uses a greedy strategy to minimize the total cost. We can consider swapping elements in nums1 to ensure that for every i, nums1[i] is not equal to nums2[i]. Here, we try to choose swaps that incur the minimum cost at each step, prioritizing swaps with the minimal sum of indices.
The Python code above iteratively tries to swap every pair of indices i and j in nums1 and checks whether the condition nums1[i] != nums2[i] is satisfied for all i. If it finds a swap that satisfies this condition, it returns the accumulated cost. If no such swap can be found at the end, it returns -1.
Python
JavaScript
Time Complexity: O(n^2), as we can have nested loops generating pairs of indices to swap.
Space Complexity: O(1), as we use no additional space apart from tracking index pairs for minimum swaps.
In this approach, a two-pointers technique is employed to traverse both arrays, parallelly finding matches and performing swaps if necessary. This helps in maintaining synchronization and efficiently managing swaps to minimal encounters.
This C++ solution initializes two pointers - one from the start and one from the end - to traverse nums1. It performs swaps when nums1[i] aligns with nums2[i], borrowing elements from the end of the array to reduce incurred costs, thus optimizing swaps.
Time Complexity: O(n), owing to the singular pass over nums1.
Space Complexity: O(1), given the constant space needed beyond input storage.
| Approach | Complexity |
|---|---|
| Greedy Approach | Time Complexity: O(n^2), as we can have nested loops generating pairs of indices to swap. |
| Two Pointers Approach | Time Complexity: O(n), owing to the singular pass over nums1. |
| Default Approach | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Greedy with Counting | O(n) | O(n) | Best general solution. Handles majority conflicts efficiently using a hash map. |
| Two Pointers Candidate Selection | O(n log n) | O(n) | Useful when explicitly sorting and selecting candidate indices for minimal cost swaps. |
Biweekly Contest 93 | Minimum Total Cost to Make Arrays Unequal • codingMohan • 2,038 views views
Watch 2 more video solutions →Practice Minimum Total Cost to Make Arrays Unequal with our built-in code editor and test cases.
Practice on FleetCode