unrust

Debugging interview: 6 steps and a mock round

Published

By the Unrust team · 12 min read · Editorial method

Debugging interview prep: a 6-step routine and a mock round run on 7 Python builds. The same ranking failure text appeared after two different fixes.

What is a debugging interview, and how do you prepare for one?

A debugging interview hands you broken code, often with failing tests, and asks you to find the cause, fix it and explain your reasoning; formats vary. To prepare, use one fixed routine: ask what correct means, read the failure literally, shrink it, test one guess, fix the cause, and prove it with a rerun.

Ask the recruiter what your round includes: the language, whether you can run the tests, and whether a debugger or a web search is allowed. This post describes no company's live debugging round and promises no interview result.

Below you get the routine as a table, a mock round we wrote for this post with the exact output of every rerun, a script of what to say out loud, and a way to score your own practice. Preparing for a debugging interview then comes down to rehearsing the routine on code you did not write, with the AI and autocomplete off.

We ran the mock round on seven CPython builds (3.9.25 to 3.15.2) and the JavaScript probes on three Node.js builds (18.20.4, 22.11.0 and 24.11.0) on November 26, 2026. The output shown comes from CPython 3.11.2 and Node.js 24.11.0. Every build printed the same exception lines and tallies, and where tracebacks differ by version, the text says so.

What are the six steps of a debugging interview routine?

Six steps: ask what correct means, read the failure literally, shrink it to the smallest case, test one guess at a time, fix the cause rather than the symptom, and prove the fix by rerunning every test. The order is our suggestion, not a standard, and the table pairs each step with the question it answers.

The steps repeat: a hard bug sends you around steps 3 to 6 several times. In the mock round below, three bugs took four runs of the whole suite, the first run plus one rerun after each fix. Round 1 leans on steps 2 to 5, Round 2 on step 1 and Round 3 on step 6.

One old study is consistent with the routine. In Gugerty and Olson's two experiments with simple LOGO and Pascal programs, experts debugged more quickly and accurately, largely because they formed good hypotheses after less study of the code, and novices frequently added bugs while looking for the original one. That is a 1986 result on simple programs, so read it as a hint about method, not as a prediction about any round.

Step      Do                                                  Question it answers
--------  --------------------------------------------------  ----------------------------------------
1 Ask     Pin down what correct means for inputs and edges    What should this return, exactly?
2 Read    Quote the failure text, quotes and spaces included  What does the message literally say?
3 Shrink  Reproduce with one test or a one-line probe         What is the smallest case that fails?
4 Guess   Name one cause, predict the output, then run it     Which single idea am I testing?
5 Fix     Change the cause, one change per rerun              Where does the wrong value first appear?
6 Prove   Rerun every test, then try an input of your own     What could still be broken?

What do debugging interview questions ask, and what does a strong answer include?

Debugging interview questions give you code that fails a test or throws an error and ask you to find the cause, fix it and explain your reasoning; formats vary. By our rubric, a strong answer names the cause with evidence from a run, fixes the cause rather than the symptom, and shows a full rerun that passes.

The mock round is ours, written for this post, not taken from any company's round. report.py is a 24-line billing report and test_report.py holds four unittest tests; run them with python3 -m unittest from the folder that holds both files.

Read report.py once before you run anything: parse_row splits a line into a name, a plan and a start date, months_active counts months, invoice_total multiplies the plan price by those months, and top_spenders ranks customers by what they owe. A code reading debugging interview, where you explain code before you change it, starts the same way.

from datetime import date

PRICES = {"basic": 12, "pro": 30}


def parse_row(line):
    name, plan, start = line.split(",")
    year, month, day = start.strip().split("-")
    return {"name": name.strip(), "plan": plan, "start": date(int(year), int(month), int(day))}


def months_active(start, today):
    return (today.year - start.year) * 12 + (today.month - start.month)


def invoice_total(row, today):
    return PRICES[row["plan"]] * months_active(row["start"], today)


def top_spenders(lines, today, n):
    rows = [parse_row(line) for line in lines]
    totals = [(row["name"], f"{invoice_total(row, today):.2f}") for row in rows]
    ranked = sorted(totals, key=lambda pair: pair[1], reverse=True)
    return [name for name, _ in ranked[:n]]

What do the four tests expect, and what does the first run show?

The four tests in test_report.py are the spec you are handed. A start date parses, Jan 15 to Mar 14 is one full month, a pro customer who started on Jan 15 owes 30 on Mar 14, and the top two spenders are Ben, then Cy. Predict before you open the answer: which tests fail, and what does each failure say?

