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.

Example 1
Inputnums1 = [10,20], nums2 = [20,10]
Output0
Swapping nums2[0] and nums2[1] is free and makes nums2 equal to [10, 20], so the cost is 0.
Example 2
Inputnums1 = [10,10], nums2 = [20,20]
Output1
Swapping nums1[0] with nums2[0] costs 1, then a free swap within nums2 makes both arrays identical.

Constraints

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

Asked at 2 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate