Last Value Not Exceeding Target
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
All elements are greater than 2, so no valid index exists.
The last value not exceeding 4 is the second 4 at index 3.
The target is at least the largest element, so the last index is 4.
Algorithm Flow

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:
Then search:
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
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
