The Find Nearest Point That Has the Same X or Y Coordinate interview question is a grid-based proximity task. You are given your current location and an array of points. A point is "valid" if it shares the same x-coordinate or the same y-coordinate as your current location. Your goal is to find the index of the valid point with the smallest Manhattan distance to your location. If there's a tie, you return the smallest index.
Amazon and Google ask the Find Nearest Point coding problem to assess a candidate's basic loop handling and condition-checking skills. It evaluates if you can accurately implement a specific distance formula (Manhattan distance: ) and maintain state (the minimum distance found so far) while iterating through a list. It’s a classic Array interview pattern for entry-level roles.
This problem follows the Linear Scan pattern.
minDist to infinity and minIndex to -1.point[0] == x OR point[1] == y.minDist, update both minDist and minIndex.Location: (1, 1), Points: [[1, 2], [3, 1], [2, 3]]
[1, 2]: , same as location. Valid. Dist: . minDist = 1, minIndex = 0.[3, 1]: , same as location. Valid. Dist: . Not smaller than 1.[2, 3]: No shared coordinates. Invalid.
Result: 0.< comparison during the update).Always clarify the distance metric. While Manhattan distance is common in grid problems, interviewers might swap it for Euclidean or even Chebyshev distance to see if you are paying attention to the specific problem constraints.