Find Nearest Point That Has the Same X or Y Coordinate - Complete Solution Guide
Find Nearest Point That Has the Same X or Y Coordinate is LeetCode problem 1779, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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] = [a i , b i ] represents that a point exists at (a i , b i ) . 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 i
Detailed Explanation
The problem asks you to find the index of the nearest point in a given list that shares the same x or y coordinate as your current location (x, y). The "nearest" point is determined by the Manhattan distance (|x1 - x2| + |y1 - y2|). If multiple points have the same minimum Manhattan distance, return the point with the smallest index. If no valid point exists, return -1.
Solution Approach
The solution uses a single loop to iterate through all points. For each point, it checks if it's valid (shares the same x or y coordinate). If valid, it calculates the Manhattan distance. It maintains a minimum distance and corresponding index. The index of the point with the minimum distance is returned. If no valid points are found, -1 is returned.
Step-by-Step Algorithm
- Initialize `min_dist` to infinity and `ans` to -1 (representing no valid point found).
- Iterate through each point `(a, b)` in the `points` list using its index `i`.
- Check if the point is valid: `a == x || b == y`.
- If the point is valid, calculate the Manhattan distance: `dist = abs(x - a) + abs(y - b)`.
- If `dist < min_dist`, update `min_dist` to `dist` and `ans` to `i`.
- After iterating through all points, return `ans`.
Key Insights
- The problem requires iterating through the points list and checking the validity of each point based on shared x or y coordinates.
- Manhattan distance is used to determine proximity, which is simply the sum of absolute differences in x and y coordinates.
- The algorithm needs to track both the minimum Manhattan distance and the index of the point achieving that minimum distance. The index is crucial because we need to return the index of the point, not the point itself.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Topics
This problem involves: Array.
Companies
Asked at: DoorDash.