BudiBadu Logo

Last Value Not Exceeding Target

Array Easy 5 views
Like30

You’re given a list of integers sorted in ascending order and a target value. In Last Value Not Exceeding Target, your task is to find the furthest right index where the value is still less than or equal to that target. This position represents the boundary where the sequence transitions from acceptable values to those that surpass the limit.

The "secret sauce" here is Boundary Binary Search. Since the list is sorted, you can find this "tipping point" in O(log N) time! Look for the largest index i such that nums[i] <= target. If multiple values equal the target, return the index of the last occurrence among them. If the list is empty or the target is smaller than the first element, return -1. This approach is the gold standard for efficient boundary detection in large datasets! Return the single integer index to help the team identify the sequence limits accurately. Precision is key!

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

All elements are greater than 2, so no valid index exists.

Example 2
Input
nums = [1, 2, 4, 4, 7], target = 4
Output
3
Explanation

The last value not exceeding 4 is the second 4 at index 3.

Example 3
Input
nums = [2, 3, 3, 3, 9], target = 10
Output
4
Explanation

The target is at least the largest element, so the last index is 4.

Algorithm Flow

Recommendation Algorithm Flow for Last Value Not Exceeding Target - Budibadu
Recommendation Algorithm Flow for Last Value Not Exceeding Target - Budibadu

Best Answers

java
class Solution {
    public int find_last_not_exceeding(Object nums, Object target) {
        int[] arr = (int[]) nums;
        int t = (int) target;
        int result = -1;
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] <= t) {
                result = mid;
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return result;
    }
}