Problem Description
Given a current location (x, y) and an array of points, find the index of a valid point that is the nearest in Manhattan distance. A point is considered valid if it shares the same x-coordinate or the same y-coordinate as (x, y). If multiple valid points have the same minimum Manhattan distance, return the one with the smallest index. If no valid point exists, return -1.
Key Insights
- A valid point must have either the same x-coordinate or the same y-coordinate as the current location.
- The Manhattan distance between two points (x1, y1) and (x2, y2) is computed as abs(x1 - x2) + abs(y1 - y2).
- Iterating over the points array and checking the validity condition allows you to update the smallest distance and corresponding index.
- Edge cases include when no valid points exist (return -1) and when the valid point is at the same location as (x, y).
Space and Time Complexity
Time Complexity: O(n) where n is the number of points in the list, since a single pass is used. Space Complexity: O(1) since only a few variables are used regardless of the input size.
Solution
We traverse the entire points array while checking each point for validity (same x or y coordinate). For valid points, we compute the Manhattan distance to (x, y) and track the minimum distance found so far along with its index. Finally, we return the index of the valid point with the smallest Manhattan distance; if none are valid, we return -1. The solution uses a simple iterative approach and basic arithmetic operations.