import unittest
from datetime import date

from report import invoice_total, months_active, parse_row, top_spenders

TODAY = date(2026, 3, 14)

LINES = [
    "Ana, pro , 2026-01-15",
    "Ben, basic, 2025-03-20",
    "Cy, pro, 2025-12-01",
]


class ReportTests(unittest.TestCase):
    def test_parse_row_reads_the_start_date(self):
        row = parse_row("Ben, basic, 2025-03-20")
        self.assertEqual(row["start"], date(2025, 3, 20))

    def test_months_active_counts_full_months_only(self):
        self.assertEqual(months_active(date(2026, 1, 15), TODAY), 1)

    def test_invoice_total_for_a_pro_customer(self):
        row = parse_row("Ana, pro , 2026-01-15")
        self.assertEqual(invoice_total(row, TODAY), 30)

    def test_top_spenders_are_ranked_by_amount(self):
        self.assertEqual(top_spenders(LINES, TODAY, 2), ["Ben", "Cy"])


if __name__ == "__main__":
    unittest.main()
Reveal the answer and explanation

The first line of output is EF.E, because unittest runs tests in the order of their names: the invoice test errors (E), the months test fails (F), the parse test passes (.) and the ranking test errors (E). The tally reads failures=1, errors=2: unittest calls a test that raised an unexpected exception an error, and a test whose assertion failed a failure.

Both errors are KeyError: ' pro ', and the failure is AssertionError: 2 != 1. Do not read three non-passing tests as three bugs: the KeyError stops two tests before they reach the arithmetic behind it.

The elapsed time on the Ran 4 tests line changes from run to run, so we show 0.001s. The exception lines and the tally were identical on all seven builds.

Tracebacks differ in decoration only. CPython 3.9 and 3.10 name only the class in each test header and print no marker lines under code; 3.12 and later leave out the list-comprehension frame that 3.9 to 3.11 print in the ranking traceback; and 3.13 and later draw some markers differently.

$ python3 -m unittest
EF.E
======================================================================
ERROR: test_invoice_total_for_a_pro_customer (test_report.ReportTests.test_invoice_total_for_a_pro_customer)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/app/test_report.py", line 25, in test_invoice_total_for_a_pro_customer
    self.assertEqual(invoice_total(row, TODAY), 30)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/app/report.py", line 17, in invoice_total
    return PRICES[row["plan"]] * months_active(row["start"], today)
           ~~~~~~^^^^^^^^^^^^^
KeyError: ' pro '

======================================================================
ERROR: test_top_spenders_are_ranked_by_amount (test_report.ReportTests.test_top_spenders_are_ranked_by_amount)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/app/test_report.py", line 28, in test_top_spenders_are_ranked_by_amount
    self.assertEqual(top_spenders(LINES, TODAY, 2), ["Ben", "Cy"])
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/app/report.py", line 22, in top_spenders
    totals = [(row["name"], f"{invoice_total(row, today):.2f}") for row in rows]
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/app/report.py", line 22, in <listcomp>
    totals = [(row["name"], f"{invoice_total(row, today):.2f}") for row in rows]
                               ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/app/report.py", line 17, in invoice_total
    return PRICES[row["plan"]] * months_active(row["start"], today)
           ~~~~~~^^^^^^^^^^^^^
KeyError: ' pro '

======================================================================
FAIL: test_months_active_counts_full_months_only (test_report.ReportTests.test_months_active_counts_full_months_only)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/app/test_report.py", line 21, in test_months_active_counts_full_months_only
    self.assertEqual(months_active(date(2026, 1, 15), TODAY), 1)
AssertionError: 2 != 1

----------------------------------------------------------------------
Ran 4 tests in 0.001s

FAILED (failures=1, errors=2)

Round 1: how do you read KeyError: ' pro ' literally?

Step 2 is to read the message character by character: the key is pro with a space on each side, and PRICES holds only pro and basic. The traceback names line 17 of report.py because that is where the lookup raised, but the row was already wrong when parse_row built it on line 9.

CPython 3.11 and later print the marker line under the code to show which lookup failed; 3.9 and 3.10 leave it out, and the rest of this excerpt is the same on all seven builds. The ranking test hits the same error through Ana's row, which comes first in its loop. Our stack trace post covers how Python and Node order their frames.

Predict before you open the answer: which line of report.py needs the change, and what will the first line of the next run look like?

  File "/app/report.py", line 17, in invoice_total
    return PRICES[row["plan"]] * months_active(row["start"], today)
           ~~~~~~^^^^^^^^^^^^^
