Binary Search: Binary search on sorted data and answer spaces
Goal: Learn the pattern first, then apply it to the 8 roadmap problems in this chapter.
When this pattern appears
A sorted order or a monotone feasible/not-feasible condition lets half the candidates be eliminated.
The reusable idea
Define the search interval and invariant before coding. For minimum feasible values, keep a feasible high endpoint.
A deliberate problem-solving routine
- Write the input and output in plain language. Identify whether order, duplicates, or mutation matter.
- Work a tiny example by hand; label the state you wish you had at each step.
- Choose the structure or invariant that stores that state.
- Establish a brute-force baseline, then show exactly which repeated work the pattern removes.
- State the invariant before the loop, after each iteration, and at termination.
- Test smallest, boundary, duplicate, and adversarial cases.
Watch the animated pattern
The diagram above this lesson animates the core state changes for this chapter. Use pause and step to predict what moves next. The same invariant should explain each application, even when the problem story changes.
Questions to ask yourself
What property changes only once as the candidate grows? Which half is impossible?
Common failure modes
Inclusive/exclusive bounds, integer overflow, and correct feasibility monotonicity.
Chapter problems from the workbook
- #31 · Binary Search — Day 18, Easy. Open problem ↗
- #32 · Find First and Last Position in Sorted Array — Day 18, Medium. Open problem ↗
- #33 · Search a 2D Matrix — Day 19, Medium. Open problem ↗
- #34 · Koko Eating Bananas — Day 19, Medium. Open problem ↗
- #35 · Find Minimum in Rotated Sorted Array — Day 20, Medium. Open problem ↗
- #36 · Search in Rotated Sorted Array — Day 20, Medium. Open problem ↗
- #37 · Time Based Key-Value Store — Day 22, Medium. Open problem ↗
- #38 · Median of Two Sorted Arrays — Day 22, Hard. Open problem ↗
Interview explanation
A concise explanation has four parts: the key observation, the maintained invariant, why each step preserves it, and the time/space complexity. Avoid naming a pattern as a substitute for proving the step is safe.