PU Shortest Distance in a Line

Jan 01, 1970

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.

Follow-up: What if all these points have an id and are arranged from the left most to the right most of x axis?

Solution 1:

# Write your MySQL query statement below
SELECT min(distance) as shortest
FROM (
    SELECT DISTINCT abs(p1.x - p2.x) as distance
    FROM point as p1, point as p2
    WHERE p1.x != p2.x
    )
    AS
    TMP

Solution 2:

# Write your MySQL query statement below
SELECT min(abs(p1.x - p2.x)) as shortest
FROM point as p1 
    JOIN point as p2
    ON p1.x <> p2.x

Solution 3:

# Write your MySQL query statement below
SELECT min(p1.x - p2.x) as shortest
FROM point as p1, point as p2
WHERE p1.x > p2.x

Summary:

  • nothing to say

LeetCode: 613. Shortest Distance in a Line