Find Nearest Point That Has the Same X or Y Coordinate - Problem
You are given two integers, x and y, which represent your current location on a Cartesian grid: (x, y). You are also given an array points where each points[i] = [ai, bi] represents that a point exists at (ai, bi).
A point is valid if it shares the same x-coordinate or the same y-coordinate as your location.
Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location. If there are multiple, return the valid point with the smallest index. If there are no valid points, return -1.
The Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2).
Input & Output
Example 1 — Basic Case
$
Input:
x = 1, y = 2, points = [[1,3],[3,2],[2,2]]
›
Output:
0
💡 Note:
Point [1,3] shares x=1 with distance |1-1|+|3-2|=1. Point [3,2] shares y=2 with distance |3-1|+|2-2|=2. Point [2,2] shares y=2 with distance |2-1|+|2-2|=1. Points 0 and 2 both have minimum distance 1, but index 0 is smaller.
Example 2 — No Valid Points
$
Input:
x = 1, y = 1, points = [[2,3],[3,2]]
›
Output:
-1
💡 Note:
Point [2,3] doesn't share x=1 or y=1. Point [3,2] doesn't share x=1 or y=1. No valid points exist.
Example 3 — Exact Match
$
Input:
x = 1, y = 1, points = [[1,1],[2,1],[1,2]]
›
Output:
0
💡 Note:
Point [1,1] is exactly at our location with distance 0. Even though other points are valid, distance 0 is minimum possible.
Constraints
- 1 ≤ points.length ≤ 104
- points[i].length == 2
- -104 ≤ x, y, ai, bi ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input
Current position (1,2) and array of points [[1,3],[3,2],[2,2]]
2
Filter
Only consider points sharing x=1 or y=2 coordinate
3
Calculate
Find minimum Manhattan distance among valid points
Key Takeaway
🎯 Key Insight: Only points sharing the same x or y coordinate are valid candidates
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code