Command Palette

Search for a command to run...

Module 11

Binary Search

Halve the search space at every step: find positions in sorted data, handle rotated arrays, and search over answers instead of indexes.

Intermediate 4 lessons 9 problems ~55 min of lessons

Binary search needs only one thing: a question whose answer flips from "no" to "yes" (or the reverse) exactly once across the search space. Sorted arrays have that property, but so do many problems that never mention sorting, like "what is the smallest speed that finishes in time?".

The module is mostly about getting the details right, because binary search is famously easy to get almost right: the loop condition, how mid is computed, and which half to keep. One reliable template removes most of the bugs.

Best after: Arrays

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. The classic search, written carefully: loop condition, mid calculation, and half updates.

  2. The lower-bound template: the first index whose value is at least the target.

  3. Two boundary searches: lower bound for the first copy, upper bound minus one for the last.

  4. Binary search when sortedness is broken at one point: one half is always sorted, so decide using that half.

  5. Find the rotation point by comparing mid with the right end: the first-true template again.

  6. Treat a row-sorted matrix as one virtual sorted array: index i maps to row i / cols, column i % cols.

  7. Binary search on the answer: test a speed with a quick feasibility check and halve the range of speeds.

  8. A greedy feasibility check (fill each day until the next package won't fit) plus binary search on capacity.

  9. Binary search a partition of the smaller array so that everything on the left is ≤ everything on the right.