Skip to content

Lesson 9 of 32Technical rounds

Debugging Rounds

Find and fix planted bugs in an unfamiliar repo with a calm, visible method: reproduce, hypothesise, narrow, fix, and lock it in with a test.

18 min read0/4 questions

"Here is a small service. Some tests fail and a customer reported a bug. You have 50 minutes." That is the debugging round, sometimes called a bug bash, and it is spreading because it tests what engineers actually spend their days doing. Most real work is not writing a new algorithm. It is figuring out why existing code does the wrong thing, in a codebase you did not write, without breaking anything else. The round rewards a method more than brilliance: candidates who flail through files and change things at random run out of time, while candidates who narrow the problem step by step usually fix more bugs, even if they are slower typists. This lesson is the interview-round version of the skill. Debugging Under Pressure covers bugs in your own solution during a coding round; here the code belongs to someone else.

The format

The details vary, but most debugging rounds share a shape:

  • An unfamiliar repo, usually 200 to 2,000 lines, with a test suite. Often in your choice of a few languages.
  • Several bugs of increasing difficulty. The first is usually a quick warm-up (a wrong operator), the last is subtle (state shared between calls, an async ordering bug, a timezone edge).
  • Signals of where to look: failing tests, a bug report in plain English ("customers in Berlin see yesterday's date on their receipt"), or both.
  • 45 to 60 minutes, with an interviewer watching your screen. You can usually run code, add prints and use a debugger.

Nobody expects you to fix every bug. The rubric rewards how many you fix, but also how you got there: did you reproduce before changing code, could you explain the root cause, did you add a test, and did you keep the interviewer informed? A candidate who fixes three bugs with clear reasoning and regression tests often beats one who fixes four by trial and error.

The first five minutes: triage

Do not open the first failing test and dive in. Get the map first.

  1. Run the whole suite and read the summary. Note how many tests fail and their names.
  2. Group the failures. Five failing tests might be one bug. Tests named test_paginate_* failing together point at one function.
  3. Read the bug report literally. "Yesterday's date" and "Berlin" are two clues: a date, and a timezone ahead of UTC.
  4. Pick an order. Start with a quick win to build momentum and learn the codebase, then go for the bug with the biggest blast radius: the one that corrupts data, charges money twice or leaks between users matters more than a wrong label.

Say your triage out loud: "Seven tests fail in three groups. Pagination looks like a warm-up, I'll take it first. The tagging failures only appear when the whole file runs, which smells like shared state, so I'll come back to it with more context."

The debugging loop

Every bug, easy or hard, goes through the same loop. The discipline that interviewers look for is one hypothesis at a time: you change one thing, for a reason you said out loud, and you check the result.

The debugging loop
Reproduce: a failing test or commandReproducea failing test or commandRead: assertion and stack traceReadassertion and stack traceHypothesise: one specific guessHypothesiseone specific guessNarrow: print, breakpoint, bisectNarrowprint, breakpoint, bisectFix: smallest change at the rootFixsmallest change at the rootLock in: regression test, full suiteLock inregression test, full suitetest itwrong guessroot cause found

Reproduce first. Find or write the smallest test or command that shows the bug. Without it you cannot tell whether a change helped.

1/7

Reading a failure well is half the battle. An assertion that says expected [4, 5, 6], got [4, 5] already tells you the shape of the bug: one item short at the end. A stack trace tells you where. In Python, read it bottom up: the last line is the exception, the frames above are the path that got there, and the frame you care about is usually the lowest one in the project's code, not in the standard library. In Node it is the reverse: the top frame is where it was thrown.

Narrowing is binary search on the code path. If data is right at the start of a pipeline and wrong at the end, print it at the middle. Right there? The bug is in the second half. Each print halves the search. The same idea applies across history: if the bug is new and the suite passed last week, git bisect finds the commit that broke it in about log2(n) steps. In an interview you rarely run bisect, but saying "if this were a regression I'd bisect it" shows you know the tool (Git Archaeology: Bisect, Blame and Reflog covers how).

Put it in order6 steps

A test fails in a repo you have never seen. Put your steps in order.

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

Finding your way around

You cannot fix what you cannot find. Reading Code You Didn't Write in the Engineering at Work course covers this at job scale; in a 50-minute round, three moves cover most navigation in a small repo:

  • Search for the symbol. Search for the function name from the stack trace to find its definition and every caller. Your editor's "go to definition" and "find references" are faster than reading folders.
  • Follow the call chain from the test inwards: the test calls a route, the route calls a service, the service calls a helper. Stop at the first layer where the data goes wrong.
  • Read the tests as documentation. A test called test_free_shipping_at_threshold tells you the rule is "at the threshold counts", which the function's docstring might not.
grep -rn "def paginate" .grep -rn "paginate(" --include="*.py" .git log --oneline -5 -- shop/orders.py

git log on a file shows who touched it recently. In a real incident the most recent change to the broken function is the first suspect.

