Python coding

First and last index of a value

Given a list nums sorted in non-decreasing order (values may repeat) and an integer target, return [first, last]: the first and the last index where target appears. If it does not appear, return [-1, -1].

Aim for O(log n), even when target fills most of the list.

  • find_range([5,7,7,8,8,10], 8) → [3,4]
  • find_range([5,7,7,8,8,10], 6) → [-1,-1]
  • find_range([], 0) → [-1,-1]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Don't search for target itself: search for a boundary in a half-open range [lo, hi), halving it each step.

Hint 2

Write one lower bound, the first index with nums[i] >= x. Then first is lower(target) and last is lower(target + 1) - 1.

Hint 3

Before answering, check first < len(nums) and nums[first] == target; otherwise the value is missing.

Solution and why it works
pythonO(log n) · O(1)
def find_range(nums: list[int], target: int) -> list[int]:
    def lower(x: int) -> int:
        lo, hi = 0, len(nums)
        while lo < hi:
            mid = (lo + hi) // 2
            if nums[mid] < x:
                lo = mid + 1
            else:
                hi = mid
        return lo

    first = lower(target)
    if first == len(nums) or nums[first] != target:
        return [-1, -1]
    return [first, lower(target + 1) - 1]

Both ends are boundaries of a monotonic predicate: first is the first index with nums[i] >= target, and last sits just before the first index with nums[i] >= target + 1. Two lower-bound searches stay O(log n). The trap is finding any match and then walking left and right: on [2, 2, 2, 2] that walk is O(n).

Related lab: Loops in motion