EasyNo. 0613LeetCode Premium
Shortest Distance in a Line — LeetCode 613 Python Solution
- Topics
- Database
- Reading time
- 2 min
- Source
- leetcode.com
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
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
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
| No. | Problem | Difficulty |
|---|---|---|
| 0610 | Triangle Judgement | Easy |
| 0608 | Tree Node | Medium |
| 0607 | Sales Person | Easy |
| 0619 | Biggest Single Number | Easy |
| 0620 | Not Boring Movies | Easy |
| 0175 | Combine Two Tables | Easy |
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.