Find First and Last

Locate the range of equal elements.

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 55 in [1,3,5,5,5,7,9][1, 3, 5, 5, 5, 7, 9].

  • Lower bound of 55: index 22.
  • Upper bound of 55: index 55.
  • Range: [2,4][2, 4].

Time: O(logn)O(\log n) for two binary searches.