KeyError: ' pro '
Reveal the answer and explanation

Change parse_row on line 9, not the lookup on line 17, because the fix belongs where the wrong value first appears. parse_row strips the name and the date but not the plan, and probe 1 shows the result in one line: the plan comes back as ' pro ', spaces included. Our post on separating the first symptom from the root cause in service logs draws the same line between where a failure shows up and where it starts.

All three rows carry the flaw, because the line is split on commas and the plan is never stripped: the plans read ' pro ', ' basic' and ' pro'. Editing Ana's row in the test data would only move the error to Ben's row, which raises KeyError: ' basic'.

After the one-line fix the next run starts with FF.F: still three tests that do not pass, but now all three are failed assertions. The KeyError had been hiding them, so the count did not fall even though a real bug was gone.

The probe lines come from probes.py, which starts with from datetime import date and import report; running python3 probes.py in the folder that holds report.py prints all three probes.

# probes.py, probe 1
row = report.parse_row("Ana, pro , 2026-01-15")
print("probe 1  repr(parse_row(...)['plan'])        ->", repr(row["plan"]))

# output
probe 1  repr(parse_row(...)['plan'])        -> ' pro '

# the fix, in parse_row
 def parse_row(line):
     name, plan, start = line.split(",")
     year, month, day = start.strip().split("-")
-    return {"name": name.strip(), "plan": plan, "start": date(int(year), int(month), int(day))}
+    return {"name": name.strip(), "plan": plan.strip(), "start": date(int(year), int(month), int(day))}

# the next run, excerpt
FF.F
...
AssertionError: 60 != 30
AssertionError: 2 != 1
AssertionError: Lists differ: ['Cy', 'Ana'] != ['Ben', 'Cy']
...
FAILED (failures=3)

Round 2: what should you ask before you fix months_active?

Step 1 is to ask what correct means before you edit. The test says Jan 15 to Mar 14 is one full month, but months_active returns 2 because it subtracts month numbers and ignores the day. The tests say nothing about Jan 31 to Feb 28, so ask the interviewer instead of guessing.

Probe 2 reproduces the failure in one line, and python3 -m unittest -k months_active runs only the months test. A day check fixes the cause: if today's day is earlier than the start day, the last month is not complete, so subtract 1. After this change the next run reads ...F, and only the ranking test still fails.

The table shows what the fix changed for four date pairs. Jan 31 to Feb 28 moves from 1 to 0, and no test settles whether that is right: none of the start dates in the tests falls on day 29, 30 or 31. Say which rule you assumed and why when you hand the code back.

# probes.py, probe 2
print("probe 2  months_active(Jan 15, Mar 14)       ->", report.months_active(date(2026, 1, 15), date(2026, 3, 14)))

# output
probe 2  months_active(Jan 15, Mar 14)       -> 2

# the fix, in months_active
 def months_active(start, today):
-    return (today.year - start.year) * 12 + (today.month - start.month)
+    months = (today.year - start.year) * 12 + (today.month - start.month)
+    if today.day < start.day:
+        months -= 1
+    return months

# months_active before and after the fix, for four date pairs
Start   End     Before  After
------  ------  ------  -----
Jan 31  Feb 28  1       0
Jan 31  Mar 1   2       1
Jan 15  Feb 14  1       0
Jan 15  Feb 15  1       1

Round 3: why did the ranking failure look the same after two fixes?

Because the cause was untouched. top_spenders formats each total as a string like '90.00' and sorts the strings, so '90.00' ranks above '132.00' and '30.00' ranks above '132.00'. Fixing the plan and the month count changed the totals underneath, but not the string order, so the failure text stayed identical.

A failure text is a symptom, not a progress bar. Between the second and third runs the totals changed (Ana from 60 to 30, Ben from 144 to 132) while the message did not; the progress line, FF.F and then ...F, and the shorter report were the only signs of progress.

Sort the numbers and format only when you print them. The fourth run prints four dots and OK, and the ranking is Ben, then Cy. Prove it the way step 6 says: rerun every test, then try an input of your own, such as the month-end dates from Round 2.

# the four runs of python3 -m unittest
State                    Run   Not passing
-----------------------  ----  --------------------------------------------------------------
0 as handed over         EF.E  KeyError: ' pro ' (twice); AssertionError: 2 != 1
1 after plan.strip()     FF.F  60 != 30; 2 != 1; Lists differ: ['Cy', 'Ana'] != ['Ben', 'Cy']
2 after the day check    ...F  Lists differ: ['Cy', 'Ana'] != ['Ben', 'Cy']
3 after sorting numbers  ....  nothing; the tally is OK

