Blueprints · Binary Search

Binary Search: Find the First Occurrence in a Sorted Array

One problem, three stages: make it work, make it fast, make it lean. Step through each stage in the visualizer, then run all three on a big input in the benchmark and watch the brute force overheat.

The real-world version

An audit log is sorted by timestamp, and many events share the same second. To replay everything from 09:00:00 you need the first event at that time, not just any event at that time.

The problem

Given a sorted array nums that may contain duplicates and a value x, return the index of the first element equal to x, or -1 if it isn't present.

nums = [1, 3, 3, 5, 5, 5, 8, 9, 12], x = 5  →  3

X-ray: watch it run

Benchmark: will the forge overheat?

Run all three stages on a large input in your browser and compare the work each one does.

In the interview

Write the loop invariant before the code: "the first x is always in [lo, hi)". It settles the < vs <=, mid vs mid − 1 questions that cause most binary-search bugs.