Given a list of integers points
that represent positions on a 1D line, find the shortest distance between any two different points. The distance between two points is the absolute difference of their values. You must not reuse the same point for both positions. The function should return the minimum such distance found.
points
of length at least 2, where each element is an integer representing a position on the line.
points
is an integer.The most straightforward way to solve this problem is to compare every pair of points and keep track of the minimum distance found. This brute-force approach checks all possible pairs, but quickly becomes inefficient as the number of points increases.
To optimize, notice that the minimum distance must exist between two numbers that are closest to each other on the line. If the points are sorted, the smallest gap will always be between two consecutive elements. This insight allows us to avoid checking every single pair and instead just look at adjacent elements in the sorted list.
In summary, the shift is from checking all pairs (brute-force) to sorting the array and checking only consecutive pairs (optimized).
Here’s a step-by-step breakdown of the optimized algorithm:
points
array in non-decreasing order. Sorting ensures that the closest points are next to each other.
This method is efficient because sorting takes O(n log n) time, and the single pass to check differences is O(n).
Input: points = [4, 2, 1, 3]
[1, 2, 3, 4]
2 - 1 = 1
3 - 2 = 1
4 - 3 = 1
1
The solution efficiently finds that the smallest distance between any two points is 1.
By recognizing that the minimum distance must be between consecutive elements after sorting, we reduce the problem from a quadratic to a near-linear solution. The key insight is that sorting brings the closest points together, allowing a single pass to find the answer efficiently. This approach is both elegant and practical, leveraging basic properties of numbers on a line.
def shortestDistance(points):
points.sort()
min_dist = float('inf')
for i in range(1, len(points)):
min_dist = min(min_dist, points[i] - points[i-1])
return min_dist
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
int shortestDistance(vector<int>& points) {
sort(points.begin(), points.end());
int min_dist = INT_MAX;
for (int i = 1; i < points.size(); ++i) {
min_dist = min(min_dist, points[i] - points[i-1]);
}
return min_dist;
}
import java.util.Arrays;
public class Solution {
public int shortestDistance(int[] points) {
Arrays.sort(points);
int minDist = Integer.MAX_VALUE;
for (int i = 1; i < points.length; i++) {
minDist = Math.min(minDist, points[i] - points[i-1]);
}
return minDist;
}
}
function shortestDistance(points) {
points.sort((a, b) => a - b);
let minDist = Infinity;
for (let i = 1; i < points.length; i++) {
minDist = Math.min(minDist, points[i] - points[i - 1]);
}
return minDist;
}