Minimize Manhattan Distances

Convert (x,y) to rotated (x+y, x-y) so Manhattan becomes Chebyshev — track top-2 extremes to handle "remove one point".

Hard
Time O(n log n) Space O(n)
LeetCode
8 min read
geometry math ordered-set

Problem#

Given points, the “distance” of the set is the maximum Manhattan distance between any two. Remove exactly one point to minimize this distance and return the new value.

Examples#

  • [[3,10],[5,15],[10,2],[4,4]]12.
  • [[1,1],[1,1],[1,1]]0.

Constraints#

  • 3 <= points.length <= 10^5.

Approach#

In rotated coords (u,v) = (x+y, x-y), Manhattan distance equals Chebyshev = max(|du|, |dv|). The max distance is max(maxU - minU, maxV - minV). We need top-2 max and bottom-2 min of u and v so removing any point lets us fall back to the secondary extremes.

Solution#

Minimize Manhattan Distances
class Solution {
public:
int minimumDistance(vector<vector<int>>& points) {
int n = points.size();
multiset<int> us, vs;
for (auto& p : points) {
us.insert(p[0] + p[1]);
vs.insert(p[0] - p[1]);
}
int ans = INT_MAX;
for (auto& p : points) {
int u = p[0] + p[1], v = p[0] - p[1];
us.erase(us.find(u));
vs.erase(vs.find(v));
int d = max(*us.rbegin() - *us.begin(), *vs.rbegin() - *vs.begin());
ans = min(ans, d);
us.insert(u);
vs.insert(v);
}
return ans;
}
};

Editorial#

The 45-degree rotation (u,v) = (x+y, x-y) turns L1 into L∞ — a textbook trick. Multisets let us remove a point’s contribution in O(log n) and re-query the new min/max instantly. Constant-factor tighter solutions exist (precompute top-2 extremes), but the multiset version is robust and easy to get right.

Complexity#

  • Time: O(n log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.