Shortest Distance in a Line - Problem

Given a table Point with a single column x representing positions on the X-axis, find the shortest distance between any two points.

Each row contains an integer value representing the position of a point on the X-axis. You need to calculate the minimum absolute difference between any two distinct points.

Note: The result should be the minimum distance value as a single number.

Table Schema

Point
Column Name Type Description
x PK int Position of point on X-axis (primary key)
Primary Key: x
Note: Each row represents a unique point position on the X-axis

Input & Output

Example 1 — Basic Points
Input Table:
x
-1
0
2
Output:
shortest
1
💡 Note:

Points are at positions -1, 0, and 2. The distances are: |(-1)-0| = 1, |(-1)-2| = 3, |0-2| = 2. The shortest distance is 1 between points -1 and 0.

Example 2 — Adjacent Points
Input Table:
x
1
3
6
10
Output:
shortest
2
💡 Note:

Points at 1, 3, 6, 10. Distances: |1-3| = 2, |1-6| = 5, |1-10| = 9, |3-6| = 3, |3-10| = 7, |6-10| = 4. The shortest is 2 between points 1 and 3.

Example 3 — Two Points Only
Input Table:
x
5
8
Output:
shortest
3
💡 Note:

With only two points at positions 5 and 8, the distance is |5-8| = 3.

Constraints

  • 2 ≤ number of points ≤ 500
  • -10^8 ≤ x ≤ 10^8
  • All points have unique x coordinates

Visualization

Tap to expand
Shortest Distance Problem OverviewPoints on Line-102distance = 1distance = 2distance = 3Self JoinAll Pairs Comparisonp1.xp2.xdistance-101-123022Shortest Distance: MIN(1, 3, 2) = 1Result: 1
Understanding the Visualization
1
Input
Points on X-axis
2
Self Join
Create all point pairs
3
Calculate
Find minimum distance
Key Takeaway
🎯 Key Insight: Self-join with inequality condition efficiently compares all point pairs to find minimum distance
Asked in
Amazon 23 Facebook 18 Google 15
28.5K Views
Medium Frequency
~8 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen