Leetcode Problem 1779. Find Nearest Point That Has the Same X or Y Coordinate

1779. Find Nearest Point That Has the Same X or Y Coordinate

Leetcode Solutions

Iterative Minimum Distance Search

  1. Initialize variables to store the minimum distance (minDistance) and the index of the closest valid point (closestIndex), setting them to Infinity and -1 respectively.
  2. Loop through the array of points.
    • For each point, check if it is valid by comparing its x or y coordinate with the current location's x or y coordinate.
    • If the point is valid, calculate the Manhattan distance to the current location.
    • If this distance is less than minDistance, update minDistance and closestIndex with the current distance and index.
    • If the distance is equal to minDistance, update closestIndex only if the current index is smaller than closestIndex.
  3. After the loop, check if closestIndex is still -1, which means no valid point was found, and return -1.
  4. Otherwise, return closestIndex as the index of the closest valid point.
UML Thumbnail

Brute Force Search with Early Termination

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...