Skip to content

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.

14 min read0/5 questions

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].

Steplohimidnums[mid]Decision
105233 < 9, so lo = 3
23549found, return 4

And for a target that is missing, 2:

Dry run: binary search for 2 (not present)
-1
0
↑lo
0
1
3
2
↑mid
5
3
9
4
12
5
↑hi
target = 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.

1/4
Predict the outputPython

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)
Need a nudge? Hints walk you through it.

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 l or right of r can 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): "lowest is the minimum price in prices[0..i], and best is 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 the pairs0/5 matched

Match each algorithm to its invariant.

Choose an item, then its match on the other side.

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.

Two pointers with the invariant
1
0
↑l
2
1
4
2
7
3
11
4
↑r
sum = 12target = 9

1 + 11 = 12, too big. 11 is too big even with the smallest value, so 11 cannot be in any answer. Move r left.

1/3
Quick check
In the first step, the sum 12 was too big. Why is it safe to move r and not l?
Need a nudge? A hint rules out a wrong answer.

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 < hi that exits before checking a one-element range.
  • Updating in the wrong order: recording the answer before shrinking the window, or updating lowest before computing today's profit.
  • Pointers that do not move: lo = mid instead of lo = mid + 1 loops forever when lo + 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.
Quick check
A binary search uses lo, hi = 0, len(nums) - 1 and while lo < hi:. Dry run it on nums = [5], target = 5. What happens?
Need a nudge? A hint rules out a wrong answer.
Put it in order5 steps

Put the dry-run routine in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Practice

Write the invariant first, then dry-run a missing target and a one-element list before you submit.

ChallengeEasy

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   →  0

Constraints

  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i], target <= 10^4
  • All values in nums are unique.
  • nums is sorted in ascending order.
def binary_search(nums: list[int], target: int) -> int: # Look at the middle, then throw away the half that cannot hold target. pass
Key terms
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) or while lo < hi on 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.