Minimize Manhattan Distances Problem
Description
LeetCode Problem 3102.
You are given an array points representing integer coordinates of some points on a 2D plane, where points[i] = [x_i, y_i].
The distance between two points is defined as their Manhattan distance.
Return the minimum possible value for maximum distance between any two points by removing exactly one point.
Example 1:
Input: points = [[3,10],[5,15],[10,2],[4,4]]
Output: 12
Explanation:
The maximum distance after removing each point is the following:
- After removing the 0^th point the maximum distance is between points (5, 15) and (10, 2), which is |5 - 10| + |15 - 2| = 18.
- After removing the 1^st point the maximum distance is between points (3, 10) and (10, 2), which is |3 - 10| + |10 - 2| = 15.
- After removing the 2^nd point the maximum distance is between points (5, 15) and (4, 4), which is |5 - 4| + |15 - 4| = 12.
- After removing the 3^rd point the maximum distance is between points (5, 15) and (10, 2), which is |5 - 10| + |15 - 2| = 18.
12 is the minimum possible maximum distance between any two points after removing exactly one point.
Example 2:
Input: points = [[1,1],[1,1],[1,1]]
Output: 0
Explanation:
Removing any of the points results in the maximum distance between any two points of 0.
Constraints:
3 <= points.length <= 10^5points[i].length == 21 <= points[i][0], points[i][1] <= 10^8
Solution
Approach: Rotate Coordinates
The Manhattan distance |x1 - x2| + |y1 - y2| equals the larger of |(x1 + y1) - (x2 + y2)| and |(x1 - y1) - (x2 - y2)|. So the maximum distance over a set of points is the larger of two ranges: max - min of x + y, and max - min of x - y.
For each point we remove it and compute those two ranges over the rest; the answer is the smallest result. A pair of ordered multisets (one for x + y, one for x - y) does this in O(log n) per point. Since only a point holding one of the four extreme values can change a range, it is also enough to try just those few points and scan the rest.
Complexity: O(n log n) time and O(n) space with ordered sets (O(n) time when trying only the extreme points).
class Solution:
def minimumDistance(self, points: List[List[int]]) -> int:
a = [x + y for x, y in points]
b = [x - y for x, y in points]
cand = set()
for arr in (a, b):
cand.add(arr.index(max(arr)))
cand.add(arr.index(min(arr)))
ans = float("inf")
for r in cand:
ra = a[:r] + a[r + 1:]
rb = b[:r] + b[r + 1:]
ans = min(ans, max(max(ra) - min(ra), max(rb) - min(rb)))
return ans