Code Logo

Last Value Not Exceeding Target

Published at05 Jan 2026
Easy 7 views
Like30

This problem asks for the last index in a sorted array whose value is less than or equal to the target. In other words, you want the rightmost position that still does not go over the target.

The answer is an index, not the value itself. If several numbers satisfy the rule, you must keep moving right until you find the final valid one. If every number is too large, then no position works and the answer should be -1.

For example, in [1,2,4,4,7] with target 4, the answer is 3 because the second 4 is the last value that is still allowed. In [3,5,6] with target 2, the answer is -1 because even the first value is already too big.

So the task is to find the farthest index to the right where nums[i] <= target, or return -1 if such an index does not exist.

Example Input & Output

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
Recommendation Algorithm Flow for Last Value Not Exceeding Target

Solution Approach

Because the array is sorted, binary search is a great fit. We do not need to inspect every element. We only need to keep narrowing down where the last valid position could be.

The main idea is the mirror image of finding a first valid index. Here, if nums[mid] <= target, then mid is a valid answer candidate, but there might be another valid index farther to the right.

We begin like this:

let left = 0;
let right = nums.length - 1;
let answer = -1;

Then search:

while (left <= right) {
  const mid = Math.floor((left + right) / 2);

  if (nums[mid] <= target) {
    answer = mid;
    left = mid + 1;
  } else {
    right = mid - 1;
  }
}

If nums[mid] <= target, we record mid and move right to look for a later valid index. If nums[mid] > target, then mid and everything after it are too large, so we move left.

When the loop ends, answer is the last index whose value does not exceed the target, or -1 if none exists. The time complexity is O(log n).

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