Loading…
Loading…
Charting your lesson…
Opening your lesson…
Binary Search Fundamentals
Lesson 5 of 7
6 steps•about 11 min•11 flashcards
Step 1/ 61 min
Binary search is the most powerful O(log n) idea in the toolkit and the most bug-prone to implement. Master the invariant and the boundary handling, and you unlock a whole family of "find the position" problems.
Core idea: on a sorted array, repeatedly halve the search interval by comparing the target to the middle element. Each step discards half the remaining elements, so the search finishes in O(log n) comparisons.
Step 2/ 61 min
lo, hi = 0, n-1
while lo <= hi:
mid = lo + (hi - lo) // 2 # avoids overflow
if a[mid] == target: return mid
elif a[mid] < target: lo = mid + 1
else: hi = mid - 1
return -1 # not found
O(log n) time, O(1) space. The loop invariant: the target, if present, is always within [lo, hi].
The real power is finding boundaries, not just exact hits:
a[i] >= target (leftmost insertion point).a[i] > target.upper − lower), and where to insert — all O(log n). Use lo < hi with hi = mid (not mid−1) for the "find leftmost" template.Most binary-search bugs are off-by-one. Fix a template and stick to it:
[lo, hi] with lo <= hi and mid ± 1 updates — for exact match.[lo, hi) with lo < hi and hi = mid — for lower/upper bound.mid = lo + (hi − lo)//2 to avoid integer overflow, and make sure the interval strictly shrinks each iteration to avoid infinite loops.Step 3/ 61 min
Find 7 in [1, 3, 5, 7, 9, 11]. lo=0, hi=5, mid=2 → a[2]=5 < 7 → lo=3. mid=(3+5)/2=4 → a[4]=9 > 7 → hi=3. mid=3 → a[3]=7 = target → return index 3. Three comparisons for six elements; doubling the array adds just one more step — that's O(log n).
Step 4/ 61 min
Step 5/ 61 min
mid = lo + (hi − lo)//2, never (lo + hi)//2, to prevent overflow in other languages.lo == mid with lo = mid loops forever.Writing mid = (lo + hi) // 2 and, in fixed-width languages, overflowing when lo + hi exceeds the integer max — or updating lo = mid (instead of mid + 1) so the interval never shrinks and the loop hangs. Use the overflow-safe midpoint and always move past mid.
Step 6/ 6· Worked examples1 min
Problem
Search for 23 in the sorted array [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] (indices 0–9) using binary search.
Try it on paper first.
Recall
Keep this
Usage: keep the loop invariant explicit to get the boundary conditions right.
Binary search finds a target in a sorted array in O(log n) by halving the search space each step. Beyond exact match, its real interview power is finding boundaries — the first/last occurrence, lower/upper bound — and getting the loop conditions exactly right is a notorious source of bugs.
Maintain a [lo, hi] window; compare the middle element to the target and discard half. Exact search: if arr[mid] == target return mid; else move lo or hi. For boundary searches (first element ≥ target = lower bound, first > target = upper bound), don't stop at the first match — keep shrinking toward the boundary. Compute mid as lo + (hi − lo) / 2 to avoid integer overflow.
| Task | Returns | Time |
|---|---|---|
| Exact search | index or −1 | O(log n) |
| Lower bound | first index ≥ target | O(log n) |
| Upper bound | first index > target | O(log n) |
| First/last occurrence | boundary of duplicates | O(log n) |
| Count of a value | upper − lower | O(log n) |
Search a sorted array, first/last position of a target, count occurrences, search-insert position, or sqrt/ceil via binary search. Interviewers scrutinise the loop bounds and boundary handling.
Binary search halves a sorted range for O(log n) exact or boundary queries (lower/upper bound, first/last occurrence). Use mid = lo + (hi − lo)/2, keep a consistent [lo, hi] invariant, and don't stop early when hunting a boundary.
You've read 0 of 6 steps
Now lock it in — questions straight after reading are what make it stick.