Skip to content

Lesson 15 of 27Talk it through

Debugging Under Pressure

Find a bug calmly with the clock running: say what you expected, read the error properly, bisect the algorithm, fix one thing, and know when to stop.

15 min read0/4 questions

Your code runs, and it prints ['b', 'a']. The answer should be ['a', 'b']. There are twelve minutes left and the interviewer is watching. Most candidates do one of two things here: go silent and stare at the code, or start changing lines to see what happens. Both burn time, and neither shows the interviewer anything they can score.

Debugging under pressure is a method, not a talent. This lesson gives you that method: how to narrate the hunt, how to read an error in Python and JavaScript, how to cut the search space in half, how to fix without breaking something else, and when to stop debugging and talk about the rest.

Narrate the hunt

The interviewer cannot see inside your head. A silent minute of debugging looks the same as a lost minute. So say the bug out loud in a fixed shape:

"Expected ['a', 'b'], got ['b', 'a']. The counts look right, so the problem is at the sorting step. Let me check that."

Expected, got, where. That sentence does three jobs. It confirms you know the right answer (some candidates do not, and debug toward the wrong one). It shows the difference is specific: here, an ordering problem, not a missing item. And it states a hypothesis the interviewer can follow or correct. Often they will nudge you ("are you sure about the tie-break?"), which they cannot do if you are silent.

Keep narrating as you go: "If the sort is the problem, then printing ranked before the slice should show b first. ... It does. So the key is wrong for ties."

Quick check
Your function returns 7 for an input where the answer is 4. Which is the strongest thing to say first?
Need a nudge? A hint rules out a wrong answer.

Notice the trick in that answer: the wrong value is a clue. An answer that equals n suggests a loop that never filtered anything. An answer off by exactly one points at a boundary. Zero or an empty list points at a condition that never fired or a return in the wrong place. Ask "what code would produce exactly this wrong answer?"

Read the error before you read the code

When the code crashes, the error message tells you the type of failure and the exact line. Reading it carefully is the fastest debugging step there is, and under stress people skip it.

A Python traceback lists calls from the outside in, with the most recent call last. So read it from the bottom:

  1. The last line is the exception type and message: IndexError: list index out of range.
  2. The frame just above is where it happened, with the line of code. Recent Python versions also underline the exact expression.
  3. Walk upward only as far as you need to see who called it with what.
Reading a Python traceback, bottom up
  1. Traceback (most recent call last):
  2. line 10, in <module>: next_values([4, 8, 15])your test call
  3. line 7, in next_values: first_after(nums, i)the loop
  4. line 4, in first_after: return nums[i + 1]the crash site
  5. IndexError: list index out of rangewhat went wrong

Start at the bottom. IndexError means an index was past the end (or before the start) of a list.

1/4
Python
import traceback def first_after(nums, i): return nums[i + 1] # no bounds check def next_values(nums): return [first_after(nums, i) for i in range(len(nums))] try: next_values([4, 8, 15])except IndexError: traceback.print_exc() print("---")ages = {"ana": 31}try: ages["bo"] += 1except KeyError as e: print("KeyError:", e) def depth(n): return 0 if n == 0 else 1 + depth(n - 1) try: depth(5000)except RecursionError as e: print("RecursionError:", e)
Output
Press Run (⌘ Enter) to see what happens.

JavaScript stack traces are the other way round: the message comes first, and the first at ... line is where the error was thrown. The message text also depends on the engine. Chrome and Node say Cannot read properties of undefined (reading 'at'), while Safari and Firefox word it differently, so learn what each error means rather than its exact text.

