Data Structures & AlgorithmsVery hardProduct company OA · Amazon/Microsoft-style OA

Two multisets A = {7, 2, 9, 4, 5} and B = {3, 8, 1, 6, 10} are matched one-to-one, pairing each element of A with exactly one element of B. What is the minimum possible total of |a - b| over all such matchings?

  1. A. 8
  2. B. 10
  3. C. 5
  4. D. 25

Correct answer: C. 5

Sorting both sets and pairing in order is optimal for the sum of absolute differences, which is the exchange argument behind two-pointer matching. Pairing the two sorted lists in order gives the same value as the best permutation found by brute force.

More Coding Interview Problems questions

Exams that ask this topic