Problem Description
Given an array of points on a 2D plane, each point represented as [x, y], the Manhattan distance between two points is defined as |x1 - x2| + |y1 - y2|. The task is to remove exactly one point such that the maximum Manhattan distance among all the remaining points is minimized. That is, for every possible removal, compute the maximum Manhattan distance between any pair of remaining points and return the minimum among those values.
Key Insights
- The Manhattan distance between points (x1, y1) and (x2, y2) can be expressed as max(|(x1+y1) - (x2+y2)|, |(x1-y1) - (x2-y2)|). This transformation helps reduce the problem to tracking extreme values.
- The maximum Manhattan distance among a set of points is determined by the range (difference between maximum and minimum) of either (x+y) or (x-y).
- Removing a point that currently defines an extreme is what may cause a reduction in the overall distance; hence, you only need to consider points that are at one or more of the extremes.
- Precompute sorted orders for both u = x+y and v = x-y coordinates so that if an extreme point is removed, the next extreme can be quickly determined.
- Use prefix and suffix ideas (or simply tracking the smallest and second smallest, largest and second largest) for both sets of transformed values.
Space and Time Complexity
Time Complexity: O(n log n) – due to sorting the transformed arrays. Space Complexity: O(n) – additional arrays and data structures for storing transformed values and indices.
Solution
The solution proceeds as follows:
- Transform every point into two values: u = x+y and v = x-y.
- Identify the overall extreme values: u_min, u_max, v_min, and v_max.
- Only candidate removals that can affect these extreme values need to be considered. These candidates are those points whose u or v value equals one of the overall extremes.
- Pre-sort the points (with indices stored) based on the u values and similarly for the v values.
- For each candidate point, simulate its removal by determining the new u_min and u_max (if the candidate was an extreme in u) and the new v_min and v_max (if it was an extreme in v).
- The new maximum Manhattan distance among the remaining points is the maximum of (new_u_max - new_u_min) and (new_v_max - new_v_min).
- Return the minimum such maximum distance among all candidate removals.
This approach ensures that while looping only through a handful of candidate points, we can compute the resulting maximum Manhattan distance quickly without rescanning the entire list for every removal.