Shortest Distance in a Line — LeetCode 613 Python Solution
EasyLeetCode PremiumDatabase
- Problem
- #613
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
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.