Find Nearest Point That Has the Same X or Y Coordinate - Problem

Imagine you're standing at a specific location (x, y) on a grid, and there are several points scattered around you. You can only move to points that are either directly horizontal (same x-coordinate) or directly vertical (same y-coordinate) from your current position - like a rook in chess!

Your task is to find the closest valid point using Manhattan distance (the sum of horizontal and vertical distances). If multiple points are equally close, choose the one with the smallest index.

Input: Your current coordinates (x, y) and an array points where each points[i] = [ai, bi] represents a point at (ai, bi).

Output: The index of the nearest valid point, or -1 if no valid points exist.

Manhattan Distance Formula: |x1 - x2| + |y1 - y2|

Input & Output

example_1.py โ€” Basic Case
$ Input: x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]]
โ€บ Output: 2
๐Ÿ’ก Note: Point at index 2 [2,4] shares y-coordinate 4 with distance |3-2| + |4-4| = 1, which is the minimum among all valid points.
example_2.py โ€” No Valid Points
$ Input: x = 3, y = 4, points = [[3,4]]
โ€บ Output: 0
๐Ÿ’ก Note: The only point [3,4] is at the exact same location, so distance is 0. This is valid since it shares both coordinates.
example_3.py โ€” No Valid Points
$ Input: x = 3, y = 4, points = [[2,3]]
โ€บ Output: -1
๐Ÿ’ก Note: Point [2,3] doesn't share x-coordinate (2โ‰ 3) or y-coordinate (3โ‰ 4), so no valid points exist.

Visualization

Tap to expand
YOU(6,3)P0(3,3) โœ“P1(6,2) โœ“P2(4,4) โœ—P3(8,3) โœ“dist: 3dist: 1 โญdist: 2Valid Points: Same Row or Columnโœ“ Valid points share x or y coordinate | โœ— Invalid points | โญ Closest valid point
Understanding the Visualization
1
Identify Your Position
You are at coordinates (x, y) on the grid
2
Scan All Points
Check each point to see if it shares your x or y coordinate
3
Calculate Distance
For valid points, compute Manhattan distance: |x1-x2| + |y1-y2|
4
Track the Best
Keep the closest point (or earliest index if tied)
5
Return Result
Output the index of the best valid point found
Key Takeaway
๐ŸŽฏ Key Insight: This is fundamentally a filtering and comparison problem - we must check every point for validity anyway, making a simple linear scan the optimal O(n) solution!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Must examine each point once to check validity and calculate distance

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using a few variables to track the best result

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค points.length โ‰ค 104
  • points[i].length == 2
  • 1 โ‰ค x, y, ai, bi โ‰ค 104
  • All coordinates are positive integers
Asked in
Amazon 45 Google 32 Microsoft 28 Meta 15
28.5K Views
Medium Frequency
~12 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