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 Calculation OverviewInput: Pointsxy-1-100-11Self-JoinCreate pairsp1 × p2DistanceFormulaOutput: Min Distanceshortest1.41Coordinate Plane Visualization(-1,-1)(0,0)(-1,1)1.412.00
Understanding the Visualization
1
Input
Point2D table with (x,y) coordinates
2
Self-Join
Create all unique point pairs
3
Calculate
Apply distance formula and find minimum
Key Takeaway
🎯 Key Insight: Use self-join with proper filtering to avoid duplicate pairs and apply Euclidean distance formula
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