Lesson 12 of 27From idea to plan
Dry Runs and Invariants
Trace your plan by hand on a small example before coding, and state the rule your loop keeps true.
You have a plan. Before you type it, run it in your head (or on paper) on a small example and watch every variable change. This is a dry run, and it is the cheapest bug-finding tool there is: off-by-one errors, wrong loop conditions, and pointer moves in the wrong direction all show up in the first few steps. Pair it with an invariant, a sentence that stays true on every pass of the loop, and you can explain why your code is correct, not just hope it is.
What a dry run looks like
Pick a small example, 4 to 7 elements, that includes at least one interesting case. Write a column for every variable. Then step through your plan one iteration at a time and fill in the table. Do not skip steps because "it obviously works"; the bug is usually in the step you skipped.
Here is binary search for 9 in [-1, 0, 3, 5, 9, 12].
| Step | lo | hi | mid | nums[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 5 | 2 | 3 | 3 < 9, so lo = 3 |
| 2 | 3 | 5 | 4 | 9 | found, return 4 |
And for a target that is missing, 2:
lo = 0, hi = 5, mid = 2. nums[2] = 3 is bigger than 2, so the target, if present, is left of mid: hi = 1.
Dry-run this by hand. What does it print?
nums = [2, 7, 11, 15]
target = 11
lo, hi = 0, 3
steps = 0
while lo <= hi:
mid = (lo + hi) // 2
steps += 1
if nums[mid] == target:
break
elif nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
print(mid, steps)Invariants in plain words
A loop invariant is a statement that is true before the loop starts and stays true after every iteration. You do not need formal notation. A plain sentence is enough, and it does three jobs: it tells you how to initialise, how to update, and why the answer is right when the loop ends.
- Binary search: "If the target is in the array, it is somewhere in
nums[lo..hi]." Initialise to the whole array. Each move throws away only a half that cannot contain the target. When the range is empty, the target is not there. - Two pointers on a sorted pair sum: "No pair using an index left of
lor right ofrcan be the answer." Each move discards one value that provably cannot pair with anything remaining. - Sliding window: "The window
[left, right]obeys the rule after the shrink loop." That is why you record the answer after shrinking, not before. - Running best (max profit): "
lowestis the minimum price inprices[0..i], andbestis the best profit selling on or before day i." - BFS: "Every node in the queue is at distance d or d + 1, and nodes come out in order of distance."
Match each algorithm to its invariant.
Tracing two pointers
Find two numbers summing to 9 in the sorted array [1, 2, 4, 7, 11]. Watch the invariant: everything outside l..r is ruled out.
1 + 11 = 12, too big. 11 is too big even with the smallest value, so 11 cannot be in any answer. Move r left.
r and not l?The bugs a dry run catches
Most bugs in interview code fall into a few kinds, and each one shows up quickly on a well-chosen dry run:
- Off-by-one on bounds:
range(n - 1)that skips the last element,hi = len(nums)that reads past the end. - Wrong loop condition:
while lo < hithat exits before checking a one-element range. - Updating in the wrong order: recording the answer before shrinking the window, or updating
lowestbefore computing today's profit. - Pointers that do not move:
lo = midinstead oflo = mid + 1loops forever whenlo + 1 == hi. - Forgetting to reset or mark: a DFS that never marks cells visited, which a 2 x 2 grid of land will reveal in four steps.
lo, hi = 0, len(nums) - 1 and while lo < hi:. Dry run it on nums = [5], target = 5. What happens?Put the dry-run routine in order.
- Tap the steps below in the right order.
Practice
Write the invariant first, then dry-run a missing target and a one-element list before you submit.
Binary Search
Given a list nums sorted in ascending order with no repeated values, and a number target, return the index of target, or -1 if it is not in the list. Your solution must run in O(log n) time.
nums = [-1, 0, 3, 5, 9, 12], target = 9 → 4
nums = [-1, 0, 3, 5, 9, 12], target = 2 → -1
nums = [5], target = 5 → 0Constraints
1 <= nums.length <= 10^4-10^4 <= nums[i], target <= 10^4- All values in
numsare unique. numsis sorted in ascending order.
- dry run
- Tracing your plan by hand on a small example, writing down every variable after each step.
- loop invariant
- A sentence that is true before the loop and after every iteration, such as 'the target, if present, is in
nums[lo..hi]'. - off-by-one
- A bound or index that is one too high or too low, like
range(n - 1)orwhile lo < hion an inclusive range. - trace table
- A table with one column per variable and one row per iteration, filled in during a dry run.
- termination
- Showing the loop ends: each iteration must shrink the range or advance a pointer.