Upper bound finds the first element strictly greater than the target. Combined with lower bound, you can count occurrences.
Example: Upper bound of in is index (the ).
Counting occurrences: The count of is upperBound(5) - lowerBound(5) = 4 - 2 = 2.
function upperBound(arr, target):
low = 0
high = arr.length
while low < high:
mid = low + (high - low) / 2
if arr[mid] <= target:
low = mid + 1
else:
high = mid
return low
The only difference from lower bound: use <= instead of < when comparing.