Closest Value Index
You’re given a list of integers sorted in ascending order and a target value. In Closest Value Index, your mission is to find the index of the element whose value is closest to the target. Closeness is based on absolute difference. If two neighbors are tied in distance, select the lower index to break the tie.
The "secret sauce" here is Binary Search Comparison. Use binary search to find the insert position for the target, then compare the target's distance to the values at index and index-1. If the list is empty, return -1. This approach is lightning fast (O(log N)) and ensures you always find the best representative marker for the team's data. Mastering this boundary reasoning and tie-breaking logic is a professional necessity for high-performance analysis! Return the final single integer index that best matches the target’s location in the ordered data provided.
If sorting is part of the strategy, do it intentionally as a preprocessing step to simplify downstream logic such as merging, ordering, or comparison. After sorting, keep output semantics precise: preserve expected structure, avoid dropping valid entries, and ensure tied cases still follow deterministic order rules.
Examples
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

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 problem.
