#1779
Find Nearest Point That Has the Same X or Y Coordinate
EasyArrayHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
This approach is similar to the brute force method but focuses on reducing unnecessary calculations. By maintaining a single pass through the points and directly calculating distances only for valid points, we ensure efficiency.
⚙️
Algorithm
5 steps- 1Step 1: Initialize variables for minimum distance and index.
- 2Step 2: Loop through the points array.
- 3Step 3: For each point, check if it shares the x or y coordinate with the current location.
- 4Step 4: If valid, calculate the Manhattan distance and update the minimum distance and index accordingly.
- 5Step 5: Return the index of the closest valid point or -1 if none found.
solution.py10 lines
1def nearestValidPoint(x, y, points):
2 min_distance = float('inf')
3 min_index = -1
4 for i, (a, b) in enumerate(points):
5 if a == x or b == y:
6 distance = abs(x - a) + abs(y - b)
7 if distance < min_distance or (distance == min_distance and i < min_index):
8 min_distance = distance
9 min_index = i
10 return min_indexℹ
Complexity note: The time complexity remains O(n) as we still iterate through the points array once. The space complexity is O(1) because we only use a few variables to track the minimum distance and index.
- 1Valid points are those that share either the x or y coordinate with the current location.
- 2Manhattan distance is calculated as the sum of the absolute differences of the coordinates.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.