# the totals under the failing assertion
State  Ana  Ben  Cy  top_spenders(LINES, TODAY, 2)
-----  ---  ---  --  -----------------------------
1      60   144  90  ['Cy', 'Ana']
2      30   132  90  ['Cy', 'Ana']
3      30   132  90  ['Ben', 'Cy']

# probes.py, probe 3
print("probe 3  sorted(['132.00','90.00','30.00'], reverse=True) ->", sorted(["132.00", "90.00", "30.00"], reverse=True))

# output
probe 3  sorted(['132.00','90.00','30.00'], reverse=True) -> ['90.00', '30.00', '132.00']

# the fix, in top_spenders
 def top_spenders(lines, today, n):
     rows = [parse_row(line) for line in lines]
-    totals = [(row["name"], f"{invoice_total(row, today):.2f}") for row in rows]
+    totals = [(row["name"], invoice_total(row, today)) for row in rows]
     ranked = sorted(totals, key=lambda pair: pair[1], reverse=True)
     return [name for name, _ in ranked[:n]]

# the fourth run
$ python3 -m unittest
....
----------------------------------------------------------------------
Ran 4 tests in 0.001s

OK

How does the same bug look in JavaScript?

Python raises on a missing key, so the first bug stops the run with a KeyError. JavaScript reads a missing property as undefined, undefined * 2 is NaN, and JSON.stringify turns NaN into null. The failure surfaces later and farther from the cause, so read what the language does with the bad value.

These probes are one-liners written for this post, not a JavaScript port of report.py, and they cover two of the three bug classes: the unstripped key and the string sort. Probe 2 shows the fix for the key, and probes 3a to 3c show the sort trap and its repair.

The default sort converts elements to strings and compares them, as MDN's Array.sort page describes, so [132, 90, 30].sort() returns [132, 30, 90] and the comparator in probe 3b is needed. Probe 3c reproduces the mock round's ranking bug: sorting strings like '90.00' and '132.00' puts '90.00' first. All three Node.js builds printed the same seven lines.

const PRICES = { basic: 12, pro: 30 };

console.log("probe 1a PRICES[' pro '] * 2              ->", PRICES[" pro "] * 2);
console.log("probe 1b JSON.stringify({ total: NaN })   ->", JSON.stringify({ total: PRICES[" pro "] * 2 }));
console.log("probe 1c (30).toFixed(2) vs NaN.toFixed(2)->", (30).toFixed(2), NaN.toFixed(2));
console.log("probe 2  ' pro '.trim()                   ->", JSON.stringify(" pro ".trim()), PRICES[" pro ".trim()] * 2);
console.log("probe 3a [132, 90, 30].sort()             ->", [132, 90, 30].sort());
console.log("probe 3b [132, 90, 30].sort((a, b) => b - a) ->", [132, 90, 30].sort((a, b) => b - a));
console.log("probe 3c ['132.00','90.00','30.00'].sort().reverse() ->", ["132.00", "90.00", "30.00"].sort().reverse());

$ node js_probes.js
probe 1a PRICES[' pro '] * 2              -> NaN
probe 1b JSON.stringify({ total: NaN })   -> {"total":null}
probe 1c (30).toFixed(2) vs NaN.toFixed(2)-> 30.00 NaN
probe 2  ' pro '.trim()                   -> "pro" 60
probe 3a [132, 90, 30].sort()             -> [ 132, 30, 90 ]
probe 3b [132, 90, 30].sort((a, b) => b - a) -> [ 132, 90, 30 ]
probe 3c ['132.00','90.00','30.00'].sort().reverse() -> [ '90.00', '30.00', '132.00' ]

What should you say out loud in a debugging interview?

Say what you see, what you think it means, what you will test and what you expect to see, one short sentence each. Stating the expected output before a run turns the run into a test of your idea, and a surprise tells you which assumption to drop. The table gives one line per step from the mock round.

These lines are our suggestion, not a script any round expects. If you are stuck, say what you have ruled out and what the next probe would show, so your reasoning stays visible while you think.

Step    Say out loud (our suggestion), with numbers from the mock round
------  ----------------------------------------------------------------------------------
Ask     "What should months_active return for Jan 15 to Mar 14, and for Jan 31 to Feb 28?"
Read    "The key is ' pro ' with a space on each side, and PRICES only has pro and basic."
Shrink  "I'll print repr of the plan that parse_row returns for one line."
Guess   "I expect ' pro ', which would mean parse_row keeps the spaces."
Fix     "I'll strip the plan where the row is built, not where it is looked up."
Prove   "All four tests pass; now I'll try Jan 31 to Feb 28 as an input of my own."

