Sum of Absolute Differences: Fixed Pairs, Sorted Matching, and Prefix Sums

Quick Overview
Work through three different absolute-difference interview prompts, derive the linear prefix-sum algorithm and test its edge cases.
For the arrays [1, 5] and [4, 2], adding the absolute differences of corresponding entries gives 6. If the interviewer allows you to rearrange the second array first, the smallest total is 2. Both questions use the same cost function. They have different answers because one preserves correspondence and one lets you choose it.
Fixed pairs and movable pairs
For fixed pairs, take the absolute value of each difference before adding it. Taking an absolute value only after summing allows positive and negative differences to cancel. In the example above, that mistake gives zero. A coordinate might represent temperature in one position and pressure in another. Sorting those coordinates destroys the feature mapping. When the input is a pair of feature vectors, ask whether the dimensions share a scale and whether distance or similarity is the desired output. Elastic’s guide to vector similarity measures discusses how the choice of measure changes what a search considers close.
If the two lists are interchangeable sets of locations on a line and each location must be matched once, sort both lists. Suppose a ≤ b and x ≤ y. Connecting a to y and b to x costs at least as much as connecting a to x and b to y. To see why, consider the function |t − x| − |t − y|. It is constant before x, increases between x and y, and is constant again after y. Its value at a cannot exceed its value at b. Rearrange that inequality and you get the crossing-pair comparison. Removing crossings one at a time yields an optimal sorted matching.
One total for every element
A third prompt gives one array and asks for a separate total for each position. For [1, 4, 6], those totals are [8, 5, 7]. A loop over every pair takes quadratic time. If the values are already sorted, keep a running sum of the values to the left. For the element x at index i, the left contribution is i times x minus the left sum. The right contribution is the right sum minus the number of right elements times x. Duplicates can fall on either side because each equal element contributes zero.
def distance_totals_sorted(values):
total = sum(values)
left_sum = 0
answer = []
for index, value in enumerate(values):
right_count = len(values) - index - 1
right_sum = total - left_sum - value
left_cost = index * value - left_sum
right_cost = right_sum - right_count * value
answer.append(left_cost + right_cost)
left_sum += value
return answer
The function assumes nondecreasing values. It uses linear time and constant auxiliary space beyond its output. For unsorted input, sort value/index pairs and write each result back to its original index. Otherwise repeated values may conceal the fact that output order was lost. The prefix-sum range query exercise is a useful way to check the subtraction used to recover the right sum.
One center for the entire array
If the output is a single center minimizing the sum of distances to it, choose a median. Move a candidate center one unit to the right on an integer number line. Each point at or below the old center adds one to the total, while each point above it subtracts one. Once at least half the points are on either side, further movement cannot reduce the total. For an even number of points, every center between the two middle values is optimal. With [0, 0, 9], the median 0 has cost 9, while the mean 3 has cost 12.
Test the contract under interview conditions
Try an empty list, a single element, two equal values, and negative coordinates. Compare the optimized routine against a direct double loop on small sorted inputs. For [-3, -1, -1, 4], expect [11, 7, 7, 17]. For a fixed-width integer implementation, choose a type that holds the products and accumulated sums, since each individual input may fit in a narrower type.
For a timed hiring exercise, set separate checkpoints for identifying the pairing rule and writing code. A tool such as Form Timer for timed hiring tests illustrates how a screen can impose a fixed completion window. Use part of that window to test an input where sorting would change the fixed-pair answer. Before optimizing, say aloud whether the prompt fixes the pairs, asks for every index, or asks for one center.
Comments (0)