Program to find nearest point that has the same x or y coordinate using Python

Finding the nearest point that shares the same x or y coordinate is a common problem in computational geometry. We need to find a valid point (one that shares either x or y coordinate) with the smallest Manhattan distance from our current location.

The Manhattan distance between two points (a, b) and (p, q) is calculated as |a - p| + |b - q|. When multiple points have the same minimum distance, we return the one with the smallest index.

Problem Statement

Given a list of points and a current location, find the index of the valid point with the smallest Manhattan distance. A valid point must share either the same x-coordinate or y-coordinate as our current point.

Example

If we have points [(1,2), (3,1), (3,4), (2,3), (4,4)] and current location (2,4), the valid points are:

  • (3,4) at index 2 - shares y-coordinate 4, distance = |2-3| + |4-4| = 1

  • (2,3) at index 3 - shares x-coordinate 2, distance = |2-2| + |4-3| = 1

Both have distance 1, but index 2 is smaller, so we return 2.

Algorithm Steps

Here's the step-by-step approach:

  • Extract x and y coordinates from current point

  • Initialize variables to track the best index and smallest distance

  • Iterate through all points and check if they share x or y coordinate

  • Calculate Manhattan distance for valid points

  • Update the result if we find a smaller distance or same distance with smaller index

Implementation

def solve(pts, pt):
    x, y = pt
    idx = -1
    smallest = float("inf")
    
    for i, p in enumerate(pts):
        # Check if point shares x or y coordinate
        if p[0] == x or p[1] == y:
            # Calculate Manhattan distance
            dist = abs(x - p[0]) + abs(y - p[1])
            
            # Update if we found a smaller distance
            if dist < smallest:
                idx = i
                smallest = dist
            # If same distance, choose smaller index
            elif dist == smallest and i < idx:
                idx = i
    
    return idx

# Test the function
pts = [(1,2), (3,1), (3,4), (2,3), (4,4)]
pt = (2,4)
result = solve(pts, pt)
print(f"Nearest valid point is at index: {result}")
print(f"Point coordinates: {pts[result]}")
Nearest valid point is at index: 2
Point coordinates: (3, 4)

How It Works

The algorithm uses enumerate() to get both index and point values efficiently. For each point, we check if it's valid (shares x or y coordinate), then calculate the Manhattan distance. We keep track of the smallest distance found and update our result when we find a better point.

Key Points

  • Valid Point: Must share either x-coordinate or y-coordinate with current location

  • Manhattan Distance: Sum of absolute differences in x and y coordinates

  • Tie-breaking: When distances are equal, choose the point with smaller index

  • Time Complexity: O(n) where n is the number of points

Alternative Test Case

# Test with different data
pts2 = [(0,0), (1,1), (2,0), (0,2), (3,3)]
pt2 = (0,1)

result2 = solve(pts2, pt2)
print(f"For points {pts2} and location {pt2}:")
print(f"Nearest valid point is at index: {result2}")
print(f"Point coordinates: {pts2[result2]}")
print(f"Distance: {abs(pt2[0] - pts2[result2][0]) + abs(pt2[1] - pts2[result2][1])}")
For points [(0, 0), (1, 1), (2, 0), (0, 2), (3, 3)] and location (0, 1):
Nearest valid point is at index: 0
Point coordinates: (0, 0)
Distance: 1

Conclusion

This algorithm efficiently finds the nearest valid point by checking coordinate sharing and calculating Manhattan distances. The solution handles tie-breaking by preferring smaller indices, making it reliable for competitive programming scenarios.

Updated on: 2026-03-25T20:50:41+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements