Skip to main content
Back to problems
#3868
Medium Algorithms

Minimum cost to equalize arrays using swaps

Array Hash Table Greedy Counting
48.2% acceptance
Mar 31, 2026
63
2
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.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
use std::collections::HashMap;

impl Solution {
  pub fn min_cost(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
    let n = nums1.len();
    let mut count = HashMap::new();
    let mut count1 = HashMap::new();
    
    for i in 0..n {
      if nums1[i] != nums2[i] {
        *count.entry(nums1[i]).or_insert(0i32) += 1;
        *count.entry(nums2[i]).or_insert(0i32) += 1;
        *count1.entry(nums1[i]).or_insert(0i32) += 1;
      }
    }
    
    if count.is_empty() {
      return 0;
    }
    
    for (_, &c) in &count {
      if c % 2 != 0 {
        return -1;
      }
    }
    
    let mut cost = 0;
    for (&v, &total) in &count {
      let have = *count1.get(&v).unwrap_or(&0);
      let need = total / 2;
      if have > need {
        cost += have - need;
      }
    }
    
    cost
  }
}