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 Name | Type |
|---|---|
| x | int |
| y | int |
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
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.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code