JavaScript
function lastChar(words, i) { return words[i].at(-1);}function depth(n) { return n === 0 ? 0 : 1 + depth(n - 1);}const tests = [ () => lastChar(["cat", "dog"], 2), // index past the end () => { const helpers = {}; return helpers.sum([1, 2]); }, () => depth(1e6), // too deep for the call stack () => lastChar(["cat", "dog"], 1), // the working call];for (const t of tests) { try { console.log("returned", t()); } catch (err) { console.log(err.name + ": " + err.message); }}
Output
Press Run (⌘ Enter) to see what happens.

Note the first case. JavaScript does not raise an error for words[2] on a two-item array; it quietly returns undefined, and the crash happens one step later when you call a method on it. The line that crashed is not always the line with the bug. Ask "where did this undefined come from?"

These are the errors you will see most in interview code, and what they usually mean:

ErrorUsual cause in interview code
Python IndexErrorLoop bound off by one, i + 1 at the last index, empty input
Python KeyErrorReading a count before it exists. Use .get(k, 0), defaultdict or Counter
Python RecursionErrorMissing or unreachable base case, or a correct recursion deeper than the 1000 default limit
Python TypeError: 'NoneType' object ...A function that forgot to return, or lst = lst.sort() (sort returns None)
Python UnboundLocalErrorAssigning to an outer variable inside a nested function without nonlocal
JS TypeError: Cannot read properties of undefinedIndex past the end, missing map key, or a function with no return
JS TypeError: x is not a functionA typo in a method name, or calling a property that is not a function
JS RangeError: Maximum call stack size exceededRecursion with no reachable base case, or too deep for the engine's stack

Neither Python nor JavaScript optimises tail calls, so "make it tail-recursive" does not fix a deep recursion. Convert it to a loop with an explicit stack.

Online assessment verdicts

In an online assessment you get a verdict instead of a traceback. Each one points to a different first check.

Match the pairs0/5 matched

Match each verdict to the first thing to check.

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

Time Limit Exceeded deserves one more sentence: first check whether your algorithm is the right complexity class for n (as covered in Constraints Are Hints). If it is, look for a hidden loop inside a built-in, which Your Language's Interview Toolkit lists. Only then think about constant factors such as fast input.

Binary-search the bug

When the output is wrong and nothing crashed, do not trace from the first line. Your algorithm has stages, or a loop with a known state at each step. Check the state in the middle. If it is right there, the bug is after; if it is wrong, the bug is before. Each check halves the code you have to suspect.

To make that work you need to know what the state should be at the midpoint, which is an invariant from Dry Runs and Invariants: "after the counting phase, every word maps to its count", or "after processing index i, best is the answer for the prefix up to i."

Here is the bug from the opening, found that way.

Python
from collections import Counter def top_k_words(words, k): counts = Counter(words) # phase 1 ranked = sorted(counts, key=lambda w: (counts[w], w), # phase 2 reverse=True) return ranked[:k] # phase 3 words = ["b", "a", "c", "a", "b", "d"]print("got: ", top_k_words(words, 2))print("expected:", ["a", "b"]) # ties broken alphabetically # Bisect the pipeline: check the state after each phasecounts = Counter(words)print("after phase 1:", dict(counts)) # a and b are 2, c and d are 1: correctranked = sorted(counts, key=lambda w: (counts[w], w), reverse=True)print("after phase 2:", ranked) # b before a, wrong here # The fix changes phase 2 onlyfixed = sorted(counts, key=lambda w: (-counts[w], w))print("fixed phase 2:", fixed[:2])
Output
Press Run (⌘ Enter) to see what happens.

The counts were right, so phase 1 is innocent. The ranking was wrong, so the bug is in phase 2: reverse=True reverses both parts of the key, so ties come out in reverse alphabetical order. Negating only the count fixes it.

Predict the outputPython

What does this print?

pairs = [("b", 2), ("a", 2), ("c", 1)]
print(sorted(pairs, key=lambda p: (p[1], p[0]), reverse=True))
Need a nudge? Hints walk you through it.

In an interview, a print at the midpoint is completely acceptable. Label it (print("after phase 1:", counts)) so the output reads clearly, and delete it when you are done.

Fix one thing at a time

Once you find the faulty line, change only that line, rerun the case that failed, then rerun the cases that already passed. Changing three things at once leaves you not knowing which one mattered, and often introduces a new bug that the old cases would have caught.

The strongest temptation under pressure is the rewrite: "let me just redo this loop." Resist it. A rewrite throws away everything that was already right, costs the time you were short of, and usually reproduces the same mistake because your mental model has not changed. Find the specific wrong assumption first.

There is one good reason to start over: when the approach is wrong, not the code. If each fix exposes another failing case, and the failures share a pattern (greedy keeps picking the locally best and losing), the algorithm is wrong. Then say so: "Each fix breaks another case, so I think greedy is not safe here. Let me fall back to the brute force I described, which I know is correct, and optimise from there if time allows." A working slow solution scores far better than a broken fast one.

Put it in order5 steps

Put the debugging loop in order.

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

Time-box the hunt

Debugging can eat an interview. Set yourself a budget: if one bug has cost about five minutes and you have no clear hypothesis, stop and talk.

"I have not found it yet. My best guess is the window update when a repeat is outside the window, and I would check that with abba. Since we are short on time, let me give the complexity and the cases I would test, and I am happy to come back to it."

This is not giving up. You have shown the method, named a concrete hypothesis and a test for it, and protected the parts of the rubric you can still earn: complexity analysis, testing plan, and discussion. Many interviewers will help at this point, because you have made it easy for them.

Debugging someone else's code

Some interviews hand you code you did not write and ask you to find the bugs. The method is the same, with more reading up front:

  1. Read before you run. Say what the code is meant to do and how it is structured, in two sentences.
  2. Reproduce. Find the input that fails, and the smallest version of it.
  3. Form a hypothesis from the evidence, using expected, got, where.
  4. Make the minimal fix and explain why it is correct, not just that the test now passes.
  5. Look for siblings. The same mistake often appears twice, such as an off-by-one in both a loop and a slice.

The Interview Prep course's Debugging Rounds lesson covers that format in detail, including the larger, multi-file version some companies use.

Key terms
expected, got, where
The three-part sentence that starts every bug hunt: the right answer, the actual answer, and where you suspect the difference starts.
traceback
Python's report of the calls active when an exception was raised, listed oldest first. Read it from the bottom.
stack trace
JavaScript's version of a traceback. The message comes first and the top frame is where the error was thrown.
bisecting a bug
Checking the program's state at the midpoint against the invariant, so each check halves the code you suspect.
time box
A fixed budget, about five minutes in an interview, after which you state your hypothesis and move on.
Time Limit Exceeded
An online judge verdict meaning the code was too slow: usually the wrong complexity class, or a hidden O(n) built-in in a loop.