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.

7 min readUpdated 2026-11-30
In This Lesson
  • 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, then k = 2, k = 3, ... up to max(piles) (M). Each check sums len(piles) (n) items → O(n · M) (if M = 10⁹, that times out immediately!).
  • Binary Search on Answer: Because can_finish(k) switches monotonically from False to True, binary searching [1, M] takes O(log M) checks → O(n log M) (~30 iterations even when M = 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:

python
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 -1

Step-by-Step Dry-Run Trace: binary_search([2, 5, 8, 12, 16, 23, 38], target=23)

Interactive Walkthrough: Binary Search (Target = 23)Step 1 / 2
lo
2
0
5
1
8
2
mid
12
3
16
4
23
5
38
6
hi
56
7

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.

Steplohimidnums[mid]ComparisonNext Range
10631212 < 23 → lo = 4[4..6]
24652323 == 23 → Return 5Done!

Now trace a missing target (target = 15):

  1. lo=0, hi=6, mid=3 (12 < 15) → lo=4
  2. lo=4, hi=6, mid=5 (23 > 15) → hi=4
  3. lo=4, hi=4, mid=4 (16 > 15) → hi=3
  4. Now lo (4) > hi (3) → loop exits cleanly and returns -1!

Edge Cases to Always Verify

  • Empty array []: lo = 0, hi = -1, while 0 <= -1 never runs → returns -1.
  • Single element [5]: lo = 0, hi = 0 runs once (mid = 0), checking nums[0].
  • Integer overflow note: In C++/Java, (lo + hi) // 2 can overflow 32-bit ints; Python ints have arbitrary precision, though lo + (hi - lo) // 2 is 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:

FunctionMeaningWhen Target x Exists Multiple Times
bisect_left(arr, x)First index i where arr[i] >= xIndex of the first x
bisect_right(arr, x)First index i where arr[i] > xOne past the last x
  • Count occurrences of x in O(log n): bisect_right(arr, x) - bisect_left(arr, x)
  • First index >= x: i = bisect_left(arr, x) (check i < len(arr) and arr[i] == x for 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):

python
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 lo

Dry-Run Trace: piles = [3, 6, 7, 11], h = 8

Steplohimidhours_needed at midcan_finish(mid) (<= 8)?Action
111161 + 1 + 2 + 2 = 6Truehi = 6
21631 + 2 + 3 + 4 = 10Falselo = 4
34651 + 2 + 2 + 3 = 8Truehi = 5
44541 + 2 + 2 + 3 = 8Truehi = 4
End44—lo == hi → Return 4—Done!

Notice why (p + speed - 1) // speed works: it computes integer ceiling division ceil(p / speed) without floating-point rounding!

The Infinite Loop Trap in Binary Search on Answer

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.)

Two Templates Cover 100% of Binary Search Problems
  1. Exact match (return mid or -1): lo, hi = 0, len(arr) - 1 with while lo <= hi:, updating lo = mid + 1 and hi = mid - 1.
  2. First True / lower bound: lo, hi = min_val, max_val with while lo < hi:, if ok(mid): hi = mid else: lo = mid + 1, returning lo.

Try It Yourself in the Playground

Test classic binary_search, bisect_left/bisect_right, and Koko Eating Bananas (Binary Search on Answer) live below:

Python 3Try It Live: Binary Search, bisect & Search-on-Answer
Output

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

Check Your Understanding

Roughly how many comparisons does Binary Search need to find an item in a sorted array of 1,000,000 elements?

Check Your Understanding

What property must a feasible(x) helper satisfy in order to use Binary Search on Answer?

Check Your Understanding

In a sorted list nums = [1, 3, 3, 3, 7], what does bisect_right(nums, 3) return?