Trace code with a variable table and find a bug from the first failing input.
Use it when the output is wrong and you do not yet know why. Signal words: my answer is off by one, it works on the example but not on the test, which input makes it fail.
Start find a failing input, and write the correct answer by hand or from a brute force.
Step shrink the input while it still fails. Trace the small input by hand, one row for each step, and compare each row with the code.
Stop you can point at one row where the code does something the trace does not.
It does not find a bug that appears only at a large size, such as a total that wraps. For those, check the largest input by counting.
Cost: a hand trace of a small input takes minutes. Printing every step of a large input can print millions of lines.
In this lesson you learn to find a bug without guessing. You trace code by hand with a table, print only what you need, hunt off-by-one errors, shrink a failing input, and compare with a brute force. Every number below comes from running real code.
You work on a maps app. A bus reports its speed once a minute, and a job counts the rises: the minutes when the speed is higher than in the minute before. A teammate hands you the job, and it looks right.
You try the readings 4, 2, 7, 1, 8, 3 and count by hand. The speed rises at 7 and at 8, so the answer is 2. The job returns 3.
Your team lead says: Find the bug, and show me how you know it is the cause.
A detective does not search the whole city. She writes a timeline of what happened, then finds the first moment where the story and the evidence disagree. The cause is at that moment.
The timeline is your trace table. The story is what you expect, and the evidence is what the code does. The first row where they disagree is where the bug is.
Like a detective with a timeline: find the first moment where the story and the evidence disagree, and the cause is there.
Before you change any code, trace the six readings by hand. The player lists every comparison of a correct counter.
Solve it by hand: Six readings: count every rise. The hand-solve sheet loads in your browser.
Write one row for each place, with the reading before it, the reading at the place, and the counter.
The readings are 4, 2, 7, 1, 8, 3. Place 0 has no reading before it, so the comparisons start at place 1.
| Place | Reading | Reading before | A rise? | Counter |
|---|---|---|---|---|
| 1 | 2 | 4 | no | 0 |
| 2 | 7 | 2 | yes | 1 |
| 3 | 1 | 7 | no | 1 |
| 4 | 8 | 1 | yes | 2 |
| 5 | 3 | 8 | no | 2 |
The table gives 2 rises. The teammate's job gave 3.
Start with the way most people debug: print the state at every step. This is correct, and it works on a short list.
def count_rises(readings):
rises = 0
for i in range(len(readings)):
print(i, readings[i], readings[i - 1]) # show every comparison
if readings[i] > readings[i - 1]:
rises += 1
return risesOn the six readings it prints six lines. The first line is 0 4 3: place 0 is compared with place -1, which is the last reading, 3. The loop starts one place too early.
Now check the real size.
One bus reports 1,440 readings a day, and the app has 1,000 buses. A failing day is 1,440,000 readings.
Here is the count:
So printing every step is not a method for real data. You first need a small input that still fails.
Predict the bug
Q The loop is for i in range(len(readings)) and it compares readings[i] with readings[i - 1]. For [4, 2, 7, 1, 8, 3] it counts 3 rises. Which comparison makes the extra rise?
Answer: C
In Python, index -1 is the last place. At place 0 the loop compares 4 with the last reading, 3, and 4 is higher.
The next step is to make the failing input small.
Can you find the bug without a long print-out? Make the input smaller while it still fails. Drop one reading at a time, and keep the drop when the job still returns the wrong answer.
A random test of lists of eight readings found the failing list [3, 0, 1, 6, 6, 1, 3, 1]. The job gives 4 and the correct answer is 3. Shrinking it step by step ends at [3, 1]: the job gives 1, the correct answer is 0.
The shrunk list has two readings, so the trace table has one row. That row compares place 0 with the last reading. The cause is plain.
The course method is to write the slow, simple and correct version first. Run it and the fast version on many small lists, and print the first list where they differ.
Seed the random numbers, so that anyone can repeat the run. Random lists find a failure fast, but rarely the smallest one. So also try every list of length 0 to 4 over the values 0, 1 and 2, shortest first. The 8th list is the first to fail, and it is [1, 0].
The counts below come from running the enumeration:
| Largest length | Lists to try | Calls: your function and the brute force |
|---|---|---|
| 2 | 13 | 26 |
| 4 | 121 | 242 |
| 6 | 1,093 | 2,186 |
| 8 | 9,841 | 19,682 |
Race: Lists to run when every small list is tried. The operation counter loads in your browser.
The race counts every list of length 0 up to the largest length, over three values. Even at length 8 there are 9,841 lists, so a computer tries all of them at once.
Shrink a failing list: drop one reading at a time, keep the drop while it still fails, and eight readings become two.
Now trace the correct counter on the failing list. The player stops at four steps and asks you to predict the counter.
Dry run: Predict the counter on the failing list. The step-by-step player loads in your browser.
Reading without the player? Cover the last column and predict it row by row.
| Place | Reading | Reading before | A rise? | Counter |
|---|---|---|---|---|
| 1 | 0 | 3 | no | 0 |
| 2 | 1 | 0 | yes | 1 |
| 3 | 6 | 1 | yes | 2 |
| 4 | 6 | 6 | no | 2 |
| 5 | 1 | 6 | no | 2 |
| 6 | 3 | 1 | yes | 3 |
| 7 | 1 | 3 | no | 3 |
The correct answer is 3. The buggy job added a fourth rise at place 0, where 3 is compared with the last reading, 1.
Off-by-one errors sit at the two ends of a loop. Check three things for every loop:
| Check | Question | In the rise counter |
|---|---|---|
| First pass | Does the loop start where the first valid comparison is? | Place 1, not place 0 |
| Last pass | Does the loop stop after the last valid item? | Place len - 1 is the last |
| Count | How many passes should there be? | len - 1 comparisons for len readings |
Exercise · Find the bug: The rise that is never counted. This counter misses a rise on some lists, although the loop starts at the right place. Which line is wrong?
def count_rises(readings):
rises = 0
for i in range(1, len(readings) - 1):
if readings[i] > readings[i - 1]:
rises += 1
return risesHere is the rule behind every step of this lesson. Both templates use it.
A bug sits where the code and a hand trace first disagree, so shrink the input until that first disagreement is one row of a table.
Use it when the output is wrong and you do not yet know why. Signal words: my answer is off by one, it works on the example but not on the test, which input makes it fail.
Start: find a failing input, and write the correct answer by hand or from a brute force.
Step: shrink the input while it still fails. Trace the small input by hand, one row for each step, and compare each row with the code.
Stop: you can point at one row where the code does something the trace does not.
It does not find a bug that appears only at a large size, such as a total that wraps. For those, check the largest input by counting.
Cost: a hand trace of a small input takes minutes. Printing every step of a large input can print millions of lines.
This is the counter the table describes. It starts at place 1, so place 0 is never compared with the last reading.
def count_rises(readings):
# [1] No rise has been seen yet.
rises = 0
# [2] Start at place 1: place 0 has no reading before it.
for i in range(1, len(readings)):
# [3] A rise: this reading is higher than the one just before it.
if readings[i] > readings[i - 1]:
rises += 1
# [4] Return the number of rises.
return risespublic int countRises(int[] readings) {
// [1] No rise has been seen yet.
int rises = 0;
// [2] Start at place 1: place 0 has no reading before it.
for (int i = 1; i < readings.length; i++) {
// [3] A rise: this reading is higher than the one just before it.
if (readings[i] > readings[i - 1]) {
rises++;
}
}
// [4] Return the number of rises.
return rises;
}int countRises(const std::vector<int>& readings) {
// [1] No rise has been seen yet.
int rises = 0;
// [2] Start at place 1: place 0 has no reading before it.
for (size_t i = 1; i < readings.size(); i++) {
// [3] A rise: this reading is higher than the one just before it.
if (readings[i] > readings[i - 1]) {
rises++;
}
}
// [4] Return the number of rises.
return rises;
}function countRises(readings) {
// [1] No rise has been seen yet.
let rises = 0;
// [2] Start at place 1: place 0 has no reading before it.
for (let i = 1; i < readings.length; i++) {
// [3] A rise: this reading is higher than the one just before it.
if (readings[i] > readings[i - 1]) {
rises++;
}
}
// [4] Return the number of rises.
return rises;
}Rebuild the template: put its lines back in order. Loads in your browser.
When you compare your output with a brute force, find the first place where the lists differ. That place is where you start tracing.
def first_difference(mine, expected):
# [1] Compare only as far as the shorter list reaches.
shorter = min(len(mine), len(expected))
# [2] Report the first place where the values differ.
for i in range(shorter):
if mine[i] != expected[i]:
return i
# [3] Equal so far: if the lengths differ, the difference starts where the shorter list ends.
if len(mine) != len(expected):
return shorter
# [4] The lists are identical.
return -1public int firstDifference(int[] mine, int[] expected) {
// [1] Compare only as far as the shorter list reaches.
int shorter = Math.min(mine.length, expected.length);
// [2] Report the first place where the values differ.
for (int i = 0; i < shorter; i++) {
if (mine[i] != expected[i]) {
return i;
}
}
// [3] Equal so far: if the lengths differ, the difference starts where the shorter list ends.
if (mine.length != expected.length) {
return shorter;
}
// [4] The lists are identical.
return -1;
}int firstDifference(const std::vector<int>& mine, const std::vector<int>& expected) {
// [1] Compare only as far as the shorter list reaches.
int shorter = (int)std::min(mine.size(), expected.size());
// [2] Report the first place where the values differ.
for (int i = 0; i < shorter; i++) {
if (mine[i] != expected[i]) {
return i;
}
}
// [3] Equal so far: if the lengths differ, the difference starts where the shorter list ends.
if (mine.size() != expected.size()) {
return shorter;
}
// [4] The lists are identical.
return -1;
}function firstDifference(mine, expected) {
// [1] Compare only as far as the shorter list reaches.
const shorter = Math.min(mine.length, expected.length);
// [2] Report the first place where the values differ.
for (let i = 0; i < shorter; i++) {
if (mine[i] !== expected[i]) {
return i;
}
}
// [3] Equal so far: if the lengths differ, the difference starts where the shorter list ends.
if (mine.length !== expected.length) {
return shorter;
}
// [4] The lists are identical.
return -1;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Break it: Find the pair of lists this misses. This first-difference function compares place by place and returns -1 when nothing differs. Find two lists where it gives the wrong answer.
def first_difference(mine, expected):
shorter = min(len(mine), len(expected))
for i in range(shorter):
if mine[i] != expected[i]:
return i
return -1Compare with a brute force: run the slow correct version and the fast one on small lists, and trace the first list where they differ.
You can find the cause of any wrong answer in five steps.
Your function returns [1, 2, 4] and the brute force returns [1, 2, 3]. Template 2 compares place by place, and it returns 2: the first difference is at place 2.
With [1, 2] against [1, 2, 3] it returns 2 as well, because one list ends there. Equal lists return -1.
Real data brings edge cases.
With readings = [] or readings = [5] there is no comparison, so the answer is 0. The loop of the template starts at place 1 and stops at once. A loop that starts at place 0 reads place -1, which in Python is the last place.
With readings = [3, 1] the correct answer is 0. The buggy job compares 3 with the last reading, 1, and counts a rise, so it returns 1. This is the minimal failing case.
With readings = [3, 3, 3] the answer is 0, because a rise needs a higher reading. Using >= instead of > would count 2.
Exercise · Predict the output: What does the greater-or-equal counter say?. A teammate changes the test to `>=`. Six readings, where two neighbours are equal twice. What does this print?
readings = [4, 4, 2, 7, 7, 8]
rises = 0
for i in range(1, len(readings)):
if readings[i] >= readings[i - 1]:
rises += 1
print(rises)In Java, readings[-1] throws an ArrayIndexOutOfBoundsException, so the judge shows Runtime Error. In Python the same bug does not crash and gives Wrong Answer. The kind of verdict depends on the language.
This approach reads the loop three times and finds nothing.
Counterexample: the loop for i in range(len(readings)) with readings[i - 1] looks natural. Only the trace of [3, 1] shows that place 0 is compared with the last reading and the job returns 1, not 0.
A trace shows what the code does. Reading shows what you expect.
Do not fix by trial: subtracting one from the answer passes the example and fails on the list one, two.
This version subtracts 1 from the answer, because the example gave 3 and should give 2.
Counterexample: it passes [4, 2, 7, 1, 8, 3], which now gives 2. For [1, 2] the job counts 1 and subtracting 1 gives 0, but the correct answer is 1.
A change that passes one example is not a fix. Find the cause first.
This approach runs the one example and stops.
Counterexample: the buggy job gives the right answer for [0, 1] and for [1, 2], because their last reading is above their first. It fails only for lists such as [2, 1] where the first reading is above the last. One example can hide the bug.
Test more than one input, and always test lists whose first reading is above the last.
Tracing small inputs finds logic errors. It does not find a total that wraps. Adding three payments of 1,000,000,000 in a 32-bit integer gives -1,294,967,296, and no list of three small numbers shows it.
For a size-related bug, think about the largest input: count the steps and the size of the largest total, as you did in the lesson on the judge.
Your team lead brings three product changes. Each one changes how you debug.
The judge shows Runtime Error with a line number. Go to that line first. Trace the smallest input that reaches it, usually the empty list or the one-item list.
A random test fails on some runs only. Seed the random generator, so that the same seed always makes the same lists. Then the failing list can be repeated and shrunk.
Keep the shrunk failing list as a test. After the fix it must pass, and it guards against the same bug in the future. A test with [3, 1] would have caught this bug.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how you find a bug from a wrong answer. Then say what a hand trace cannot find. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have traced it.
I find a failing input, shrink it to the smallest one that still fails, and trace it by hand with a table. The first row where the table and the code disagree is the bug.
I compare with a brute force on small random lists, so the first difference gives me a failing case. For an off-by-one I check the first and last pass of the loop.
A small trace cannot find a total that wraps at a large size, so I also check the largest input by counting.
When my answer is wrong, I do not guess. I first find an input that fails. If I have a slow but simple brute force, I run both versions on many small random lists. The first list where they differ is my failing case.
Then I shrink the input. I drop one item at a time while it still fails, until I have the smallest failing case. A list of eight readings can shrink to two.
I trace that small case by hand with a table: one row for each step, one column for each variable. The first row where the table and my code disagree is the bug. For off-by-one errors I look at the first and last pass of every loop.
I fix the cause, not the answer. Then I run the failing case and the examples again, and I keep the failing case as a test.
Checkpoint · Hand-tracing and debugging
Q1/10 What does a trace table hold?
Answer: B
A trace table follows the code step by step. You compare each row with what the code does.
Q2/10 Where is the bug, according to the lesson?
Answer: C
The first disagreement is the earliest moment the code does something the trace does not. The cause is there.
Q3/10 A job prints every step of 1,440,000 readings to find a bug. What is the problem?
Answer: B
Printing every step is correct on a short list. At real size you must shrink the input first.
Q4/10 In Python, readings[i - 1] is read at i = 0. Which place does it read?
Answer: C
Index -1 is the last place in Python. The loop does not crash, so the bug shows up as a wrong answer.
Q5/10 The buggy rise counter returns 3 on [4, 2, 7, 1, 8, 3] and the correct answer is 2. Which comparison makes the extra rise?
Answer: C
At place 0 the loop compares 4 with the last reading, 3, and counts a rise that does not exist.
Q6/10 What is a minimal failing case?
Answer: B
You drop items while the input still fails. The result has the fewest rows to trace, such as [3, 1].
Q7/10 Why run a brute force next to your fast version?
Answer: C
The course method is to write the slow, correct version first and compare on small lists.
Q8/10 The example gives 3 instead of 2, so you subtract 1 from the answer. The example passes. Why is this not a fix?
Answer: B
For [1, 2] the right answer is 1, and the job minus 1 gives 0. Find the cause, not a number that fits one example.
Q9/10 In Java, the same loop reads readings[-1]. What does the judge show?
Answer: C
Java throws an ArrayIndexOutOfBoundsException. Python does not crash, so the verdict depends on the language.
Q10/10 Which bug can a hand trace of a small list not find?
Answer: C
A total that wraps shows only with large values. Check the largest input by counting.
Ten questions on this lesson. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | First unread thread | Chat | Easy | Tracing a right-to-left pass and the edge at the end |
| 2 | Missing sequence number | Chat | Easy | A total instead of a search, and a product that wraps |
| 3 | Find the off by one in the window | Stream | Medium | The number of windows, and the value that leaves |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.