problemeasyalgorithmsleetcode-1779leetcode 1779leetcode1779

Find Nearest Point That Has the Same X or Y Coordinate

EasyUpdated: Jul 31, 2025
Practice on:

Problem

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] = [ai, bi] represents that a point exists at (ai, bi). 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 index. If there are no valid points, return -1.

The Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2).

Examples

Example 1:

Input:
x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]]
Output:
 2
Explanation: Of all the points, only [3,1], [2,4] and [4,4] are valid. Of the valid points, [2,4] and [4,4] have the smallest Manhattan distance from your current location, with a distance of 1. [2,4] has the smallest index, so return 2.

Example 2:

Input:
x = 3, y = 4, points = [[3,4]]
Output:
 0
Explanation: The answer is allowed to be on the same location as your current location.

Example 3:

Input:
x = 3, y = 4, points = [[2,3]]
Output:
 -1
Explanation: There are no valid points.

Solution

Method 1 – Linear Scan with Manhattan Distance

Intuition

We want to find the valid point (same x or y coordinate) with the smallest Manhattan distance to (x, y). We can check each point, compute the distance if valid, and keep track of the minimum.

Approach

  1. Initialize minDist to infinity and ans to -1.
  2. For each point, if it shares x or y with (x, y), compute its Manhattan distance.
  3. If the distance is less than minDist, update minDist and ans with the current index.
  4. Return ans after checking all points.

Code

C++
class Solution {
public:
    int nearestValidPoint(int x, int y, vector<vector<int>>& points) {
        int ans = -1, minDist = INT_MAX;
        for (int i = 0; i < points.size(); ++i) {
            if (points[i][0] == x || points[i][1] == y) {
                int d = abs(points[i][0] - x) + abs(points[i][1] - y);
                if (d < minDist) {
                    minDist = d;
                    ans = i;
                }
            }
        }
        return ans;
    }
};
Go
func nearestValidPoint(x int, y int, points [][]int) int {
    ans, minDist := -1, 1<<31-1
    for i, p := range points {
        if p[0] == x || p[1] == y {
            d := abs(p[0]-x) + abs(p[1]-y)
            if d < minDist {
                minDist = d
                ans = i
            }
        }
    }
    return ans
}
func abs(a int) int { if a < 0 { return -a }; return a }
Java
class Solution {
    public int nearestValidPoint(int x, int y, int[][] points) {
        int ans = -1, minDist = Integer.MAX_VALUE;
        for (int i = 0; i < points.length; i++) {
            if (points[i][0] == x || points[i][1] == y) {
                int d = Math.abs(points[i][0] - x) + Math.abs(points[i][1] - y);
                if (d < minDist) {
                    minDist = d;
                    ans = i;
                }
            }
        }
        return ans;
    }
}
Kotlin
class Solution {
    fun nearestValidPoint(x: Int, y: Int, points: Array<IntArray>): Int {
        var ans = -1
        var minDist = Int.MAX_VALUE
        for (i in points.indices) {
            if (points[i][0] == x || points[i][1] == y) {
                val d = Math.abs(points[i][0] - x) + Math.abs(points[i][1] - y)
                if (d < minDist) {
                    minDist = d
                    ans = i
                }
            }
        }
        return ans
    }
}
Python
class Solution:
    def nearestValidPoint(self, x: int, y: int, points: list[list[int]]) -> int:
        ans, minDist = -1, float('inf')
        for i, (a, b) in enumerate(points):
            if a == x or b == y:
                d = abs(a - x) + abs(b - y)
                if d < minDist:
                    minDist = d
                    ans = i
        return ans
Rust
impl Solution {
    pub fn nearest_valid_point(x: i32, y: i32, points: Vec<Vec<i32>>) -> i32 {
        let mut ans = -1;
        let mut min_dist = i32::MAX;
        for (i, p) in points.iter().enumerate() {
            if p[0] == x || p[1] == y {
                let d = (p[0] - x).abs() + (p[1] - y).abs();
                if d < min_dist {
                    min_dist = d;
                    ans = i as i32;
                }
            }
        }
        ans
    }
}
TypeScript
class Solution {
    nearestValidPoint(x: number, y: number, points: number[][]): number {
        let ans = -1, minDist = Number.MAX_SAFE_INTEGER;
        for (let i = 0; i < points.length; i++) {
            if (points[i][0] === x || points[i][1] === y) {
                let d = Math.abs(points[i][0] - x) + Math.abs(points[i][1] - y);
                if (d < minDist) {
                    minDist = d;
                    ans = i;
                }
            }
        }
        return ans;
    }
}

Complexity

  • ⏰ Time complexity: O(n), where n is the number of points.
  • 🧺 Space complexity: O(1), only constant extra space is used.

Comments