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 in a Line INPUT X -1 0 2 Point Table x (integer) -1 0 2 Input Values: Points: [-1, 0, 2] ALGORITHM STEPS 1 Sort Points ORDER BY x ASC -1 0 2 2 Self Join Compare adjacent pairs 3 Calculate Distances |x2 - x1| for each pair |0 - (-1)| = 1 |2 - 0| = 2 |2 - (-1)| = 3 4 Find Minimum MIN(1, 2, 3) = 1 SELECT MIN(ABS(p1.x - p2.x)) FROM Point p1, Point p2 FINAL RESULT Shortest Distance Found -1 0 2 Distance = 1 OUTPUT 1 Minimum distance between points -1 and 0 OK - Verified Key Insight: Sorting first ensures adjacent elements have minimum differences. The optimal solution uses self-join with p1.x < p2.x condition to compare distinct pairs. Time complexity: O(n^2) for self-join, but O(n log n) with sorting optimization by only comparing consecutive points. TutorialsPoint - Shortest Distance in a Line | Optimal Solution
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