Explain an algorithm with a cost and an invariant
Use a small search problem to connect correctness with growing input size.
What you’ll learn
- State what a loop preserves at every iteration
- Count meaningful operations without relying on one stopwatch result
- Explain the sorted-input precondition of binary search
Choose the contract first
Suppose a list stores published lesson numbers in increasing order. The task is to find the first position whose value is at least a requested number, returning the list length if there is no such value. This is more precise than saying find the number because it defines duplicates and missing targets. Specify whether the input is sorted, whether duplicates are allowed, and what the return value means. Correctness is always relative to such a contract; a fast answer to a different question is still wrong.
Keep a region of possible answers
Use two boundaries, lo and hi, beginning at zero and the list length. Maintain that every position before lo contains a value smaller than the target, while every position at or after hi contains a value at least as large. The unclassified interval is from lo up to but excluding hi. A midpoint comparison discards part of that interval without discarding the first valid answer. This preserved statement is a loop invariant: it explains why each update is legitimate rather than asking you to memorize one arrangement of signs.
Trace the boundaries on concrete values
For values [2, 5, 5, 9] and target 5, begin with lo = 0 and hi = 4. The midpoint is 2 and its value is 5, so move hi to 2. The next midpoint is 1 and again its value is 5, so move hi to 1. The next midpoint is 0 and its value is 2, so move lo to 1. The interval is now empty, and position 1 is the first answer. Notice that equality moves the upper boundary because an earlier equal value may remain.
def first_at_least(values, target):
lo, hi = 0, len(values)
while lo < hi:
mid = lo + (hi - lo) // 2
if values[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
print(first_at_least([2, 5, 5, 9], 5)) # 1Connect progress to cost
Each iteration makes the remaining interval smaller, approximately halving it, so the number of comparisons grows logarithmically with input length. A linear scan can need a comparison for each element. These growth descriptions do not say which implementation wins on every tiny input or account for every hardware cost. Binary search also assumes efficient access to a midpoint and already sorted data. If sorting is needed for one isolated query, include that preparation cost when comparing approaches.
Test the assumptions and the edges
Try an empty list, a target before every element, a target after every element, an exact match, and repeated values. Verify not just a returned index but the promised properties: all preceding values are smaller, and the returned value, when present, meets the target. Then deliberately use an unsorted input and explain why the proof no longer applies. Learning the precondition and invariant makes the algorithm easier to adapt safely than remembering its name alone.
Try it yourself
Trace the algorithm for [1, 4, 4, 8, 12] and target 6. Give the final index, then explain which boundary update would be wrong when the midpoint equals the target.
Show a possible solution
The final index is 3, containing 8. Moving lo beyond an equal midpoint would be wrong for this first-at-least contract because it could discard the earliest valid equal value; equality must move hi to the midpoint.
Check your understanding
Try 14 questions across data structures and algorithms. Read each explanation and revisit anything that needs another pass.
Practise this subjectGo to the source
Use these primary references to check details and explore the topic further.
Saved in this browser. Signed-in progress syncs to your account.