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
Find Nearest Valid Point INPUT 0 1 2 3 2 3 You 0 1 2 x = 1, y = 2 points = [ [1,3], // index 0 [3,2], // index 1 [2,2] // index 2 ] ALGORITHM STEPS 1 Check Point 0: (1,3) x=1 matches! Valid Dist = |1-1|+|2-3| = 1 2 Check Point 1: (3,2) y=2 matches! Valid Dist = |1-3|+|2-2| = 2 3 Check Point 2: (2,2) y=2 matches! Valid Dist = |1-2|+|2-2| = 1 4 Compare Results Min dist = 1 Points 0 and 2 tie Distance Comparison idx 0: dist=1 BEST idx 1: dist=2 idx 2: dist=1 same but larger idx FINAL RESULT You 0 Point 0 at (1,3) Manhattan dist = 1 Output: 0 Verification: Point 0 shares x=1 Smallest index with minimum distance Key Insight: Early Termination Optimization A point is valid only if it shares the same x OR y coordinate. Manhattan distance simplifies when coordinates match: if x matches, dist = |y1-y2|; if y matches, dist = |x1-x2|. When multiple points have the same minimum distance, return the smallest index (earliest in array). TutorialsPoint - Find Nearest Point That Has the Same X or Y Coordinate | Early Termination Optimization
Asked in
Amazon 15 Microsoft 8
24.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen