Minimum Cost to Equalize Arrays Using Swaps

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:

  • Internal Swap (Free): Swap any two elements within nums1 or any two within nums2.
  • Swap between two arrays: Choose an index i. Then, swap nums1[i] and nums2[i]. This operation incurs a cost of 1.

Return the minimum cost to make nums1 and nums2 identical. If it's impossible, return -1.

Example 1:

Input: nums1 = [4, 5, 6], nums2 = [4, 5, 7]

Output: -1

Explanation:

The numbers 6 and 7 appear exactly once in total across both arrays. Since their total frequencies are odd, it is impossible to split them evenly to make the two arrays identical.

Example 2:

Input: nums1 = [8, 8, 8, 9], nums2 = [8, 9, 9, 9]

Output: 1

Explanation:

The total count is four 8s and four 9s. Each array must have two 8s and two 9s. nums1 has an extra 8, and nums2 has an extra 9. A single cross-array swap of an 8 for a 9 balances both arrays.

Now Your Turn!

Pick the correct output for the given input

Input: nums1 = [1, 2, 3, 4], nums2 = [4, 3, 2, 1]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 2 <= n == nums1.length == nums2.length <= 8 * 104
  • 1 <= nums1[i], nums2[i] <= 8 * 104

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
int minCost(vector<int>& nums1, vector<int>& nums2) {
// Write your code here
 
 
}
};
Test Case

Input:

Nums1
Nums2