EasyNo. 0613LeetCode Premium

Shortest Distance in a Line — LeetCode 613 Python Solution

Topics
Database
Reading time
2 min

The problem

Report the shortest distance between any two distinct points on the X axis, in a column named shortest. The Point table has one row per point: x (int, the primary key and the coordinate of the point on the X axis).

Example

Example
Point table:

| x  |
| -- |
| -4 |
| 1  |
| 3  |
| 10 |

Result:

| shortest |
| -------- |
| 2        |

Sorted, the gaps are 5, 2 and 7, so the closest pair is 1 and 3 at a distance of 2.

Python solution

PythonSolution
import pandas as pd

def shortest_distance(point: pd.DataFrame) -> pd.DataFrame:
    xs = point['x'].sort_values().to_numpy()
    gaps = xs[1:] - xs[:-1]
    return pd.DataFrame({'shortest': [int(gaps.min())]})

Complexity

Time
O(n log n)(typical)
Space · auxiliary
O(n)

Related problems

Related problems
No.ProblemDifficulty
0610Triangle JudgementEasy
0608Tree NodeMedium
0607Sales PersonEasy
0619Biggest Single NumberEasy
0620Not Boring MoviesEasy
0175Combine Two TablesEasy

Frequently asked questions

How hard is LeetCode 613. Shortest Distance in a Line?

LeetCode 613. Shortest Distance in a Line is rated Easy on LeetCode.

What topics does LeetCode 613. Shortest Distance in a Line cover?

LeetCode 613. Shortest Distance in a Line is tagged Database on LeetCode.

Is LeetCode 613. Shortest Distance in a Line a premium problem?

Yes. LeetCode 613. Shortest Distance in a Line is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.