Taro Logo

Minimum Cost to Equalize Arrays Using Swaps

#1 Most AskedMedium
0 views
Topics:
ArraysGreedy Algorithms

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:

Input: nums1 = [10,20], nums2 = [20,10]

Output: 0

Explanation:

  • Swap nums2[0] = 20 and nums2[1] = 10.
    • nums2 becomes [10, 20].
    • This operation is free of charge.
  • nums1 and nums2 are now identical. The cost is 0.

Example 2:

Input: nums1 = [10,10], nums2 = [20,20]

Output: 1

Explanation:

  • Swap nums1[0] = 10 and nums2[0] = 20.
    • nums1 becomes [20, 10].
    • nums2 becomes [10, 20].
    • This operation costs 1.
  • Swap nums2[0] = 10 and nums2[1] = 20.
    • nums2 becomes [20, 10].
    • This operation is free of charge.
  • nums1 and nums2 are now identical. The cost is 1.

Example 3:

Input: nums1 = [10,20], nums2 = [30,40]

Output: -1

Explanation:

It is impossible to make the two arrays identical. Therefore, the answer is -1.

Constraints:

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the specific indicator (e.g., -1) we should return if it is impossible to make nums1 and nums2 identical?
  2. What are the constraints on the length of the arrays and the value ranges of the elements inside nums1 and nums2?
  3. Can the arrays contain negative numbers, zeros, or duplicate values?
  4. Does the cost value for a swap have any constraints, such as being non-negative?
  5. Are nums1 and nums2 guaranteed to be non-empty and of equal length?

Brute Force Solution

Approach

The problem asks for the minimum cost to make two arrays identical using free internal swaps and costly between-array swaps. Since internal swaps are free, making the arrays identical is equivalent to making the multiset of elements in both arrays identical. Each between-array swap moves one element from one array to the other, so we simply need to count how many excess elements must be transferred.

Here's how the algorithm would work step-by-step:

  1. Combine the frequency counts of all numbers from both input arrays.
  2. Verify that every distinct number appears an even total number of times across both arrays, returning -1 if any count is odd.
  3. Determine the target frequency for each number in a single array, which is half of its total count.
  4. Sum the excess counts of elements in the first array relative to their target frequency.
  5. Return the total excess count as the minimum number of between-array swaps needed.

Code Implementation

from collections import Counter

def min_cost_to_equalize_arrays(nums1, nums2):
    # Count the total occurrences of each element across both arrays
    total_counts = Counter(nums1) + Counter(nums2)
    
    # Check if every element appears an even number of times in total
    for value, total_count in total_counts.items():
        if total_count % 2 != 0:
            return -1
            
    first_array_counts = Counter(nums1)
    excess_swaps = 0
    
    # Calculate how many elements need to be transferred across arrays
    for value, target_count in total_counts.items():
        half_count = target_count // 2
        current_count = first_array_counts[value]
        if current_count > half_count:
            excess_swaps += current_count - half_count
            
    return excess_swaps

Big(O) Analysis

Time Complexity
O(n) – We iterate through both arrays of length n to construct frequency counts and then iterate over the unique keys, taking linear time overall.
Space Complexity
O(n) – The frequency hash maps store at most 2n unique elements across both arrays, which requires linear extra space.

Optimal Solution

Approach

Since internal swaps within an array are free, the order of elements does not matter. The goal is simply to distribute the combined multiset of elements equally between the two arrays so that both have identical element frequencies. Therefore, every distinct value must appear an even number of times overall, and the minimum number of inter-array swaps needed equals half of the total absolute differences in frequency counts.

Here's how the algorithm would work step-by-step:

  1. Count the frequency of each number in the first array, the second array, and their combination.
  2. Verify that every distinct number in the combined frequencies appears an even number of times; if any does not, return -1.
  3. Determine the target frequency for each distinct number in each array, which is exactly half of its combined count.
  4. Sum the excess counts where an element appears more frequently in the first array than its target frequency.
  5. Return this sum as the minimum number of cost-incurring swaps between arrays.

Code Implementation

from collections import Counter

def min_cost_to_equalize_arrays(nums1: list[int], nums2: list[int]) -> int:
    # Count frequencies of each number in both arrays combined and individually
    count1 = Counter(nums1)
    count2 = Counter(nums2)
    total_counts = count1 + count2
    
    # Check if any element occurs an odd number of times in total
    for value, frequency in total_counts.items():
        if frequency % 2 != 0:
            return -1
            
    # Calculate total elements that must be swapped between arrays
    imbalance = 0
    for value, frequency in total_counts.items():
        target = frequency // 2
        if count1[value] > target:
            imbalance += count1[value] - target
            
    # Each swap adjusts one excess from nums1 and one excess from nums2
    return imbalance

Big(O) Analysis

Time Complexity
O(n) – We iterate through the input arrays of length n to build the frequency maps, and then iterate through the unique elements, which is bounded by O(n).
Space Complexity
O(n) – The frequency hash maps store counts for at most 2n unique elements across both arrays.

Edge Cases

Empty arrays or arrays of differing lengths
How to Handle:
Return an error indicator or invalid cost immediately since equal-length inputs are required.
Arrays of length one with differing elements at the single index
How to Handle:
Compare the single elements and return either zero if they match or the swap cost if they differ.
Already identical arrays where no swaps are needed
How to Handle:
Verify element equality across all positions initially and return a total cost of zero immediately.
Impossible configuration where total counts of each unique value across both arrays do not match
How to Handle:
Check frequency distributions of all combined elements and return the failure indicator if counts differ.
Extreme magnitude values including negative numbers and large integers
How to Handle:
Use 64-bit integer accumulators to prevent overflow when calculating the cumulative swap costs.
Maximum possible input size with large arrays
How to Handle:
Use an efficient O(N) frequency counting approach to scale within time limits without exceeding memory.
All elements are identical within and across both arrays
How to Handle:
Bypass complex swap calculations and return zero cost since the arrays are already equivalent.
0/1 completed