Array Upper Bound Problem
Description
LeetCode Problem 2774.
Write code that enhances all arrays such that you can call the upperBound() method on any array and it will return the last index of a given target number. nums is a sorted ascending array of numbers that may contain duplicates. If the target number is not found in the array, return -1.
Example 1:
Input: nums = [3,4,5], target = 5
Output: 2
Explanation: Last index of target value is 2
Example 2:
Input: nums = [1,4,5], target = 2
Output: -1
Explanation: Because there is no digit 2 in the array, return -1.
Example 3:
Input: nums = [3,4,6,6,6,6,7], target = 6
Output: 5
Explanation: Last index of target value is 5
Constraints:
1 <= nums.length <= 10^4-10^4 <= nums[i], target <= 10^4numsis sorted in ascending order.
Follow up: Can you write an algorithm with O(log n) runtime complexity?
Solution
Approach: Binary search
The array is sorted, so binary search applies. Search for the first index whose value is strictly greater than target; that position is one past the last occurrence of target. Then look at the element just before it: if it equals target, its index is the answer, otherwise target is not in the array and the answer is -1.
Searching for "first element greater than target" (rather than "equal to target") is what makes the duplicates case work: the search keeps moving right across equal values instead of stopping at an arbitrary one. A one-line alternative is this.lastIndexOf(target), but that is linear.
Complexity: Time O(log n), space O(1).
/**
* @param {number} target
* @return {number}
*/
Array.prototype.upperBound = function (target) {
let lo = 0;
let hi = this.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (this[mid] > target) {
hi = mid;
} else {
lo = mid + 1;
}
}
return lo > 0 && this[lo - 1] === target ? lo - 1 : -1;
};