1409. Pairwise Manhattan Total

Medium3.5 points estimatedGeometrySortingPrefix SumMaths

A courier network has n pickup locations on a street grid, where the cost of travelling between two locations is the Manhattan distance |x1 - x2| + |y1 - y2|. The accountant wants the sum of this cost over every unordered pair of locations, each pair counted once.

Given points, a list of [x, y] pairs (duplicates are allowed and count as separate locations), return that total as a 64-bit integer. With one location the total is 0. Trying all pairs takes quadratic time and is too slow for the largest input. Notice that the x part and the y part are independent: sort the x values, then the k-th smallest value (counting from 0) contributes v_k * k - (sum of the k smaller sorted values). Do the same for the y values and add the two results. The total can be as large as about 2 * 10^14, so use 64-bit arithmetic. The intended solution runs in O(n log n) time and O(n) space.

Example 1

Input:
points = [[0,0],[2,3],[-1,1]]
Output:
12
Explanation:

The pair distances are 5 for (0,0)-(2,3), 2 for (0,0)-(-1,1) and 5 for (2,3)-(-1,1), a total of 12.

Example 2

Input:
points = [[4,4]]
Output:
0
Explanation:

A single location has no pairs, so the total is 0.

Constraints

1 ≤ points.length ≤ 105

-104 ≤ x, y ≤ 104

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

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

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…