Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

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

Array

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)
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;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.