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

Master LeetCode problem 1779 (Find Nearest Point That Has the Same X or Y Coordinate), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1779. Find Nearest Point That Has the Same X or Y Coordinate

Easy

Problem Explanation

Explanation

To solve this problem, we iterate through each point in the points array and calculate the Manhattan distance for each point. We keep track of the minimum distance and the index of the point with the minimum distance that shares the same x-coordinate or y-coordinate with the given location (x, y).

We initialize the minimum distance as infinity and the result index as -1. We then iterate through each point, calculate the Manhattan distance, and update the result index if the current point has a smaller Manhattan distance and shares the same x-coordinate or y-coordinate.

After iterating through all points, we return the result index as the answer.

  • Time complexity: O(n), where n is the number of points
  • Space complexity: O(1)

Solution Code

class Solution {
    public int nearestValidPoint(int x, int y, int[][] points) {
        int minDistance = Integer.MAX_VALUE;
        int resultIndex = -1;
        
        for (int i = 0; i < points.length; i++) {
            int px = points[i][0];
            int py = points[i][1];
            
            if (px == x || py == y) {
                int distance = Math.abs(px - x) + Math.abs(py - y);
                if (distance < minDistance) {
                    minDistance = distance;
                    resultIndex = i;
                }
            }
        }
        
        return resultIndex;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1779 (Find Nearest Point That Has the Same X or Y Coordinate)?

This page provides optimized solutions for LeetCode problem 1779 (Find Nearest Point That Has the Same X or Y Coordinate) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1779 (Find Nearest Point That Has the Same X or Y Coordinate)?

The time complexity for LeetCode 1779 (Find Nearest Point That Has the Same X or Y Coordinate) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1779 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1779 in Java, C++, or Python.

Back to LeetCode Solutions