#612
Medium Database Shortest distance in a plane
Database
61.0% acceptance
Mar 31, 2026
226
72
No description available.
Solution
Pandas
Time O(n)
Space O(1)
# Table: Point2D
#
# +-------------+------+
# | Column Name | Type |
# +-------------+------+
# | x | int |
# | y | int |
# +-------------+------+
# (x, y) is the primary key column (combination of columns with unique values) for this table.
# Each row of this table indicates the position of a point on the X-Y plane.
#
#
#
# The distance between two points p1(x1, y1) and p2(x2, y2) is sqrt((x2 - x1)2 + (y2 - y1)2).
#
# Write a solution to report the shortest distance between any two points from the Point2D table. Round the distance to two decimal points.
#
# The result format is in the following example.
#
# Example 1:
# Input:
# Point2D table:
# +----+----+
# | x | y |
# +----+----+
# | -1 | -1 |
# | 0 | 0 |
# | -1 | -2 |
# +----+----+
# Output:
# +----------+
# | shortest |
# +----------+
# | 1.00 |
# +----------+
# Explanation: The shortest distance is 1.00 from point (-1, -1) to (-1, 2).
import pandas as pd
def shortest_distance(point2_d: pd.DataFrame) -> pd.DataFrame:
merged = point2_d.merge(point2_d, how='cross', suffixes=('_1', '_2'))
merged = merged[(merged['x_1'] != merged['x_2']) | (merged['y_1'] != merged['y_2'])]
merged['dist'] = round(((merged['x_1'] - merged['x_2'])**2 + (merged['y_1'] - merged['y_2'])**2)**0.5, 2)
return pd.DataFrame({'shortest': [merged['dist'].min()]})