mediumBinary SearchBinary Search

Find First and Last Position

mediumTime: 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.

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.

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