Unit 3 of 8 · about 5 hours · derive, implement

Binary search: intervals, bounds and feasibility predicates

Binary search fails in production through boundary bugs, not through asymptotics. One invariant derives every variant, and the same invariant searches answer spaces that are not arrays at all.

You'll be able to

  • Prove the binary-search loop invariant and derive safe boundary updates for lower-bound, upper-bound and first-true variants.
  • Implement exact-match, lower-bound, upper-bound and answer-space search from the invariant, with differential tests against bisect.
  • Turn a monotone feasibility predicate into lo/hi bounds with cost , and defend why monotonicity (not sortedness) is the requirement.

Covers

Binary-search interval conventions and terminationLower bound, upper bound and duplicate handlingBinary search on a monotone feasibility predicate
1

Read

In this order, only the parts listed

0 of 4 done

  1. Binary search: the canonical versionDSA Handbook - search, trees and heaps

    Pick the template from the question, not the input; Template A: exact-match on a closed interval; Template B: lower-bound on a half-open interval; Template C: predicate-driven leftmost; The off-by-one death zone

  2. Binary search variants: lower_bound, upper_bound, peaks, and rotated arraysDSA Handbook - search, trees and heaps

    Variant 1: lower_bound and upper_bound on duplicates; Variant 4: binary search on the answer; Pitfalls

    Skim Variants 2, 3 and 5 (rotated arrays, peaks, cross-array partition) for recognition only; they are not implemented here.

  3. Lecture Note 12: the dictionary lower boundAlgorithms

    Section 12.3 Information Theory

    Read only the dictionary lower-bound argument (Omega(log n) queries); the sorting sections belong to the merge-sort unit.

  4. Algorithmica: Binary SearchAlgorithmica - search and sorting performance

    Binary Search (The Bottleneck); Removing Branches

    Read for the branch-prediction and cache explanation only. Every speedup number there (2.5x to 3x branchless on small arrays, about 2x Eytzinger against std::lower_bound) is a C++ measurement with Clang 10 on Zen 2; do not transfer any crossover point to Python.

2

Focus on

  • Closed [lo,hi] pairs with while lo <= hi and hi=mid-1; half-open [lo,hi) pairs with while lo < hi and hi=mid. Mixing the pairs is the non-termination bug.
  • lower_bound keeps equality right with nums[mid] < target; upper_bound keeps equality left with nums[mid] <= target. Their difference counts duplicates.
  • Answer-space search is Template C with a monotone predicate: feasibility must hold above (or below) a threshold with no gaps. Cost is for predicate cost and width .
  • Algorithmica's C++ numbers explain why equal-asymptotic searches cross over (an unpredictable branch costs 10 to 15 cycles, a cache miss up to 300), but Python's interpreter overhead moves every crossover. Verify bounds against bisect, not against ported constants.
Common mistakes · 3
  • Returning lo for every template. The upper-bound twin and Template A need their own return values; derive each from the invariant instead of memorizing one.
  • Writing lo=mid or hi=mid in Template A after a miss. The closed interval needs mid+1 and mid-1 to shrink; the half-open forms are the ones that keep mid.
  • Searching on a predicate that is not monotone. Prove hours(k) is nonincreasing in (or your predicate's direction) before trusting the loop; a gap in feasibility silently returns a wrong answer.
3

Try it yourself

Closed-book, before checking anything

From a blank file, implement lower_bound, upper_bound and a first-true search on [lo,hi). On [1,2,2,2,3] with target 2, return 1 and 4. Reproduce Koko: piles [3,6,7,11] with h=8 must return 4. Run a Hypothesis differential test of both bounds against bisect_left and bisect_right on 300 sorted lists up to length 30.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Prove Template B terminates with lo at the lower bound.Answer

    Invariant: every index j < lo has nums[j] < target and every index k >= hi has nums[k] >= target. Each iteration replaces [lo,hi) with a strictly smaller interval that preserves the invariant, since mid sits strictly inside while lo < hi. The width reaches zero, so lo == hi, and the invariant says every index below lo is < target and every index from lo on is >= target (lo = n when none is), so lo is the lower bound.

  2. 2.On [1,2,2,2,3], what do exact-match search, lower_bound and upper_bound return for target 2, and why?Answer

    Exact match returns some index in {1,2,3}. lower_bound returns 1 because the strict comparison keeps equality right; upper_bound returns 4 because the non-strict comparison keeps equality left. The duplicate count is .

  3. 3.Why is binary search correct on the Koko predicate when speeds are not stored in an array?Answer

    hours(k) is nonincreasing in : a faster speed never needs more hours. That monotonicity is the only requirement; the loop searches the predicate, not a sorted array. Each probe scans piles, so the cost is .

  4. 4.A colleague ports Algorithmica's branchless binary search to Python expecting 2.5x. What do you tell them?Answer

    The 2.5x to 3x number is Algorithmica's C++ measurement (Clang 10, Zen 2) on small arrays. Python's per-iteration interpreter overhead dominates and removes the branch-prediction effect, so the constant does not transfer. Measure with timeit on the real workload instead.

5

Practice

  • LeetCode 875: Koko Eating Bananas

    Solve with a monotone hours predicate on [1, max(piles)]; example piles [3,6,7,11] with h=8 expects 4

    Attempt cold: state the predicate and its monotonicity before coding. After submitting, read the AlgoMaster write-up for Koko Eating Bananas (https://algomaster.io/learn/dsa/koko-eating-bananas).

  • LeetCode 34: Find First and Last Position of Element in Sorted Array

    Two bound searches; example inputs ([5,7,7,8,8,10], 8) expects [3,4] and ([5,7,7,8,8,10], 6) expects [-1,-1]

    Cover the empty array and the absent target without extra branches. After submitting, read the AlgoMaster write-up for Find First and Last Position of Element in Sorted Array (https://algomaster.io/learn/dsa/find-first-and-last-position-of-element-in-sorted-array).

You're done when

Your three searches match bisect on 300 random cases, Koko returns 4, and you can write any bound variant from its invariant without trial edits.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 7 more in the section
  • DSA Handbook - search, trees and heapsHandbook Academy · primary

    Study Part 2 Search and Sort, Part 5 Linked Lists, and Part 6 Trees and Heaps. Include canonical and answer-space binary search, comparison and linear-time sorts, quickselect, sentinels, cycles, heaps, BSTs, balanced-tree vocabulary, tries and segment trees.

  • Algorithmica - search and sorting performanceSergey Slotin · support

    Use the binary-search, sorting, branch prediction and cache chapters to explain why two algorithms with the same asymptotic bound cross over on real workloads.

  • AlgorithmsJeff Erickson · reference

    Use Chapter 1 (mergesort, quicksort, recursion trees and linear-time selection) when deriving merge, partition and selection algorithms, and lecture note 12 Lower Bounds for the comparison-sorting decision-tree argument. This is the proof reference when the handbook explanation is too brief.

Also in this section