A practice bug bash

Here is a small module with its tests. Four of the five tests fail. Before you change anything, read each failure message and say your hypothesis. Then fix one bug at a time and run again. Do not change the tests: they describe the intended behaviour.

Pythonbug_bash.py
from datetime import datetime, timedelta, timezone # ---- shop/orders.py (the code under test) ---- def paginate(items, page, per_page): """Return one page of items. Pages are 1-based.""" start = (page - 1) * per_page return items[start:start + per_page - 1] def add_tag(tag, tags=[]): """Return the tag list with the new tag added.""" tags.append(tag) return tags def ships_free(total_pence): """Orders of 50 pounds or more ship free.""" return total_pence > 5000 def order_day(placed_at_utc, utc_offset_hours): """The calendar day the customer saw when they ordered.""" return placed_at_utc.date() # ---- tests/test_orders.py ---- def test_paginate_second_page(): got = paginate(list(range(1, 11)), page=2, per_page=3) assert got == [4, 5, 6], f"got {got}" def test_add_tag_fresh_list(): got = add_tag("gift") assert got == ["gift"], f"got {got}" def test_add_tag_again_fresh_list(): got = add_tag("sale") assert got == ["sale"], f"got {got}" def test_free_shipping_at_threshold(): assert ships_free(5000) is True, "5000 should ship free" assert ships_free(4999) is False, "4999 should not" def test_order_day_in_customer_timezone(): late = datetime(2026, 1, 31, 23, 30, tzinfo=timezone.utc) got = str(order_day(late, utc_offset_hours=2)) assert got == "2026-02-01", f"got {got}" failed = 0for name, fn in list(globals().items()): if name.startswith("test_"): try: fn() print("PASS", name) except AssertionError as e: failed += 1 print("FAIL", name, "->", e)print(f"{failed} failed")assert failed == 0, "fix the bugs until every test passes"
Output
Press Run (⌘ Enter) to see what happens.

Notice what each failure message gives you before you read a line of the function:

  • got [4, 5] instead of [4, 5, 6]: right start, one short at the end. That is an off-by-one in the slice end.
  • test_add_tag_fresh_list passes but the second tag test gets ['gift', 'sale']. Data from one call leaked into the next. A test that passes alone and fails in a suite almost always means shared state: here, a mutable default argument, which Python creates once when the function is defined.
  • 5000 should ship free: the boundary is wrong. Wrong comparison operator, > where the rule says "or more".
  • got 2026-01-31: 23:30 UTC is already 01:30 the next day at UTC+2. The function ignores the offset, a timezone bug. This is the "Berlin customers see yesterday's date" report.
Fixes and why each one is the root cause
Pythonbug_bash_fixed.py
from datetime import datetime, timedelta, timezone def paginate(items, page, per_page): start = (page - 1) * per_page return items[start:start + per_page] # slice end is exclusive already def add_tag(tag, tags=None): tags = [] if tags is None else tags # a new list per call tags.append(tag) return tags def ships_free(total_pence): return total_pence >= 5000 # "or more" means >= def order_day(placed_at_utc, utc_offset_hours): local = placed_at_utc.astimezone(timezone(timedelta(hours=utc_offset_hours))) return local.date() # convert, then take the date got = paginate(list(range(1, 11)), page=2, per_page=3)assert got == [4, 5, 6], gotassert add_tag("gift") == ["gift"] and add_tag("sale") == ["sale"]assert ships_free(5000) is True and ships_free(4999) is Falselate = datetime(2026, 1, 31, 23, 30, tzinfo=timezone.utc)assert str(order_day(late, 2)) == "2026-02-01"print("all 5 tests pass")
Output
Press Run (⌘ Enter) to see what happens.

Each fix is one small change at the place the behaviour goes wrong. A symptom patch would be something like if page == 2: ... or tags.clear() at the start of the test. Both make the test green and leave the bug for the next caller. In real code, prefer a proper time zone name such as zoneinfo.ZoneInfo("Europe/Berlin") over a fixed offset, because offsets change with daylight saving time.

The same kinds of bugs are planted in JavaScript rounds, with two favourites of their own. Run this, then fix it:

JavaScriptlogin.test.js
// ---- src/users.js ----const users = new Map([ [1, { id: 1, active: true }], [2, { id: 2, active: false }],]); async function getUser(id) { await new Promise((resolve) => setTimeout(resolve, 5)); // pretend database call return users.get(id) ?? null;} async function canLogIn(id) { const user = getUser(id); return Boolean(user && user.active);} // ---- src/prices.js ----function cheapestFirst(prices) { return [...prices].sort();} // ---- tests ----const tests = { "inactive user cannot log in": async () => (await canLogIn(2)) === false, "unknown user cannot log in": async () => (await canLogIn(99)) === false, "active user can log in": async () => (await canLogIn(1)) === true, "prices sort cheapest first": async () => cheapestFirst([1200, 350, 99]).join(",") === "99,350,1200",}; let failed = 0;for (const [name, test] of Object.entries(tests)) { const ok = await test(); if (!ok) failed++; console.log(ok ? "PASS" : "FAIL", name);}console.log(`${failed} failed`);if (failed > 0) throw new Error("fix the bugs until every test passes");
Output
Press Run (⌘ Enter) to see what happens.

The login bug is a missing await: user is a Promise, which is truthy, and user.active is undefined, so everyone is refused. The nasty part is that two of the three login tests pass by accident, because "refuse" was the right answer for them. When some tests pass, do not assume the code is mostly right; ask whether they pass for the right reason. The fix is const user = await getUser(id);. The sort bug is the classic one: with no comparator, Array.prototype.sort compares values as strings, so "1200" comes before "350". The fix is .sort((a, b) => a - b).

Predict the outputPython

What does this print?

def add(x, acc=[]):
  acc.append(x)
  return len(acc)

print(add(1), add(2), add(3, []), add(4))
Need a nudge? Hints walk you through it.

The usual suspects

Interviewers plant the same families of bugs because they are the ones that hurt in production. Knowing the list lets you form good hypotheses fast.

Bug familyTypical symptomWhere to look
Off-by-oneOne item missing or extra, last page emptySlice ends, range bounds, < vs <=, 0- vs 1-based pages
Shared mutable statePasses alone, fails in the suite; data leaks between usersMutable defaults, module-level caches, class attributes, test fixtures not reset
Missing await[object Promise], undefined fields, things happen "out of order"Any call to an async function without await, forEach with an async callback
Wrong comparisonBoundary values behave wrongly> vs >=, == vs is, string vs number comparison
Dates and time zonesWrong day near midnight, off by an hour twice a yearNaive vs aware datetimes, .date() before converting, fixed offsets instead of zone names
Stale closure (React)A value "stuck" at its first renderEffects and callbacks that read state with an empty dependency array

The React one is worth seeing, because it appears in frontend debugging rounds:

Ticker.tsx
useEffect(() => {
  const id = setInterval(() => setCount(count + 1), 1000); // count is always 0 here
  return () => clearInterval(id);
}, []);

The interval callback closed over count from the first render, so the display goes to 1 and stays there. Use the updater form, setCount((c) => c + 1), which always receives the latest value.

Match the pairs0/5 matched

Match each symptom to the most likely bug family.

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

Talk while you hunt

Silent debugging looks like being lost, even when you are not. The interviewer can only credit reasoning they can hear. Use a simple pattern: expected, actual, next check.

"The test expects three items and gets two, with the right first item. So the start index is fine and the end is short. I'll check the slice end. Python slices already exclude the end, so the - 1 is removing an item. That's the bug."

Equally important, say what you ruled out: "I checked whether the input list was already short. It has ten items, so the bug is inside paginate, not in the caller." Ruling things out is real progress, and it lets the interviewer nudge you if you are about to go down a dead end.

When you are stuck for more than a few minutes on one bug, say so and choose: "I've spent five minutes on the tagging bug. I'll note what I know, move on to the timezone one, and come back." Parking a bug is a sign of good judgment in a timed round, not a failure.

Quick check
Three bugs remain with 15 minutes left: a misaligned label, a report total that is off by one cent on some orders, and a cache that can return one user's cart to another user. Which do you tackle first?
Need a nudge? A hint rules out a wrong answer.

Tools at a glance

You do not need every debugger feature, but you should be able to stop the program and look around without fumbling. The Debugging Python and Errors and Debugging lessons cover the tools in depth. For the round, these are enough:

  • Python: put breakpoint() on a line to drop into pdb. Then p expr prints a value, n runs the next line, s steps into a call, c continues, w shows where you are in the stack, l lists the code around you. pytest -x --pdb stops at the first failure and opens the debugger right there.
  • Node: node --inspect-brk app.js pauses on the first line and lets Chrome DevTools or your editor attach. A debugger; statement acts as a breakpoint whenever a debugger is attached.
  • Browser: DevTools Sources panel for breakpoints, the Network panel to see whether a request was even sent and what came back, and the Console for errors.

A well-placed print is a perfectly good tool too. Interviewers care that you gather evidence, not which tool you use. Remove the prints before you finish.

Key terms
bug bash
An interview round, or team exercise, where you find and fix several planted bugs in an unfamiliar codebase within a time limit.
root cause
The underlying mistake that produces a bug, as opposed to the symptom where it shows up.
regression test
A test that fails while a bug exists and passes once it is fixed, so the bug cannot quietly return.
blast radius
How much damage a bug can do: how many users, how much data or money, and whether it crosses security boundaries.
mutable default argument
A Python default like [] or {} that is created once when the function is defined and shared by every call that uses it.
git bisect
A Git command that binary-searches commit history to find the commit that introduced a bug.
stale closure
A function that captured an old value of a variable, such as React state from an earlier render, and keeps using it.