[LeetCode] Minimum Cost to Equalize Arrays Using Swaps

3868. 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:

  • Swap within the same array: Choose two indices i and j. Then, choose either to swap nums1[i] and nums1[j], or nums2[i] and nums2[j]. This operation is free of charge.
  • Swap between two arrays: Choose an index i. Then, swap nums1[i] and nums2[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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int minCost(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int,int> freq;
for(auto& n : nums1) freq[n]++;
for(auto& n : nums2) freq[n]++;
for(auto& [k,v] : freq) if(v&1) return -1;
freq = {};
for(auto& n : nums1) freq[n]++;
for(auto& n : nums2) freq[n]--;
int res = 0;
for(auto& [k,v] : freq) res += abs(v);
return res / 4;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/minimum-cost-to-equalize-arrays-using-swaps/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.