This website contains ALL LeetCode **Premium** problems for
**FREE!!**.

All leaked interview problems are collected from Internet.

All leaked interview problems are collected from Internet.

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 |

`point`

.
b'

\n\n## Solution

\n

\n#### Approach: Using

\n\n\n\n

'
\n

`ABS()`

and `MIN()`

functions [Accepted]**Intuition**

Calculate the distances between each two points first, and then display the minimum one.

\n**Algorithm**

To get the distances of each two points, we need to join this table with itself and use `ABS()`

function since the distance is nonnegative.\nOne trick here is to add the condition in the join to avoid calculating the distance between a point with itself.

SELECT\n p1.x, p2.x, ABS(p1.x - p2.x) AS distance\nFROM\n point p1\n JOIN\n point p2 ON p1.x != p2.x\n;\n

\n\nNote: The columns p1.x, p2.x are only for demonstrating purpose, so they are not actually needed in the end.

\n

Taking the sample data for example, the output would be as below.

\n| x | x | distance |\n|----|----|----------|\n| 0 | -1 | 1 |\n| 2 | -1 | 3 |\n| -1 | 0 | 1 |\n| 2 | 0 | 2 |\n| -1 | 2 | 3 |\n| 0 | 2 | 2 |\n

At last, use `MIN()`

to select the smallest value in the *distance* column.

**MySQL**

SELECT\n MIN(ABS(p1.x - p2.x)) AS shortest\nFROM\n point p1\n JOIN\n point p2 ON p1.x != p2.x\n;\n