#3868

Minimum Cost to Equalize Arrays Using Swaps

Medium
ArrayHash TableGreedyCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Count the frequency of each number in both arrays. If any number has an odd total frequency, return -1. Calculate the minimum swaps needed based on the frequency differences.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the frequency of each number in both arrays using a hash map.
  2. 2Step 2: Check if the total frequency of any number is odd; if so, return -1.
  3. 3Step 3: Calculate the total number of swaps needed based on the frequency differences.
solution.py9 lines
1from collections import Counter
2
3def minCost(nums1, nums2):
4    count1, count2 = Counter(nums1), Counter(nums2)
5    for num in set(count1) | set(count2):
6        if (count1[num] + count2[num]) % 2 != 0:
7            return -1
8    swaps = sum(abs(count1[num] - count2[num]) // 2 for num in count1)
9    return swaps // 2

Complexity note: The complexity is linear due to counting frequencies and checking conditions.

  • 1Frequencies matter more than positions.
  • 2Odd total frequencies indicate impossibility.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.