Using lower bound and upper bound together, you can find the first and last occurrence of a value.
Problem: Find the starting and ending position of a target in a sorted array.
Solution:
function searchRange(arr, target):
first = lowerBound(arr, target)
if first == arr.length or arr[first] != target:
return [-1, -1]
last = upperBound(arr, target) - 1
return [first, last]
Example: Find range of in .
- Lower bound of : index .
- Upper bound of : index .
- Range: .
Time: for two binary searches.