Hone logo
Hone
Problems

Shortest Distance in a Line

Imagine a set of points scattered along a one-dimensional line. Your task is to find the minimum distance between any two distinct points in this set. This is a fundamental problem in computational geometry and data analysis, with applications in clustering, data compression, and finding closest pairs of items.

Problem Description

Given an array of distinct numerical values representing points on a line, determine the smallest absolute difference between any two distinct points in the array.

Key Requirements:

  • You must find the shortest distance between any two different points.
  • The input will be an array of numbers.
  • The output should be a single numerical value representing the shortest distance.

Expected Behavior:

  • The function should iterate through the given points and calculate the distance between every unique pair of points.
  • It should keep track of the minimum distance found so far and return it at the end.

Edge Cases to Consider:

  • An array with fewer than two points: What should happen if there aren't enough points to form a pair?
  • All points being identical (though the problem statement specifies distinct values, it's good practice to consider such scenarios).

Examples

Example 1:

Input: [3, 6, 1, 8, 4]
Output: 1
Explanation: The distances between pairs are:
|3-6|=3, |3-1|=2, |3-8|=5, |3-4|=1
|6-1|=5, |6-8|=2, |6-4|=2
|1-8|=7, |1-4|=3
|8-4|=4
The smallest distance is 1 (between points 3 and 4).

Example 2:

Input: [10, 1, 5, 20]
Output: 4
Explanation: The distances are:
|10-1|=9, |10-5|=5, |10-20|=10
|1-5|=4, |1-20|=19
|5-20|=15
The smallest distance is 4 (between points 1 and 5).

Example 3: (Edge case for input size)

Input: [5]
Output: No pairs to compare. (Or an appropriate indicator for invalid input)
Explanation: There is only one point, so no distance can be calculated between two distinct points.

Constraints

  • The input array will contain at least 2 and at most 1000 elements.
  • Each element in the array will be an integer between -1000 and 1000, inclusive.
  • All elements in the input array will be distinct.
  • Your solution should aim for an efficient time complexity, ideally better than O(n^2).

Notes

  • The "distance" between two points on a line is the absolute difference of their values.
  • Consider how sorting the input array might simplify the problem.
  • If the input array has fewer than two elements, you should handle this gracefully, perhaps by returning a special value or raising an error, as it's impossible to find a distance between two points.
Loading editor...
plaintext