Minimum sum of absolute difference of pairs of two arrays

Pattern: Candy and assign cookies

medium

Pair the values of two equal-length arrays to make the sum of |a - b| smallest: sort both and pair them in order. A crossed pairing can always be uncrossed without increasing the total.

The problem

Pair each value of a with a different value of b (same lengths) to make the sum of |a[i] - b[j]| over the pairs as small as possible, and return it. a = [4, 1, 8, 7], b = [2, 3, 6, 5] gives 6.

Think first

  • If a1 < a2 and b1 < b2, which pairing is better?
  • What does that say about the whole pairing?
  • How do you get it?

Hints

    Brute force, and why it fails

    Try every pairing: O(n! × n).

    The key insight

    Uncrossing any crossed pair never increases the total, so the sorted pairing is optimal.

    Dry run

    pairs1-2 4-3 7-5 8-6

    a = [4, 1, 8, 7], b = [2, 3, 6, 5]. Sorted: a = 1, 4, 7, 8 and b = 2, 3, 5, 6.

    Step 1 of 3

    The plan

    sort a; sort b
    return sum of |a[i] - b[i]|
    

    Complexity

    Time
    O(n log n)
    Space
    O(n)

    Two sorts.

    Edge cases

    • Equal arrays: 0.
    • Negative values.
    • One pair.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public long findMinSum(int[] a, int[] b) {
            int[] x = a.clone(), y = b.clone();
            Arrays.sort(x);
            Arrays.sort(y);                         // pair the i-th smallest with the i-th smallest
            long sum = 0;
            for (int i = 0; i < x.length; i++) sum += Math.abs((long) x[i] - y[i]);
            return sum;
        }
    }

    C++

    class Solution {
    public:
        long long findMinSum(vector<int>& a, vector<int>& b) {
            vector<int> x(a), y(b);
            sort(x.begin(), x.end());
            sort(y.begin(), y.end());               // pair the i-th smallest with the i-th smallest
            long long sum = 0;
            for (size_t i = 0; i < x.size(); i++) sum += llabs(static_cast<long long>(x[i]) - y[i]);
            return sum;
        }
    };

    Python

    class Solution:
        def findMinSum(self, a: list[int], b: list[int]) -> int:
            return sum(abs(x - y) for x, y in zip(sorted(a), sorted(b)))   # pair the i-th smallest with the i-th smallest

    Common mistakes

    • Pairing in input order.
    • Sorting one array ascending and the other descending.

    Similar problems