#613
Easy Database Shortest distance in a line
Database
79.7% acceptance
Mar 31, 2026
344
41
No description available.
Solution
Pandas
Time O(n)
Space O(1)
# Table: Point
#
# +-------------+------+
# | Column Name | Type |
# +-------------+------+
# | x | int |
# +-------------+------+
# In SQL, x is the primary key column for this table.
# Each row of this table indicates the position of a point on the X-axis.
#
#
#
# Find the shortest distance between any two points from the Point table.
#
# The result format is in the following example.
#
# Example 1:
# Input:
# Point table:
# +----+
# | x |
# +----+
# | -1 |
# | 0 |
# | 2 |
# +----+
# Output:
# +----------+
# | shortest |
# +----------+
# | 1 |
# +----------+
# Explanation: The shortest distance is between points -1 and 0 which is |(-1) - 0| = 1.
import pandas as pd
def shortest_distance(point: pd.DataFrame) -> pd.DataFrame:
sorted_x = point['x'].sort_values().reset_index(drop=True)
diffs = sorted_x.diff().dropna().abs()
return pd.DataFrame({'shortest': [diffs.min()]})