Shortest Distance to a Point on a Line
Imagine you're designing a robotic arm that needs to precisely position itself along a straight line. Given a set of points on that line and a target point, you need to determine the shortest distance from the target point to any of the given points. This problem is fundamental in robotics, geometry, and various optimization scenarios.
Problem Description
You are given a list of points representing locations on a one-dimensional line (a number line) and a target point. Your task is to find the minimum absolute distance between the target point and any point in the list. The points in the list are assumed to be distinct.
What needs to be achieved: Calculate the absolute difference between the target point and each point in the input list. Determine the smallest of these absolute differences.
Key requirements:
- The input will be a list (or array) of numbers representing the points on the line.
- The input will also include a single number representing the target point.
- You must return a single number representing the shortest distance.
Expected behavior: The function should return the minimum absolute distance. If the input list is empty, return infinity (or a very large number representing an unreachable distance).
Edge cases to consider:
- Empty input list.
- Target point coinciding with one of the points in the list (distance should be 0).
- Large distances between points and the target.
- Negative coordinates.
Examples
Example 1:
Input: [1, 5, 10, 15]
Target: 7
Output: 2
Explanation: The distances from the target (7) to each point are |1-7|=6, |5-7|=2, |10-7|=3, |15-7|=8. The minimum distance is 2.
Example 2:
Input: [-2, 0, 3]
Target: 1
Output: 1
Explanation: The distances are |-2-1|=3, |0-1|=1, |3-1|=2. The minimum distance is 1.
Example 3:
Input: [2, 4, 6, 8]
Target: 2
Output: 0
Explanation: The target point coincides with one of the points in the list, so the minimum distance is 0.
Example 4:
Input: []
Target: 5
Output: Infinity (or a very large number, e.g., 1000000)
Explanation: The input list is empty, so there are no points to calculate distances from.
Constraints
- The input list will contain between 0 and 1000 points.
- Each point in the list and the target point will be integers.
- The absolute value of each point and the target point will be less than 10000.
- The solution should ideally have a time complexity of O(n), where n is the number of points in the list.
Notes
Consider iterating through the list of points and calculating the absolute distance to the target point for each point. Keep track of the minimum distance found so far. You can use the built-in absolute value function of your chosen language. Remember to handle the edge case of an empty input list. Sorting the list first could be an option, but it's not required and might not be the most efficient approach.