Binary Search
Write off-by-one-free binary searches over sorted data and over monotonic answer spaces.
4 objectives 6 steps about 130 min
Check what you know
The lessons are coming later. The knowledge check is ready now.
This skill page is a public outline. Its lessons and knowledge check appear here as subject-matter experts approve them.
Learning objectives
- Implement exact-match, lower-bound and upper-bound binary search from a stated loop invariant, and match the results of the bisect module.
- Recognize a monotonic predicate in an optimization problem and binary-search the answer space, such as the minimum capacity that ships all packages within D days.
- Adapt binary search to rotated sorted arrays, sorted 2D matrices and real-valued answers with a stated precision.
- Binary-search structures that are not plain sorted arrays: a peak in an unsorted array, the k-th smallest element of two sorted arrays by partition, and the end of an unbounded sorted sequence by exponential search.
Lesson plan
6 steps, about 130 min · 0 of 5 lessons available so far
- Invariants That Prevent Off-by-One Bugs Concept · 20 min · coming later
- Lower Bound, Upper Bound and bisect Worked example · 20 min · coming later
- Searching the Answer, Not the Array Worked example · 25 min · coming later
- Lab: Rotated Arrays, Matrices and Real Numbers Lab · 25 min · coming later
- Peaks, Partitions and Unbounded Ranges Worked example · 25 min · coming later
- Check: Binary Search Variants Knowledge check · 8 questions
Practise it
Solve five variants (first and last occurrence, search in a rotated array, minimum shipping capacity, integer square root, first failing build) with one shared lower-bound template, passing tests that include duplicates and boundary values. Then find the median of two sorted lists of up to 10^6 values in O(log(min(m, n))) by partition search, checked against merging on random inputs.
References
Hard prerequisites
Unlocks
Nothing depends on this skill yet.
On these roadmaps
Progress and evidence for this skill are shared across all of them.