EasyNo. 1779

Find Nearest Point That Has the Same X or Y Coordinate — LeetCode 1779 Python Solution

Topics
Array
Reading time
2 min

The 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).

Example

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.

Python solution

PythonSolution
class Solution:
    def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:
        ans, mi = -1, inf
        for i, (a, b) in enumerate(points):
            if a == x or b == y:
                d = abs(a - x) + abs(b - y)
                if mi > d:
                    ans, mi = i, d
        return ans

Complexity

Time
O(n)
Space · auxiliary
O(1) to O(n)

Related problems

Related problems
No.ProblemDifficulty
0057Insert IntervalMedium
0228Summary RangesEasy
0485Max Consecutive OnesEasy
0665Non-decreasing ArrayMedium
0674Longest Continuous Increasing SubsequenceEasy
0699Falling SquaresHard

Frequently asked questions

How hard is LeetCode 1779. Find Nearest Point That Has the Same X or Y Coordinate?

LeetCode 1779. Find Nearest Point That Has the Same X or Y Coordinate is rated Easy on LeetCode.

What topics does LeetCode 1779. Find Nearest Point That Has the Same X or Y Coordinate cover?

LeetCode 1779. Find Nearest Point That Has the Same X or Y Coordinate is tagged Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.