DDSA Solutions

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

Time: O(n)
Space: O(1)

Problem Overview

Find Nearest Point That Has the Same X or Y Coordinate (Unknown) asks you to solve a structured algorithmic task. This is a common Array pattern in coding interviews. Linear scan; filter points sharing x or y with query; return index of minimum Manhattan distance.

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

Approach

Linear scan; filter points sharing x or y with query; return index of minimum Manhattan distance.

Related patterns: Array

1779.cs
C#
// Approach: Linear scan; filter points sharing x or y with query; return index of minimum Manhattan distance.
// Time: O(n) Space: O(1)

public class Solution
{
    public int NearestValidPoint(int x, int y, int[][] points)
    {
        int ans = -1;
        int minDist = int.MaxValue;

        for (int i = 0; i < points.Length; ++i)
        {
            int dx = x - points[i][0];
            int dy = y - points[i][1];
            if (dx == 0 || dy == 0)
            {
                int dist = Math.Abs(dx) + Math.Abs(dy);
                if (dist < minDist)
                {
                    minDist = dist;
                    ans = i;
                }
            }
        }

        return ans;
    }
}
Was this solution helpful?

Related Problems