Classic search
O(log n)Look at the middle. If the target is bigger, drop the left half, otherwise drop the right. Stop when you hit it or run out.
Reach for it when the array is sorted and you want one exact value.Go deeper: Where log n comes fromHalve the search space with every question. A million options take twenty guesses, as long as each answer tells you which half to throw away.
Look at the middle. If the target is bigger, drop the left half, otherwise drop the right. Stop when you hit it or run out.
Reach for it when the array is sorted and you want one exact value.Go deeper: Where log n comes fromTreat the range as a row of false then true. Narrow in on the first true, never stopping early on a match.
Reach for it when you need the first or last position, an insert point, or the first bad version.Go deeper: Where log n comes fromA sorted array cut and swapped still has one sorted half at every middle. Check which half it is, then ask if the target lives there.
Reach for it when the array was sorted once but now starts somewhere in the middle.Guess an answer, check it with a simple pass over the input, and halve the range of guesses depending on whether it worked.
Reach for it when checking a candidate is easy but finding the best one directly is not, and bigger candidates only get easier.Binary search on where to cut one array. The cut in the other array follows, and you move until both left sides sit below both right sides.
Reach for it when two sorted arrays must be split together, as in finding their combined median.Learn one shape, not five. Find the first value where a yes/no check turns true, and almost every binary search becomes a choice of range and check.
| # | Problem | Pattern | Difficulty | Solution |
|---|---|---|---|---|
| 1 | Binary Search | Classic search | Easy | Read |
| 2 | Search Insert Position | Boundary search | Easy | Read |
| 3 | First Bad Version | Boundary search | Easy | Read |
| 4 | Sqrt(x) | Search on the answer | Easy | Read |
| 5 | Find First and Last Position of Element in Sorted Array | Boundary search | Medium | Read |
| 6 | Search a 2D Matrix | Classic search | Medium | Read |
| 7 | Find Peak Element | Boundary search | Medium | Read |
| 8 | Find Minimum in Rotated Sorted Array | Rotated array | Medium | Read |
| 9 | Search in Rotated Sorted Array | Rotated array | Medium | Read |
| 10 | Koko Eating Bananas | Search on the answer | Medium | Read |
| 11 | Capacity To Ship Packages Within D Days | Search on the answer | Medium | Read |
| 12 | Split Array Largest Sum | Search on the answer | Hard | Read |
| 13 | Median of Two Sorted Arrays | Partition search | Hard | Read |