Skip to content
BytePatterns

First And Last Occurrence

MediumSearching#binary-search#boundary-search~25m

Problem

A sorted list may hold a target value many times over. Report the first and last positions it occupies, as a pair, or a pair of -1 values when it is absent. The run of equal values can be long, so walking outwards from a hit is too slow.

Examples

Input:  nums = [5, 7, 7, 8, 8, 10], target = 8
Output: (3, 4)
Input:  nums = [5, 7, 7, 8, 8, 10], target = 6
Output: (-1, -1)
Why:    the value is absent, even though it sits inside the range
Input:  nums = [], target = 1
Output: (-1, -1)
Why:    edge case, an empty list has no positions at all

Hints

0 / 3

Stuck on the idea rather than the code? Binary Search Variants covers it.