Shortest Distance in a Plane - Problem

You have a table Point2D that stores coordinates of points on a 2D plane. Each row represents a point with its (x, y) coordinates.

Your task: Find the shortest distance between any two points in the table.

The distance between two points p1(x1, y1) and p2(x2, y2) is calculated using the Euclidean distance formula: sqrt((x2 - x1)² + (y2 - y1)²)

Requirements:

  • Round the result to 2 decimal places
  • Return only the shortest distance value
  • Handle cases where multiple point pairs have the same minimum distance

Table Schema

Point2D
Column Name Type Description
x PK int X coordinate of the point
y PK int Y coordinate of the point
Primary Key: (x, y)
Note: The combination of (x, y) is unique for each point

Input & Output

Example 1 — Basic Point Distance
Input Table:
x y
-1 -1
0 0
-1 1
Output:
shortest
1.41
💡 Note:

We have three points: (-1,-1), (0,0), and (-1,1). The distances are:

  • (-1,-1) to (0,0): √[(0-(-1))² + (0-(-1))²] = √2 ≈ 1.41
  • (-1,-1) to (-1,1): √[(-1-(-1))² + (1-(-1))²] = √4 = 2.00
  • (0,0) to (-1,1): √[(-1-0)² + (1-0)²] = √2 ≈ 1.41

The minimum distance is 1.41.

Example 2 — Same Distance Points
Input Table:
x y
0 0
3 4
Output:
shortest
5
💡 Note:

With only two points (0,0) and (3,4), there's only one distance to calculate:

Distance = √[(3-0)² + (4-0)²] = √[9 + 16] = √25 = 5.00

Example 3 — Close Points
Input Table:
x y
0 0
1 0
0 1
2 2
Output:
shortest
1
💡 Note:

Multiple pairs have distance 1.00: (0,0) to (1,0) and (0,0) to (0,1). Both are horizontal/vertical distances of 1 unit, which is the minimum among all possible pairs.

Constraints

  • 2 ≤ number of points ≤ 500
  • -10^4 ≤ x, y ≤ 10^4
  • All points have distinct coordinates
  • At least one pair of points exists

Visualization

Tap to expand
Shortest Distance in a Plane INPUT Point2D Table x y -1 -1 0 0 -1 -2 P1(-1,-1) P2(0,0) P3(-1,-2) ALGORITHM STEPS 1 Self Join Table Compare each point with every other point 2 Filter Pairs Exclude same point: p1.x != p2.x OR p1.y != p2.y 3 Calculate Distance Euclidean formula: SQRT((x2-x1)^2 + (y2-y1)^2) 4 Find Minimum Use MIN() and ROUND() to 2 decimal places P1-P2: sqrt(1+1) = 1.41 P1-P3: sqrt(0+1) = 1.00 P2-P3: sqrt(1+4) = 2.24 FINAL RESULT shortest 1.00 Shortest Distance Pair: P1 P3 P1(-1,-1) to P3(-1,-2) Distance = 1.00 OK - Result Verified Key Insight: Use SQL SELF JOIN to compare all point pairs. The Euclidean distance formula calculates straight-line distance between two points. Filter out identical point comparisons and find MIN() for shortest path. TutorialsPoint - Shortest Distance in a Plane | Optimal Solution
Asked in
Amazon 15 Google 12 Microsoft 8
28.0K Views
Medium Frequency
~12 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen