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.
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."
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:
- The last line is the exception type and message:
IndexError: list index out of range. - The frame just above is where it happened, with the line of code. Recent Python versions also underline the exact expression.
- Walk upward only as far as you need to see who called it with what.
Start at the bottom. IndexError means an index was past the end (or before the start) of a list.
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.
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:
| Error | Usual cause in interview code |
|---|---|
Python IndexError | Loop bound off by one, i + 1 at the last index, empty input |
Python KeyError | Reading a count before it exists. Use .get(k, 0), defaultdict or Counter |
Python RecursionError | Missing 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 UnboundLocalError | Assigning to an outer variable inside a nested function without nonlocal |
JS TypeError: Cannot read properties of undefined | Index past the end, missing map key, or a function with no return |
JS TypeError: x is not a function | A typo in a method name, or calling a property that is not a function |
JS RangeError: Maximum call stack size exceeded | Recursion 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 each verdict to the first thing to check.
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.
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.
What does this print?
pairs = [("b", 2), ("a", 2), ("c", 1)]
print(sorted(pairs, key=lambda p: (p[1], p[0]), reverse=True))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 the debugging loop in order.
- Tap the steps below in the right order.
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:
- Read before you run. Say what the code is meant to do and how it is structured, in two sentences.
- Reproduce. Find the input that fails, and the smallest version of it.
- Form a hypothesis from the evidence, using expected, got, where.
- Make the minimal fix and explain why it is correct, not just that the test now passes.
- 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.
- 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.