Lesson 9 of 40Core patterns
Binary Search
Halve the search space each step to find values, boundaries and even answers in O(log n), without off-by-one bugs.
Binary search finds an item among a billion sorted ones in about 30 steps. The idea takes a minute to understand, and the details take practice: it is famous for off-by-one bugs, and interviewers know it. Beyond sorted arrays, the same halving idea answers "what is the smallest speed that works?" questions, which is where it really shines.
The halving idea
Think of guessing a number from 1 to 100 with "higher" or "lower" hints. You guess 50, then 25 or 75, and so on. Each guess throws away half of what is left. That is binary search: compare against the middle of the remaining range and keep only the half that can still contain the answer.
It needs one thing: the data must be sorted (or more generally, ordered so that one comparison tells you which half to keep).
The range is all 10 items. mid = (0 + 9) // 2 = 4, value 16. 16 is less than 23, so the answer is to the right.
Each step halves the range, so n items take about log₂ n steps: O(log n) time and O(1) space.
The exact template
Here is the classic version for "find the index of target, or -1". Memorise this shape exactly.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.The discipline that prevents off-by-one bugs: decide what lo and hi mean, and keep that meaning true. Here, the answer (if it exists) is always inside [lo, hi], both ends included. So:
- The loop runs while that range is non-empty:
lo <= hi. - When you rule out
mid, exclude it:mid + 1ormid - 1. Writinglo = midhere can loop forever.
while lo <= hi: but updates with lo = mid instead of lo = mid + 1. With nums = [1, 3] and target = 3, what happens?Binary Search
Given a list nums sorted in ascending order with no repeated values, and a number target, return the index of target, or -1 if it is not in the list. Your solution must run in O(log n) time.
nums = [-1, 0, 3, 5, 9, 12], target = 9 → 4
nums = [-1, 0, 3, 5, 9, 12], target = 2 → -1
nums = [5], target = 5 → 0Constraints
1 <= nums.length <= 10^4-10^4 <= nums[i], target <= 10^4- All values in
numsare unique. numsis sorted in ascending order.
Searching for a boundary
Many questions are not "is it there?" but "where does it start?". Picture the array as a row of answers to a yes/no question, like nums[i] >= target. On sorted data it looks like F F F T T T. You want the first T.
This is the second template. Now hi starts at len(nums) (meaning "no T found, the answer is past the end") and the range is [lo, hi).
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.| Template | Range meaning | Loop | On "too small" | On "big enough" | Use for |
|---|---|---|---|---|---|
| Exact match | [lo, hi] inclusive | lo <= hi | lo = mid + 1 | hi = mid - 1 | find a value or -1 |
| First true | [lo, hi) half-open | lo < hi | lo = mid + 1 | hi = mid | boundaries, minimum that works |
hi = mid is safe in the second template because mid is always strictly less than hi when lo < hi, so the range still shrinks.
Python ships the boundary search in the standard library: bisect.bisect_left(nums, x) is exactly first_true above, and bisect.bisect_right(nums, x) is the first index with nums[i] > x. JavaScript has no built-in equivalent, so you write the loop.
What does this print?
import bisect nums = [1, 2, 2, 2, 5] print(bisect.bisect_left(nums, 2), bisect.bisect_right(nums, 2))
Search insert position
nums is sorted ascending with no duplicates. Return the index of target if it is present. If not, return the index where it would be inserted to keep the list sorted. Aim for O(log n).
nums = [1, 3, 5, 6], target = 5 → 2
nums = [1, 3, 5, 6], target = 2 → 1
nums = [1, 3, 5, 6], target = 7 → 4Binary search on the answer
Here is the leap. You do not need an array at all. You need a range of possible answers and a yes/no check that flips once.
Koko eats bananas from piles [3, 6, 7, 11] and has h = 8 hours. At speed k she eats up to k bananas from one pile per hour. What is the slowest speed that finishes in time? Speeds go from 1 to 11 (the biggest pile). A faster speed never makes things worse, so "finishes in time" looks like F F F T T T ... across speeds. Find the first T.
Try speed 6: 6 hours, which fits in 8. Maybe a slower speed works too, so keep 6 and look left.
The check costs O(n) (one pass over the piles), and you run it log(max pile) times, so the total is O(n log m) where m is the largest pile. The general recipe:
- Find the smallest and largest possible answer.
- Write
works(x)that returns True when x is good enough, and make sure it flips only once. - Run the first-true template over that range.
Order the steps of binary search on the answer.
- Tap the steps below in the right order.
Koko Eating Bananas
There are piles of bananas, piles[i] in pile i, and h hours until the guards return. Each hour Koko picks one pile and eats up to k bananas from it. If the pile has fewer than k left, she finishes it and waits out the rest of that hour. Return the smallest whole-number speed k that lets her eat every banana within h hours.
piles = [3, 6, 7, 11], h = 8 → 4
piles = [30, 11, 23, 4, 20], h = 5 → 30
piles = [30, 11, 23, 4, 20], h = 6 → 23A pile of p bananas takes ceil(p / k) hours.
Constraints
1 <= piles.length <= 10^4piles.length <= h <= 10^91 <= piles[i] <= 10^9
Rotated sorted arrays
A sorted array that has been rotated, like [4, 5, 6, 7, 0, 1, 2], is still searchable in O(log n). The key fact: when you split at mid, at least one half is properly sorted. Compare nums[mid] with nums[hi]:
- If
nums[mid] > nums[hi], the drop (the minimum) is somewhere to the right ofmid. - Otherwise the right half is sorted, and the minimum is at
midor to its left.
def find_min(nums):
lo, hi = 0, len(nums) - 1
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] > nums[hi]:
lo = mid + 1 # the drop is to the right of mid
else:
hi = mid # mid could be the minimum
return nums[lo]To search for a target, find which half is sorted, check whether the target lies inside that half's range, and keep that half or the other one. Practice both with the find-min-rotated and search-rotated problems.
Common mistakes
- Mixing the templates:
lo < hiwithhi = mid - 1, orlo <= hiwithhi = mid. Pick one meaning for the range and follow it. - Forgetting the data must be sorted (or that
works(x)must flip only once). - Overflow in
(lo + hi) / 2in languages with fixed-size integers. Python integers do not overflow, and JS numbers are safe up to 2⁵³, butlo + (hi - lo) // 2is the habit worth showing. - Wrong bounds on the answer range, such as starting Koko at speed 0 (division by zero) or ending below the biggest pile.
- binary search
- Repeatedly compare with the middle and keep the half that can still hold the answer. O(log n).
- invariant
- What
loandhimean, kept true every iteration, such as "the answer is in [lo, hi)". - first true
- The boundary template: find the first index or value where a monotonic yes/no check becomes true.
- binary search on the answer
- Search over possible answers (speeds, capacities) using a check function instead of an array.
- bisect_left
- Python's built-in first-index-at-or-after search on a sorted list.