Shortest Distance in a Plane - Problem

You are given a database table Point2D containing coordinates of points on a 2D plane. Your task is to 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)²)

Table Schema:

Column NameType
xint
yint

The combination of (x, y) serves as the primary key, ensuring each point is unique.

Goal: Write a SQL query to return the shortest distance between any two distinct points, rounded to 2 decimal places.

Input & Output

example_1.sql — Basic Triangle
$ Input: Point2D table: | x | y | |---|---| |-1 |-1 | | 0 | 0 | |-1 |-2 |
Output: | shortest_distance | |------------------| | 1.00 |
💡 Note: The three points form a triangle. Distance from (-1,-1) to (0,0) is √2 ≈ 1.41, from (-1,-1) to (-1,-2) is 1.00, and from (0,0) to (-1,-2) is √5 ≈ 2.24. The minimum is 1.00.
example_2.sql — Square Formation
$ Input: Point2D table: | x | y | |---|---| | 0 | 0 | | 1 | 0 | | 0 | 1 | | 1 | 1 |
Output: | shortest_distance | |------------------| | 1.00 |
💡 Note: Four points forming a unit square. Adjacent sides have distance 1.00, while diagonals have distance √2 ≈ 1.41. The shortest distance is 1.00.
example_3.sql — Only Two Points
$ Input: Point2D table: | x | y | |---|---| | 3 | 4 | | 0 | 0 |
Output: | shortest_distance | |------------------| | 5.00 |
💡 Note: With only two points (3,4) and (0,0), the distance is √(3² + 4²) = √25 = 5.00. This is also the classic 3-4-5 right triangle.

Constraints

  • At least 2 points will be present in the table
  • All coordinates are integers
  • -100 ≤ x, y ≤ 100
  • Maximum 1000 points in the table
  • Each (x, y) combination is unique

Visualization

Tap to expand
XYA(-1,-1)B(0,0)C(-1,-2)1.411.00 ★2.24SQL Query ExecutionSELECT ROUND(MIN( SQRT(POWER(p2.x - p1.x, 2) + POWER(p2.y - p1.y, 2))FROM Point2D p1CROSS JOIN Point2D p2WHERE p1.x < p2.x OR (p1.x = p2.x AND p1.y < p2.y)Distance Calculations:A→B: √[(0-(-1))² + (0-(-1))²] = 1.41A→C: √[(-1-(-1))² + (-2-(-1))²] = 1.00B→C: √[(-1-0)² + (-2-0)²] = 2.24MIN(1.41, 1.00, 2.24) = 1.00Shortest Distance Problem
Understanding the Visualization
1
Plot all points
Visualize all points on a coordinate plane
2
Generate all pairs
Create lines between every possible pair of distinct points
3
Calculate distances
Apply Euclidean distance formula: √[(x₂-x₁)² + (y₂-y₁)²]
4
Find minimum
Identify the pair with the shortest distance
Key Takeaway
🎯 Key Insight: Use SQL's CROSS JOIN to generate all point pairs, then apply MIN() with the Euclidean distance formula to find the shortest distance efficiently in a single query.
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 25
26.8K Views
Medium Frequency
~15 min Avg. Time
892 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