Closest Value Index
You are given a list of integers arranged in ascending order and a target value. Your task is to determine which element in the list is closest to the target and return its index. The notion of closeness is based on absolute difference: the element with the smallest distance from the target is considered closer. If two elements are tied in distance, choose the one that appears earlier in the list by index.
This problem encourages careful reasoning about how values are positioned along a number line. Consider the target as a point and the list elements as fixed markers. Your job is to identify the marker that most closely aligns with the target’s position. When the target falls between two neighboring values, you must resolve the tie consistently: select the lower index. If the target lies beyond the largest or smallest values, the closest element will be at one end of the list. If the list is empty, there is no candidate, and the correct result is -1.
Return a single integer representing the index within the list. Avoid modifying the list; its ascending order is already guaranteed. Focus on the relationship between neighboring values and how distances to the target change across the sequence. The final answer should reflect the index of the value that best represents the target’s location with respect to the ordered data, using the tie-break rule that favors the smaller index.
Example 1:
Input: nums = [1, 4, 6, 8], target = 5
Output: 1
Explanation: The closest value to 5 is 4 at index 1.
Example 2:
Input: nums = [2, 5, 9], target = 7
Output: 1
Explanation: 5 and 9 are equally close to 7; choose the smaller index 1.
Example 3:
Input: nums = [], target = 3
Output: -1
Explanation: The list is empty, so no index exists.
Related Problems
No related problems found
Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
