Learning objectives
- Specify the difference between finding any match and finding the first insertion point.
- Use the half-open interval and the sorted-order guarantee to justify each update.
Learn
Binary search uses the fact that a sorted sequence arranges values in order. A comparison at the middle element can eliminate one part of the candidate interval. For a lower bound, seek the first index at which a value is at least the target. Use a half-open interval with a left comparison index and a right sentinel. An answer equal to the length means every element was smaller. For duplicates, equal values never justify skipping earlier positions without testing them.
The contract and invariant play different roles. The contract specifies the position the function should return. The invariant describes what must be true of the areas already ruled out. At initialization the left boundary is zero and the right boundary is the list length, so no real elements have been excluded. At a middle value smaller than the target, sorted order puts that element and every earlier one below the target. Otherwise the middle is an upper bound on the answer and stays eligible as the right boundary even when it is no longer in the undecided comparison interval. At termination the left and right edges agree. The excluded prefix and the remaining boundary identify the first eligible index.
Separate the cost of finding a position from the cost of acting on it. In an array with direct access by index, each comparison approximately halves the remaining interval. Inserting a new element into the middle of a Python list can still move many elements. A collection used mostly for lookup has a different workload from one with frequent insertions. Test the empty list, the first and last possible positions, repeated values, and a missing value between two present ones. These cases exercise different failures even when every test uses sorted input.
Failure-oriented laboratory: Binary-search boundaries and duplicate keys
An algorithm specification includes behavior for duplicate keys and absent values. Finding any matching element differs from finding the first position at which a key could be inserted. A lower-bound search maintains a half-open interval [lo, hi) and discards only positions that cannot be the first element greater than or equal to the target. Equality must move the upper boundary, not return an arbitrary midpoint.
An invariant explains correctness: all positions below lo contain values strictly less than the target, while all positions at or above hi are known not to be the answer's missing earlier candidates. Each iteration shortens the undecided interval. At termination lo equals hi, identifying the boundary, including the valid one-past-end result. Dereferencing that position requires a separate bounds check.
Performance claims must identify operations and representation. Binary search makes logarithmically many comparisons on a sorted random-access sequence, but inserting into a Python list still shifts elements linearly. Maintaining sorted data can dominate lookup cost. Compare an append-and-sort batch with repeated sorted insertions under a stated workload rather than advertising one asymptotic number for the whole application.
Explain the fixture
The positions are 0, 3 and 5. Returning a middle 2 answers membership but not the first-occurrence contract. Position 5 is a valid insertion boundary for 10 but is not a valid index to dereference. Empty input must return 0 without accessing an element.
Apply
Use the sorted list 2, 4, 4, 4, 9, with zero-based indexes and target 4. Start with left 0 and right 5. The middle index is 2, where the value is 4, so set the right edge to 2. With left 0 and right 2 the middle is 1, again 4, making the right edge 1. Now the middle is 0, with value 2, so move the left edge to 1. The ends agree at index 1, the first 4. A lookup for an exact match can separately check that the resulting index is in bounds and the value equals the target. That extra check matters when searching for 5, whose insertion point contains 9.
The adjustment from middle index zero to left index one is essential. Keeping zero when the target is greater can make the same comparison repeat without shrinking the interval.
Optional check
What lower bound should the same method return for target 12?
Show the explained answer
It should return 5, the length of the list. All five values are smaller, so there is no element to inspect at the returned position until the sequence changes.