Courses / DSA Patterns for Working Engineers / Chapter 10
Module 4 · Binary search, subsets, greedy, backtracking and DP · Chapter 10 of 39
Modified Binary Search: Bounds, Rotations and Searching the Answer
Builds on The Coding Interview: How the Round Runs and How to Prepare. Next up: Subsets: Every Subset, Permutation and Combination.
Part 1 · Introduction to binary search
One template for every search
Looking up a name in a sorted list, or one timestamp in a day of logs, is far quicker by halving than by reading. Binary search is simple to describe and easy to get wrong at the edges.
Binary search finds a position in sorted data by looking at the middle and throwing away the half that cannot hold the answer. Each step halves the candidates, so n items need about log2 n steps: 20 for 10 lakh items and 30 for 100 crore. Most bugs in it come from off-by-one choices: whether the range includes its last cell, whether to move to mid or mid + 1, and whether the loop ends on < or <=.
This chapter removes those choices by using one template for every problem. A predicate is a yes-or-no question about an index. It is monotone when it is false for every index up to some point and true from there on, as in false, false, false, true, true. The template finds the first index where a monotone predicate is true. Every problem in the chapter turns into choosing the predicate.
| Question about a sorted list | Predicate on index i | Answer |
|---|---|---|