↶ Home

Binary Search Variants.

— Same skeleton, four return rules. Step through each mode and watch what changes.
INTERACTIVE · CLICK NEXT
LC 704 · 35 · 34
Target
5
Left
0
Mid
Right
STEP 0 OF —
Press Next → to start the search.
step 0 of —
mid (peek)
eliminated half
match
recorded best

The four modes.

All four use the same loop skeleton (while L <= R, halve based on comparison). What differs is the return rule on match and the final return when the loop exits.

ModeOn matchLoop exit returnUsed by
Exact match return mid return -1 LC 704 Binary Search
Insertion point return mid return left — the first slot ≥ target LC 35 Search Insert Position
First occurrence record ans=mid, then R = mid - 1 to keep narrowing left return ans (or -1 if never recorded) LC 34 Find First (1 of 2 passes)
Last occurrence record ans=mid, then L = mid + 1 to keep narrowing right return ans (or -1 if never recorded) LC 34 Find Last (2 of 2 passes)

The biased searches (first / last) are the one trick that catches everyone — don't return on match, record and keep narrowing. The recorded index is the answer if the loop later exhausts the range.