Problem Statement

Find First and Last Position

You are given a sorted list of numbers (sorted means smallest to largest, in order) and a target number. Your job is to find where the target starts and where it ends in the list. Since the list can have repeats, the target might show up several times in a row. You return two index positions: the first spot where the target appears and the last spot. If the target is not in the list at all, you return [-1, -1]. The catch is speed: the solution must run in O(log n) time, which means we cannot just walk through every item one by one. The tool for that is binary search. Binary search is like guessing a number between 1 and 100 where each guess tells you "too high" or "too low," so you can throw away half the choices every time. We run it twice: once tuned to find the leftmost copy of the target, and once tuned to find the rightmost copy.

mediumBinary SearchBinary SearchTime: O(log n) · Space: O(1)

Signals to notice

find first and last position in sorted arraytwo binary searchesleft and right boundaries

Brute force first

Linear scan left to right for first, right to left for last. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

The key insight

Two binary searches: one finding the leftmost occurrence (left boundary), one finding the rightmost (right boundary). Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Trace it on nums=[5,7,7,8,8,10], target=8

LEFT search: lo=0 hi=5 result=-1
mid=2 nums[2]=7<8 -> lo=3
mid=4 nums[4]=8==8 -> result=4, hi=3 (go left)
mid=3 nums[3]=8==8 -> result=3, hi=2 (go left); lo>hi -> left=3
RIGHT search: lo=0 hi=5 result=-1; mid=2 nums[2]=7<8 -> lo=3
mid=4 nums[4]=8==8 -> result=4, lo=5 (go right)
mid=5 nums[5]=10>8 -> hi=4; lo>hi -> right=4
return [3, 4]

What must stay true

Left boundary search: when nums[mid] == target, keep searching left (right = mid - 1). Right boundary search: when nums[mid] == target, keep searching right (left = mid + 1). When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Shape of the loop

function findBound(isLeft):
  lo, hi, result = 0, n-1, -1
  while lo <= hi:
    mid = (lo + hi) / 2
    if nums[mid] == target: result = mid; if isLeft: hi=mid-1 else lo=mid+1
    elif nums[mid] < target: lo = mid+1
    else: hi = mid-1
  return result            # answer = [findBound(true), findBound(false)]

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Using one binary search and then scanning — that degrades to when many duplicates exist. Two separate binary searches guarantee. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Binary Search Pattern