Magicsheet logo

Minimum Absolute Sum Difference

Medium
50%
Updated 8/1/2025

Minimum Absolute Sum Difference

What is this problem about?

In the Minimum Absolute Sum Difference problem, you are given two arrays, nums1 and nums2. Initially, the "absolute sum difference" is the sum of |nums1[i] - nums2[i]| for all i. You are allowed to replace exactly one element in nums1 with any other element already present in nums1 to minimize this total sum. The goal is to find the maximum possible reduction you can achieve by making this single strategic swap.

Why is this asked in interviews?

Companies like Uber ask this Minimum Absolute Sum Difference interview question to evaluate a candidate's ability to optimize a global value through a local change. It requires a mix of Sorting and Binary Search. It's not just about finding a difference; it's about searching through a set of candidates (all values in nums1) to find the best possible replacement for a specific index to minimize the local error.

Algorithmic pattern used

The primary Binary Search interview pattern is used here. First, you calculate the initial total sum difference. Then, you create a sorted version of nums1. For each index i, you want to replace nums1[i] with a value from the sorted nums1 that is closest to nums2[i]. Using binary search (bisect_left or lower_bound), you can quickly find the closest value in O(logN)O(\log N) time. By checking all indices, you find the one that gives the largest "improvement."

Example explanation

Let nums1 = [1, 7, 5] and nums2 = [2, 3, 5].

  1. Initial differences: |1-2|=1, |7-3|=4, |5-5|=0. Total = 5.
  2. Sorted nums1: [1, 5, 7].
  3. Try replacing nums1[1] (which is 7). We want a value in [1, 5, 7] closest to nums2[1] (which is 3).
  4. Binary search finds 1 and 5.
    • If we use 1: |1-3| = 2. Improvement = 4 - 2 = 2.
    • If we use 5: |5-3| = 2. Improvement = 4 - 2 = 2.
  5. The best improvement is 2. New total sum = 5 - 2 = 3.

Common mistakes candidates make

  • Replacing with any value: Thinking you can replace nums1[i] with any integer, rather than only values that already exist in nums1.
  • Linear search for best replacement: For each index, scanning the entire nums1 array to find the closest value. this results in an O(N2)O(N^2) solution, which is inefficient.
  • Forgetting the Modulo: This problem often requires the answer modulo 109+710^9 + 7. Candidates sometimes apply the modulo during the improvement calculation, which can lead to incorrect comparisons (since a < b doesn't mean a % mod < b % mod).

Interview preparation tip

Practice finding the "closest element in a sorted array" using binary search. This is a very common sub-task in Minimum Absolute Sum Difference coding problems and many other competitive programming tasks. Understanding how to handle the two closest candidates (the one just smaller and the one just larger) is essential.

Similar Questions