Find the Upper Bound of a Target in a Sorted Array

Implement upperBound

Given an array nums sorted in non-decreasing order (duplicates allowed) and an integer target, return its upper bound — the index of the first element that is strictly greater than target. If no element is greater, return nums.length. Together, lower bound and upper bound let you find every occurrence of a value in a sorted array in O(log n): upperBound - lowerBound is exactly the count.

Example 1:

Input: nums = [1,3,5,5,5,7,9], target = 5

Output: 5

Example 2:

Input: nums = [1,3,5,5,5,7,9], target = 4

Output: 2

Example 3:

Input: nums = [1,3,5,5,5,7,9], target = 9

Output: 7

+ 4 hidden test cases run on Submit.

Constraints:

  • 1 ≤ nums.length ≤ 10⁴
  • -10⁴ ≤ nums[i], target ≤ 10⁴
  • nums is sorted in non-decreasing order (duplicates are allowed)

nums =

[1, 3, 5, 5, 5, 7, 9]

target =

5