Shortest Distance in a Line - Problem
Find the Shortest Distance Between Any Two Points
You have a database table called Point that contains coordinates of points positioned on the X-axis. Your task is to find the shortest distance between any two points in this table.
Table Schema:
+-------------+------+ | Column Name | Type | +-------------+------+ | x | int | +-------------+------+
Where x is the primary key representing the position of a point on the X-axis.
Goal: Write a SQL query to return the minimum absolute difference between any two points.
Example: If you have points at positions [1, 3, 6, 10], the shortest distance would be between points 1 and 3, which gives us a distance of |3 - 1| = 2.
Input & Output
example_1.sql โ Basic Case
$
Input:
Point table:
+---+
| x |
+---+
| 1 |
| 3 |
| 6 |
|10 |
+---+
โบ
Output:
+-------------------+
| shortest_distance |
+-------------------+
| 2 |
+-------------------+
๐ก Note:
The distances between consecutive points are: |3-1|=2, |6-3|=3, |10-6|=4. The minimum is 2.
example_2.sql โ Two Points Only
$
Input:
Point table:
+---+
| x |
+---+
|-5 |
| 7 |
+---+
โบ
Output:
+-------------------+
| shortest_distance |
+-------------------+
| 12 |
+-------------------+
๐ก Note:
With only two points at -5 and 7, the distance is |7-(-5)| = 12.
example_3.sql โ Negative Coordinates
$
Input:
Point table:
+----+
| x |
+----+
|-10|
| -2|
| 0|
| 5|
+----+
โบ
Output:
+-------------------+
| shortest_distance |
+-------------------+
| 2 |
+-------------------+
๐ก Note:
Sorted points: [-10, -2, 0, 5]. Distances: |-2-(-10)|=8, |0-(-2)|=2, |5-0|=5. Minimum is 2.
Constraints
- 2 โค number of points โค 106
- -108 โค x โค 108
- All points have unique x-coordinates (primary key constraint)
- Result will always fit in a 32-bit signed integer
Visualization
Tap to expand
Understanding the Visualization
1
Plot points on number line
Visualize all points as positions on a straight line
2
Sort by position
Arrange points from left to right (smallest to largest x-coordinate)
3
Check adjacent distances
The closest pair must be neighbors when sorted
4
Return minimum
The smallest distance among all adjacent pairs is our answer
Key Takeaway
๐ฏ Key Insight: Once points are sorted by position, the shortest distance must be between consecutive points, reducing complexity from O(nยฒ) to O(n log n).
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code