#1779
Easy Algorithms Find nearest point that has the same x or y coordinate
Array
69.9% acceptance
Feb 25, 2026
880
191
You are given two integers x and y representing your current location, and an array points. A point is valid if it shares the same x or y coordinate with your location.
Return the index of the valid point with the smallest Manhattan distance. If multiple, return the smallest index. If none, return -1.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn nearest_valid_point(x: i32, y: i32, points: Vec<Vec<i32>>) -> i32 {
let mut best_dist = i32::MAX;
let mut best_idx = -1i32;
for (i, p) in points.iter().enumerate() {
let (a, b) = (p[0], p[1]);
if a == x || b == y {
let dist = (a - x).abs() + (b - y).abs();
if dist < best_dist {
best_dist = dist;
best_idx = i as i32;
}
}
}
best_idx
}
}