Lesson 3 of 5
Testing without a run button
Many interview rounds never run your code, so you run it yourself. This lesson turns that into a procedure you can follow under pressure, built on the no-execution checklist, a trace table that checks the promise on every row, edge cases for each pattern, loop bounds and None paths.
Run the no-execution checklist on your own code, in order, out loud
Fill a trace table that checks the promise on every row, not only the final answer
Choose the edge cases that fit the pattern you used
Check the first and last pass of every loop, including a while loop whose pointers meet
Find every line that can read from None, and every path that returns nothing
You have written a function in a shared editor. It looks right. The interviewer asks, "How do you know it works?" and there is no Run button. You cannot try it. You can only read it, and module 1 showed why reading is not enough: you read what you meant, not what you wrote.
Testing without running means running the code yourself, out loud, on inputs you choose. Testing is one of the four things the round scores. Skip it, and you risk the mistake one published rubric gives as its example of Strong No Hire, the lowest rating: announcing "done" over an untested, glaring bug.
This lesson turns the habit from module 1 into a procedure you can run under pressure. It has four parts: a checklist; a trace table (one column per name, one row per pass) with one more column for the promise, the sentence your code keeps true after every step; the edge cases each pattern needs; and two places bugs often hide, loop bounds and None (Python's value for "no value").
The checklist
What do you check, and in what order? A dry run is running code by hand: you play the computer, one line at a time, and write down the value of every name. The research digest behind this course gives a checklist for rounds with no code execution. Here it is in order, with the kind of bug each step catches:
| Step | Check | What it catches |
|---|---|---|
| 1 | Reread the whole code once | a typo, a name used before it is set, a missing return |
| 2 | Trace one typical case aloud, with every name's value | wrong logic on the main path |
| 3 | Trace an empty input and a one-item input | a crash on nums[0], a wrong starting value |
| 4 | Trace duplicates and boundaries | ties, an answer at the first or last position |
| 5 | Check every loop bound for off-by-one | a loop that stops one pass early or runs one pass too far |
| 6 | Check None, absent-node and not-found paths | a crash on None.next, a search that returns nothing |
| 7 | Confirm that base cases (inputs a recursive function answers without calling itself) and early returns fire | recursion that never stops, an early return that never runs |
| 8 | State time and space, then declare done | no bug: it answers the complexity question before it is asked |
Each testing step looks for what the steps before it miss. The typical case comes first because it shows the main idea works and gives the interviewer a picture of your code. The small and strange inputs come next because they find the bugs a typical case misses. Bounds and None come after, as a line-by-line read, because no single input is sure to hit them. The cost comes last.
In the think-aloud script from the previous lesson, the test phase gets 5 to 7 minutes. Small inputs are what make that budget work: each pass of a loop is one row of a table, so a 5-item input fills 5 or 6 rows, counting the row before the loop. Step 1 needs no section of its own: read each line once, slowly, looking for the bugs in its row. The rest of this lesson takes steps 2 to 8 in order.
A trace table, out loud
What does a dry run sound like, and what do you check on each row? Here is a function you might write in a round. A sensor sends one reading per minute, and a stuck sensor sends the same value again and again. longest_run(nums) returns the length of the longest run of equal neighbors, where a run is a stretch of positions in a row that all hold the same value. For [4, 4, 4, 2, 7] the answer is 3: the three 4s.
Before typing, you stated the promise, the sentence that must be true about the notebook (the values the loop keeps) after every step: best is the longest run among the positions visited so far. In the trace, the arrow i under the list marks the position being compared with its left neighbor. Before you step through, guess two things: what the code returns for [4, 4, 4, 2, 7], and on which pass best first changes from 0.
def longest_run(nums):best = 0run = 1for i in range(1, len(nums)):if nums[i] == nums[i - 1]:run += 1else:best = max(best, run)run = 1return best
(nothing printed yet)The answer is right, and a quick tester stops here. A careful tester checks the promise on every row, because a right answer can come from wrong code. Here is the same run as a trace table (from module 1), with one extra column: the longest run among the positions visited so far, worked out by looking at the list itself. That column is what the promise says best should hold.
| Pass | i | Same as left neighbor? | run | best | Longest run so far |
|---|---|---|---|---|---|
| before | 1 | 0 | 1 | ||
| 1 | 1 | yes, 4 and 4 | 2 | 0 | 2 |
| 2 | 2 | yes, 4 and 4 | 3 | 0 | 3 |
| 3 | 3 | no, 2 and 4 | 1 | 3 | 3 |
| 4 | 4 | no, 7 and 2 | 1 | 3 | 3 |
The promise is broken on the first three rows. best says 0 while the longest run so far is 1, then 2, then 3. best only catches up when a run ends. In this input the run of 4s ended at the 2, so the final answer came out right by luck.
Out loud, the first row sounds like this: "Before the loop, run is 1 for the first 4, and best is 0. My promise says best is the longest run so far, which is already 1. So best lags behind. It only changes in the else branch, when a run ends. What if the longest run is the last one?" That question is the bug, found by reading one row against the promise.
Here is the dry run itself in the four questions this course asks of every method:
Now answer the question the table raised, before the next trace shows it.
Use longest_run from the trace above, unchanged. What does longest_run([6, 6, 6]) return? The right answer would be 3. Type what the code returns: fill one row per pass, starting with the row before the loop.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Edge cases
Which inputs find the bugs a typical case misses? An edge case is an input at the edge of what the problem allows: empty, one item, all items equal, the answer in the first or last position. Start with the bug the table pointed at: best is updated only when a run ends, and the last run never ends, because the loop runs out of positions first. Guess what longest_run([5, 7, 7]) returns, then step through.
def longest_run(nums):best = 0run = 1for i in range(1, len(nums)):if nums[i] == nums[i - 1]:run += 1else:best = max(best, run)run = 1return best
(nothing printed yet)Three tiny inputs expose this bug: a list that ends in its longest run ([5, 7, 7] gives 1), a list of equal items ([6, 6, 6] gives 0), and a single item ([8] gives 0). None of them is exotic. They are steps 3 and 4 of the checklist: one item, all equal, the answer at a boundary.
The fix follows from the promise: update best on every pass, not only when a run ends. The starting values must make the promise true before the loop: one position visited, a run of 1, so best starts at 1 too. That raises a new edge case. An empty list has no first item, so starting at 1 would return 1 for it. It needs a guard: an if at the top that returns 0 before anything else runs. Here the guard is if not nums: return 0, since not nums is True exactly when the list is empty.
Put the fixed version together. Two of the lines are the old bugs.
Put the lines in order to build a longest_run that keeps its promise on every row: after each pass, best is the longest run among the positions visited. Follow the fix from the text: best starts where the promise needs it and is updated on every pass, never only when a run ends. The guard for the empty list comes first, as it usually does. Indentation is part of each line. Two lines do not belong: they are the old bugs.
Add lines from the list below, in order.
run = 1def longest_run(nums):best = max(best, run)if not nums:return 0for i in range(1, len(nums)):run, best = 1, 1if nums[i] == nums[i - 1]:return bestrun += 1run, best = 1, 0else:best = max(best, run)
Then rerun the input that found the bug. Here is the fixed code:
def longest_run(nums):
if not nums: # the guard: an empty list has no runs
return 0
run, best = 1, 1 # one position visited: a run of 1
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
run += 1
else:
run = 1
best = max(best, run) # every pass, not only when a run ends
return best
And here is its trace table on [5, 7, 7], with the promise column:
| Pass | i | Same as left neighbor? | run | best | Longest run so far |
|---|---|---|---|---|---|
| before | 1 | 1 | 1 | ||
| 1 | 1 | no, 7 and 5 | 1 | 1 | 1 |
| 2 | 2 | yes, 7 and 7 | 2 | 2 | 2 |
best matches the promise column on every row, and the call returns 2. The other edge cases agree: [6, 6, 6] gives 3, [8] gives 1, and [] stops at the guard with 0.
Edge cases for each pattern
Each pattern has its own edge cases. The table below is what to reach for after the typical case. You will not trace all of them in one round: pick the two or three that match the code you wrote.
| Pattern or input | Edge cases to trace | What they catch |
|---|---|---|
| Any list or string | empty, one item, all items equal | a crash on nums[0], a wrong starting value, a last run never recorded |
| Numbers | all negative, all positive | a maximum that starts at 0 (wrong when all are negative), a minimum that starts at 0 (wrong when all are positive) |
| Walks and windows | the answer at the very first or very last position | a loop that starts late or stops early |
| Hash map, pairs | duplicates, such as [3, 3] with target 6, and a number that is half the target | pairing an item with itself, missing a pair of two equal values |
| Sorted input, binary search | one item, the target first or last, a target below or above every item, a target that is absent | a loop that stops before lo and hi meet, a not-found path with no return |
| Monotonic stack | already sorted, sorted backwards | items still on the stack when the walk ends: one of these two orders leaves every item there, waiting for an answer |
| Linked list | None, one node, two nodes, a cycle | a crash on None.next, a walk that never ends |
| Tree | None, one node, every node leaning one way | a missing base case, a node with one child treated as a leaf |
| Graph | a cycle, two parts with no edge between them | a walk with no visited set, a search that misses a part |
| Intervals | touching ([1, 3] and [3, 5]), one inside another | < where <= belongs, an end that shrinks |
Recap. A typical case shows the main idea works. Edge cases find the bugs, and the table above says which ones to try for each pattern. Check the promise on every row, including the row before the loop, and after any fix, trace the edge cases again.
Loop bounds: the first pass and the last
Does each loop start and stop in the right place? An off-by-one bug is a loop that runs one pass too many or one too few. Module 1 gave the rule for for loops: write down the first and last value the loop variable takes, and check both against the data. while loops need the same check, and the moment to look at is the last pass: what is true when the loop is about to stop?
Binary search moves two bounds, so it is a good place to practice. This version uses while lo < hi. The arrows lo, mid and hi sit under the list. Guess what find([1, 3, 5, 7], 7) returns. The 7 is at index 3.
def find(nums, target):lo, hi = 0, len(nums) - 1while lo < hi:mid = (lo + hi) // 2if nums[mid] == target:return midif nums[mid] < target:lo = mid + 1else:hi = mid - 1return -1
(nothing printed yet)When lo equals hi, one candidate is left (one position that could still hold the target), and lo < hi stops before checking it. The find template from module 6 uses while lo <= hi for exactly this reason. Module 6's first-true template does use lo < hi, and there it is right: a yes keeps mid with hi = mid, and the loop's job is to narrow down to one candidate and return it, not to look at it. The loop bound has to match the moves. The cheapest test that catches the bug here is one item: find([7], 7) starts with lo and hi both at 0, the loop never runs, and the function returns -1.
This is find from the trace, still with while lo < hi. Type exactly what it prints.
def find(nums, target):
lo, hi = 0, len(nums) - 1
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
print(find([1, 3, 5, 7], 1))
print(find([1, 3, 5, 7], 3))
print(find([2, 4], 4))
for loops fail the same way, one position short. The rule from module 1 finds it: write the first and last value the loop variable takes, and check the last one against the last position the loop must reach. The next three exercises follow one planted bug from start to finish: find it by hand, pick the test that would have caught it, then fix it.
max_window_sum(nums, k) should return the largest sum of k neighboring items. For [2, 1, 3, 4] and k = 2 the windows are [2, 1], [1, 3] and [3, 4], with sums 3, 4 and 7, so the answer is 7. Each pass slides the window one place right: nums[right] enters and nums[right - k] leaves. The code has one planted bug.
def max_window_sum(nums, k):
window = sum(nums[:k])
best = window
for right in range(k, len(nums) - 1):
window += nums[right] - nums[right - k]
best = max(best, window)
return best
Dry-run it on paper for nums = [2, 1, 3, 4] and k = 2. First write the first and last value right takes. Then fill one row per pass with right, window and best, starting with a row for the state before the loop. Type what the code returns, then reveal the steps one at a time to check your rows.
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Suppose you had not spotted the bug in max_window_sum (the loop is for right in range(k, len(nums) - 1)). You have time to trace one more test. Which one would have caught the bug?
Choose one answer, then check.
Fix max_window_sum. The tests are edge cases from this lesson: the answer in the last window, the answer in the first window, k equal to the length, all negative numbers, and k = 1. Before you press Run, dry-run your fix on [1, 1, 1, 9] with k = 2, then press Watch it run to see right reach the last position.
Recap. For every loop, say the first and last value of its variable. For a while loop, look at the moment the pointers meet: does the loop still check the last candidate? A one-item input caught the binary search bug, and the answer in the last window caught the for loop bug.
None paths and not-found paths
What happens when a name holds None? A reminder from modules 7 and 8: a linked list node keeps its value in .val and the node after it in .next, and a tree node keeps its children in .left and .right. Linked lists and trees end in None: the last node's next is None, and so are a leaf's left and right (a leaf is a tree node with no children). An empty list or an empty tree is None itself. Every .next, .left, .right or .val asks a question: can this name be None here? If it can, that line crashes.
This function returns the value in the last node of a linked list. The trace draws each node as a box with an arrow to the next one, and cur as a tag above the node it names. The function is called twice. Guess which call breaks, and on which line.
def last_value(head):cur = headwhile cur.next is not None:cur = cur.nextreturn cur.valprint(last_value(build_list([3, 1, 4])))print(last_value(build_list([])))
(nothing printed yet)The loop condition was written for a list with at least one node. The fix is one guard at the top, before anything reads cur.next. What the guard returns is a question for the interviewer: what should an empty list give? None is a common answer, but ask.
def last_value(head):
if head is None: # an empty list has no last value
return None
cur = head
while cur.next is not None:
cur = cur.next
return cur.val
Not-found paths fail more quietly. A search that returns inside its loop when it finds the target reaches the end of the function when it does not. With no return there, it hands back None, and the caller crashes later or prints a wrong answer. find above has return -1 after its loop for this reason. Ask of every function: does every path end in a return with the right kind of value?
Base cases and early returns are paths too, and a path no test goes down is a path nobody checked. An early return is a return inside an if that ends the function before its last line, as the guard above does. For each one, pick a test that takes it: the empty list for if head is None, an empty tree for a recursive base case. Then trace that test.
remove_first(head, target) removes the first node whose value is target and returns the head of the list. The line numbers count from the def line as line 1.
def remove_first(head, target):
if head.val == target:
return head.next
cur = head
while cur.next.val != target:
cur = cur.next
cur.next = cur.next.next
return head
Which of these calls crash? Choose every one that does.
Choose every option that applies, then check.
Saying done
How do you end the test phase? When you find a bug, say so before you fix it. The digest's think-aloud script puts it in that order: announce the bug, then fix it. A bug you find and name is your testing working, in front of the person who scores it.
Then rerun the input that found the bug, and the edge cases, because a fix can add a bug. Then state the cost. Only then say done. For the window bug from the exercises, the whole thing sounds like this:
"I see a bug. The range stops at len(nums) - 1, so right never reaches the last position and the last window is never built. I'll change it to len(nums). Rerunning [2, 1, 3, 4] with k = 2: right now takes 2 and then 3, the last window is 3 + 4 = 7, so it returns 7. The one-item case, [4] with k = 1, still returns 4. It is one pass, so O(n) time and O(1) extra space. I'm done."
Last, say a full test plan for a pattern you know well.
You have written this in a round with no run button:
def two_sum(nums, target):
seen = {} # value -> index, for numbers already passed
for i, x in enumerate(nums):
if target - x in seen:
return [seen[target - x], i]
seen[x] = i
The interviewer asks how you know it works. Say your test plan out loud, as you would in the room: which inputs you trace, what you check on each, and how you finish.
Saved in this browser as you type.