3. Recursion, Searching & Sorting
Binary Search, bisect & Binary Search on Answer
Search sorted data in O(log n) without off-by-one bugs: master the lo/hi loop invariant, Python's stdlib bisect_left/bisect_right, and optimization via Binary Search on Answer.
- Write bug-free Binary Search with clear loop bounds and mid calculation
- Find insertion points and duplicates cleanly with Python's bisect module
- Apply Binary Search on Answer to monotonic optimization problems
Whenever you see "sorted array" or "find the minimum speed, capacity, or threshold such that...", you can chop the search space in half at every step—turning O(n) into O(log n) (just ~20 checks for 1,000,000 items, or ~30 checks for 1,000,000,000 items!).
Why It Matters: The Problem with Brute Force
Suppose Koko has piles of bananas [3, 6, 7, 11] and h = 8 hours, and wants the slowest integer eating speed k to finish on time:
- Brute force: Test
k = 1, thenk = 2,k = 3, ... up tomax(piles)(M). Each check sumslen(piles)(n) items →O(n · M)(ifM = 10⁹, that times out immediately!). - Binary Search on Answer: Because
can_finish(k)switches monotonically fromFalsetoTrue, binary searching[1, M]takesO(log M)checks →O(n log M)(~30 iterations even whenM = 10⁹!).
Pattern 1: Bug-Free Classic Binary Search (lo <= hi)
Binary search fails in interviews for one reason: inconsistent loop invariants (< vs <=, hi = mid vs hi = mid - 1). Pick one crystal-clear template per goal:
def binary_search(nums: list[int], target: int) -> int:
lo, hi = 0, len(nums) - 1 # Search inclusive range [lo..hi]
while lo <= hi:
mid = lo + (hi - lo) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
lo = mid + 1 # mid is ruled out; search [mid+1..hi]
else:
hi = mid - 1 # mid is ruled out; search [lo..mid-1]
return -1Step-by-Step Dry-Run Trace: binary_search([2, 5, 8, 12, 16, 23, 38], target=23)
Step 1: Check mid=3 (12 < 23)
mid value is 12, which is smaller than target 23 → discard left half and set lo = mid + 1 = 4.
| Step | lo | hi | mid | nums[mid] | Comparison | Next Range |
|---|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 12 | 12 < 23 → lo = 4 | [4..6] |
| 2 | 4 | 6 | 5 | 23 | 23 == 23 → Return 5 | Done! |
Now trace a missing target (target = 15):
lo=0, hi=6, mid=3 (12 < 15)→lo=4lo=4, hi=6, mid=5 (23 > 15)→hi=4lo=4, hi=4, mid=4 (16 > 15)→hi=3- Now
lo (4) > hi (3)→ loop exits cleanly and returns-1!
Edge Cases to Always Verify
- Empty array
[]:lo = 0,hi = -1,while 0 <= -1never runs → returns-1. - Single element
[5]:lo = 0, hi = 0runs once (mid = 0), checkingnums[0]. - Integer overflow note: In C++/Java,
(lo + hi) // 2can overflow 32-bit ints; Python ints have arbitrary precision, thoughlo + (hi - lo) // 2is great defensive habit.
Pattern 2: Python's Built-In bisect Module
Never hand-roll lower-bound or upper-bound search with duplicates when Python's C-speed bisect module already exists:
| Function | Meaning | When Target x Exists Multiple Times |
|---|---|---|
bisect_left(arr, x) | First index i where arr[i] >= x | Index of the first x |
bisect_right(arr, x) | First index i where arr[i] > x | One past the last x |
- Count occurrences of
xinO(log n):bisect_right(arr, x) - bisect_left(arr, x) - First index
>= x:i = bisect_left(arr, x)(checki < len(arr) and arr[i] == xfor exact match!).
Pattern 3: Binary Search on Answer (lo < hi Lower Bound)
When searching for the smallest valid value in [min_ans, max_ans] where feasible(x) is False, False, ..., False, True, True, ..., use the half-open/converging template (while lo < hi):
def min_eating_speed(piles: list[int], h: int) -> int:
def can_finish(speed: int) -> bool:
hours_needed = sum((p + speed - 1) // speed for p in piles)
return hours_needed <= h
lo, hi = 1, max(piles)
while lo < hi:
mid = (lo + hi) // 2
if can_finish(mid):
hi = mid # mid works! Keep mid as candidate, try slower
else:
lo = mid + 1 # mid is too slow; strictly exclude mid
return loDry-Run Trace: piles = [3, 6, 7, 11], h = 8
| Step | lo | hi | mid | hours_needed at mid | can_finish(mid) (<= 8)? | Action |
|---|---|---|---|---|---|---|
| 1 | 1 | 11 | 6 | 1 + 1 + 2 + 2 = 6 | True | hi = 6 |
| 2 | 1 | 6 | 3 | 1 + 2 + 3 + 4 = 10 | False | lo = 4 |
| 3 | 4 | 6 | 5 | 1 + 2 + 2 + 3 = 8 | True | hi = 5 |
| 4 | 4 | 5 | 4 | 1 + 2 + 2 + 3 = 8 | True | hi = 4 |
| End | 4 | 4 | — | lo == hi → Return 4 | — | Done! |
Notice why (p + speed - 1) // speed works: it computes integer ceiling division ceil(p / speed) without floating-point rounding!
When writing while lo < hi: with hi = mid, you MUST compute mid = (lo + hi) // 2 (floor) and set lo = mid + 1 in the else branch. If you instead write lo = mid with floor division when hi = lo + 1, mid == lo forever and the loop hangs! (For finding the maximum valid True, use mid = (lo + hi + 1) // 2 with lo = mid and hi = mid - 1.)
- Exact match (
return midor-1):lo, hi = 0, len(arr) - 1withwhile lo <= hi:, updatinglo = mid + 1andhi = mid - 1. - First
True/ lower bound:lo, hi = min_val, max_valwithwhile lo < hi:,if ok(mid): hi = mid else: lo = mid + 1, returninglo.
Try It Yourself in the Playground
Test classic binary_search, bisect_left/bisect_right, and Koko Eating Bananas (Binary Search on Answer) live below:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: How can you count how many times x appears in a sorted list nums in O(log n) time using bisect?
Quick Checkpoints
Roughly how many comparisons does Binary Search need to find an item in a sorted array of 1,000,000 elements?
What property must a feasible(x) helper satisfy in order to use Binary Search on Answer?
In a sorted list nums = [1, 3, 3, 3, 7], what does bisect_right(nums, 3) return?