This problem asks for the index of the array value that is closest to a target number. To measure closeness, you compare absolute differences like |nums[i] - target|.
If two values are equally close, you do not pick either one at random. You return the smaller index, so the earlier position wins the tie. If the array is empty, there is no valid answer, so you return -1.
For example, if nums = [2,5,9] and target = 7, both 5 and 9 are 2 units away, so the answer is index 1 because 5 appears first. If nums = [1,4,6,8] and target = 5, the closest value is 4 at index 1.
So the task is to compare every value's distance from the target and return the index of the closest one, using the smaller index whenever there is a tie.
Example Input & Output
The list is empty, so no index exists.
5 and 9 are equally close to 7; choose the smaller index 1.
The closest value to 5 is 4 at index 1.
Algorithm Flow

Solution Approach
A simple linear scan works well here. As we move through the array, we keep track of the best index seen so far and the smallest distance from the target.
The distance for one value is:
If this distance is smaller than the best one we have seen, we update our answer. If it is equal, we keep the earlier index, which means the current index only replaces the answer when its distance is strictly smaller.
We can start from the first element like this:
Then scan the rest:
Because we only update on a strictly smaller distance, ties automatically keep the earlier index.
If the array is empty, return -1 immediately. Otherwise, after the loop, bestIndex is the answer. This runs in O(n) time and uses O(1) extra space.
Best Answers
class Solution {
public int[] closest_value_index(int[] nums, double target) {
if (nums.length == 0) return new int[0];
double minDiff = Double.MAX_VALUE;
java.util.List<Integer> indices = new java.util.ArrayList<>();
for (int i = 0; i < nums.length; i++) {
double diff = Math.abs(nums[i] - target);
if (Math.abs(diff - minDiff) < 1e-9) {
indices.add(i);
} else if (diff < minDiff) {
minDiff = diff;
indices.clear();
indices.add(i);
}
}
int[] res = new int[indices.size()];
for (int i = 0; i < indices.size(); i++) res[i] = indices.get(i);
return res;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
