Shortest Distance Problem
Description
LeetCode Problem 613.
Table point holds the x coordinate of some points on x-axis in a plane, which are all integers.
Write a query to find the shortest distance between two points in these points.
| x |
|-----|
| -1 |
| 0 |
| 2 |
The shortest distance is '1' obviously, which is from point '-1' to '0'. So the output is as below:
| shortest|
|---------|
| 1 |
Note: Every point is unique, which means there is no duplicates in table point.
Solution
Approach: Sort and Compare Neighbors
On a line, the closest pair of points is always two points that are next to each other in sorted order: any other pair has at least one point between them, so its distance is larger than the gap to that middle point. So we don't need to compare every pair of points.
- Sort the points by
xand useLAG(x) OVER (ORDER BY x)to get the previous point for each one. x - LAG(x)is the gap between neighbors. The smallest point has no previous point, so its gap isNULL.MIN(gap)gives the answer, andMINignores thatNULL.
This takes one sort instead of the n² rows of a self-join of every point with every other point. Since all points are distinct, every gap is positive.
The Pandas version sorts x, takes diff() between neighbors, and returns the smallest difference.
WITH gaps AS (
-- Distance from each point to the point just before it on the line.
SELECT x - LAG(x) OVER (ORDER BY x) AS gap
FROM point
)
SELECT MIN(gap) AS shortest
FROM gaps;