DDSA
Advertisement

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

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

Approach

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

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;
    }
}
Advertisement
Was this solution helpful?