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.
| Mode | On match | Loop exit return | Used 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.