Skip to main content
Back to problems
#2774
Easy JavaScript

Array upper bound

82.2% acceptance
Mar 31, 2026
23
2
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.

Solution

TypeScript
Time O(n)
Space O(1)
LeetCode
solution.ts
interface Array<T> {
  upperBound(target: number): number;
}

Array.prototype.upperBound = function (target): number {
  let lo = 0,
  hi = this.length - 1,
  result = -1;
  while (lo <= hi) {
  const mid = (lo + hi) >> 1;
  if (this[mid] === target) {
    result = mid;
    lo = mid + 1;
  } else if (this[mid] < target) {
    lo = mid + 1;
  } else {
    hi = mid - 1;
  }
  }
  return result;
};

// [3,4,5].upperBound(5); // 2
// [1,4,5].upperBound(2); // -1
// [3,4,6,6,6,6,7].upperBound(6) // 5