How do you practice debugging interview questions?

Practice on failing code you did not write, with the AI and autocomplete off: run the tests, work through the six steps, and write down the failure text after every change. Then score yourself with the rubric below and repeat the kind of bug you missed. The plan and rubric are our suggestion, not a tested method.

If you have no broken code to hand, swap a broken function and its tests with a colleague, or revert an old fix in your own project so its test fails again. If the code spans several files, our guide to tracing a bug across multiple files shows how to follow one input across each module boundary.

Log every bug you miss with a short class label, as in the bug log below for the mock round. The three were whitespace, boundary and ordering, and the next sitting should start with a bug of the class you missed.

30-minute debugging interview practice plan for one mock round (our suggestion; planned minutes, not measured)
Minutes  Step
-------  ------------------------------------------------------------------------------------------------
3        Ask: read the tests and the code; write what correct means and one question for the author
3        Read: run the suite once; copy each failure text and say what it literally says
12       Shrink, Guess, Fix: one probe, one guess, one change and one rerun per bug, about 4 minutes each
5        Prove: rerun every test, then try one input of your own, such as a month-end date
7        Score: apply the rubric below, log the class of each bug you missed, rewrite the weakest answer

Six-point rubric for each practice round (our suggestion)
Point     You earn it when you...
--------  ----------------------------------------------------------------------------
1 Ask     wrote down what correct means, plus one question, before you edited anything
2 Read    quoted each failure text and said what it literally says
3 Shrink  ran one test or a one-line probe, not only the whole suite
4 Guess   predicted each probe's output before you ran it
5 Fix     changed one thing per rerun, and each change targeted a cause
6 Prove   reran every test after the last fix and tried an input of your own

Bug log for the mock round (a format for your own practice)
Class       Symptom                      Cause                             Fix
----------  ---------------------------  --------------------------------  -------------------------------------
whitespace  KeyError: ' pro '            plan never stripped in parse_row  plan.strip() in parse_row
boundary    AssertionError: 2 != 1       months_active ignores the day     subtract 1 when today.day < start.day
ordering    Lists differ: ['Cy', 'Ana']  totals sorted as strings          sort the numbers, format on output

Can you use ChatGPT or another AI in a debugging interview?

It depends on the round, so ask in advance and follow the rules you are given: some formats may allow an assistant and others may not. Practice with the AI off either way, because the hard part is judging a fix, and a suggested fix is only another guess to test with a probe and a rerun.

The mock round shows why. The plan.strip() fix looks complete because it removes the error, yet the next run still had three tests that did not pass. A fix, from you or from a tool, is done when the whole suite passes and the numbers underneath make sense, not when one message disappears.

If a tool writes the fix, review it like any diff: ask what it changes, run the probe that would show it, and rerun everything. Our code review interview post practices that habit on four diffs.

Debugging interview tips: five quick answers

Should you read the code first or run it first? Run the tests first, so the failure text tells you where to look, then read the line that raised and the code that produced its inputs. In the mock round the exception came from line 17 of report.py and the fault sat on line 9, so the two ends of the data path were the lines worth reading first.

What if you cannot find the bug? Say what you have ruled out, then shrink the problem: run one test with -k, stop at the first failure with -f, print the value just before the failure, or ask what the code should do for one input. Avoid rewriting the function, because in the 1986 study novices frequently added bugs while looking for the original one.

Is a debugging interview the same as a code review interview? No. A code review interview centers on a diff you review and rank, while a debugging interview starts from a failure and asks for the cause. The habits overlap, and our code review interview post has four runnable diffs to practice on.

Do you need a debugger in a debugging interview? Not for the mock round: three one-line probes and four runs of the suite found all three bugs. If a debugger is allowed, use it the same way, to test one guess at a time, and ask which tools your round permits. Print output has its own traps, which our print debugging post covers.

Will practicing this routine get you through a debugging round? We cannot promise any interview result, and formats and scoring differ by company. The routine trains one habit, checking each claim about code with a run, which helps in any format but does not replace learning what your own round includes. Our page on preparing for a coding interview without an assistant covers the wider week.

References and next steps

See how you debug with the AI off

Take Unrust's free diagnostic with AI and autocomplete off: about 14 minutes in one sitting, with no account needed for your first read. Its Debugging skill asks you to locate the broken line and name the root cause, and its Tracing skill asks you to predict what a snippet prints. It is a snapshot of unassisted reasoning on short exercises and cannot predict interview success.

More from the blog