Python 1779.py
class Solution:
def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:
result = -1
best = +inf
for i, (px, py) in enumerate(points):
if px == x or py == y:
distance = abs(px - x) + abs(py - y)
if distance < best:
result = i
best = distance
return result
Difficulty
and has an acceptance rate of about 70% (100k+ submissions).
Typical patterns to solve this problem:
- Array
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of locating the nearest point that lies on the same horizontal or vertical line as a given reference coordinate ((x, y)). It returns the index of that point within the input list, or (-1) when no such point exists. The algorithm proceeds with a single linear scan, maintaining the best (smallest) Manhattan distance encountered among points that satisfy the alignment condition.
Initialization
At the start, two variables are prepared: result is set to (-1) to represent the “not found” state, and best is assigned the value +inf to act as a sentinel larger than any possible distance. This ensures that the first qualifying point will always replace the initial sentinel.
result = -1
best = +inf
Iteration and Filtering
The core loop enumerates the input list points, exposing both the index i and the coordinate pair (px, py). For each point, the algorithm checks whether the point shares either the same x-coordinate (px == x) or the same y-coordinate (py == y). This logical filter discards any point that is not aligned horizontally or vertically with the reference point, thereby reducing unnecessary work.
for i, (px, py) in enumerate(points):
if px == x or py == y:
# further processing
Distance Computation
When a point passes the alignment test, its Manhattan distance to ((x, y)) is computed as the sum of the absolute differences along each axis. The use of abs guarantees correct handling of both positive and negative coordinate values.
distance = abs(px - x) + abs(py - y)
Result Selection
If the computed distance is strictly smaller than the current best distance, the algorithm updates both result and best. The index i of the newly found closer point is stored, and best is set to the new minimal distance. Because the comparison uses a strict <, ties are resolved in favor of the earlier point in the list, preserving the required “lowest index” rule.
if distance < best:
result = i
best = distance
Edge Cases Handled
The code gracefully handles an empty points list: the loop body never executes, leaving result at its initial (-1) value, which correctly signals the absence of a valid point. When no point shares the same x or y coordinate with the reference, the conditional filter never passes, again resulting in (-1). The algorithm also correctly processes points with negative coordinates, as the absolute value operation neutralizes sign effects. In scenarios where multiple points have identical minimal distances, the strict < comparison ensures that the first such point (lowest index) remains selected, matching typical problem specifications. Extremely large coordinate values are accommodated because Python’s integer type can represent arbitrarily large numbers, and the sentinel +inf remains larger than any finite distance.
Performance Characteristics
The implementation achieves its goal with a single pass over the input list, performing a constant amount of work for each element: a couple of equality checks, an absolute-value calculation, and a simple comparison. By discarding non-aligned points early, it avoids unnecessary distance calculations, which contributes to a lean execution path. The use of +inf as an initial benchmark eliminates the need for separate handling of the first qualifying point, simplifying the update logic. Overall, the algorithm scales linearly with the number of points, delivering efficient performance for large inputs without additional data structures or auxiliary storage.
ELI5 - Simplified Explanation
Imagine you have a treasure map covered in dots, and you are standing at a specific spot marked with coordinates. Some of these dots are special because they are either straight across or straight up from where you are standing. The code starts by looking for these special dots one by one. It checks each dot to see if it lines up perfectly with your position. If it does, the code measures how far away that dot is by counting the steps between your spot and that point. It keeps track of the closest special dot it has found so far. Every time it finds a new dot that is even closer than the last one, it remembers the new spot instead. By the time it finishes looking at all the dots on the map, it knows exactly which one is the nearest one that lines up with you.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Java | |||||||||
| leetcode.ca | C++ | Python | Java | C | Go | Rust | TS | ||||
| Progiez | C++ | Python | Java | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Java | ||||||||||
| leetcode.ca | C, C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 973: K Closest Points to Origin
Solved On The Same Day
- problem 1991: Find the Middle Index in Array
- problem 2042: Check if Numbers Are Ascending in a Sentence
- problem 2062: Count Vowel Substrings of a String
- problem 1780: Check if Number is a Sum of Powers of Three
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality