BudiBadu Logo

Closest Value Index

Array Easy 0 views
Like30

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

Example 1
Input
nums = [], target = 3
Output
-1
Explanation

The list is empty, so no index exists.

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 = [1, 4, 6, 8], target = 5
Output
1
Explanation

The closest value to 5 is 4 at index 1.

Algorithm Flow

Recommendation Algorithm Flow for Closest Value Index - Budibadu
Recommendation Algorithm Flow for Closest Value Index - Budibadu

Best Answers

java
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;
    }
}