iq.lab
Python starts when a code cell comes near or you run one
14 Interview mode

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.

About 1 hour 5 minutes
By the end you can
  • 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:

StepCheckWhat it catches
1Reread the whole code oncea typo, a name used before it is set, a missing return
2Trace one typical case aloud, with every name's valuewrong logic on the main path
3Trace an empty input and a one-item inputa crash on nums[0], a wrong starting value
4Trace duplicates and boundariesties, an answer at the first or last position
5Check every loop bound for off-by-onea loop that stops one pass early or runs one pass too far
6Check None, absent-node and not-found pathsa crash on None.next, a search that returns nothing
7Confirm that base cases (inputs a recursive function answers without calling itself) and early returns firerecursion that never stops, an early return that never runs
8State time and space, then declare doneno 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.

Step throughA dry run on a typical case
Step 1 of 21
Line 1 is about to run.
def longest_run(nums):
best = 0
run = 1
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
run += 1
else:
best = max(best, run)
run = 1
return best
Names
no names yet
Output
(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.

PassiSame as left neighbor?runbestLongest run so far
before101
11yes, 4 and 4202
22yes, 4 and 4303
33no, 2 and 4133
44no, 7 and 2133

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.

Work it outWhen every item is equal

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.

longest_run([6, 6, 6])

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.

Step throughThe edge case that breaks it
Step 1 of 14
Line 1 is about to run.
def longest_run(nums):
best = 0
run = 1
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
run += 1
else:
best = max(best, run)
run = 1
return best
Names
no names yet
Output
(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 in orderThe fixed longest run

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.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • run = 1
    • def longest_run(nums):
    • best = max(best, run)
    • if not nums:
    • return 0
    • for i in range(1, len(nums)):
    • run, best = 1, 1
    • if nums[i] == nums[i - 1]:
    • return best
    • run += 1
    • run, best = 1, 0
    • else:
    • 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:

    PassiSame as left neighbor?runbestLongest run so far
    before111
    11no, 7 and 5111
    22yes, 7 and 7222

    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 inputEdge cases to traceWhat they catch
    Any list or stringempty, one item, all items equala crash on nums[0], a wrong starting value, a last run never recorded
    Numbersall negative, all positivea maximum that starts at 0 (wrong when all are negative), a minimum that starts at 0 (wrong when all are positive)
    Walks and windowsthe answer at the very first or very last positiona loop that starts late or stops early
    Hash map, pairsduplicates, such as [3, 3] with target 6, and a number that is half the targetpairing an item with itself, missing a pair of two equal values
    Sorted input, binary searchone item, the target first or last, a target below or above every item, a target that is absenta loop that stops before lo and hi meet, a not-found path with no return
    Monotonic stackalready sorted, sorted backwardsitems still on the stack when the walk ends: one of these two orders leaves every item there, waiting for an answer
    Linked listNone, one node, two nodes, a cyclea crash on None.next, a walk that never ends
    TreeNone, one node, every node leaning one waya missing base case, a node with one child treated as a leaf
    Grapha cycle, two parts with no edge between thema walk with no visited set, a search that misses a part
    Intervalstouching ([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.

    Step throughA while loop that stops one pass early
    Step 1 of 16
    Line 1 is about to run.
    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
    Names
    no names yet
    Output
    (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.

    PredictWhere lo < hi gives up

    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.

    On paperA planted bug, by hand

    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.

    what the code returns

    Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

    Quick checkWhich test catches it?

    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.

    Code itFix the window

    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.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Press Run tests to run your code and the checks.

    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.

    Step throughA walk that assumes a node is there
    Step 1 of 15
    Line 1 is about to run.
    def last_value(head):
    cur = head
    while cur.next is not None:
    cur = cur.next
    return cur.val
    print(last_value(build_list([3, 1, 4])))
    print(last_value(build_list([])))
    Names
    no names yet
    Output
    (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.

    Quick checkWhich calls crash?

    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.

    Say itTest two sum out loud

    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.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Building in parts