
Read it once, completely
Resist the urge to point at the first suspicious line. Read from top to bottom and say out loud what each part is for. Half the time you find the bug during this pass, and you find it with the context you need to explain it.
Say what it should do
State the expected behavior in one sentence, and ask the interviewer to confirm it. A bug is a difference between expected and actual. If you do not have the expected side, you are only reviewing style.
Walk one input through
Pick a small, concrete input and trace it line by line, writing down the value of each variable. The line where your written value stops matching what the code needs is the bug, or sits right next to it.
Check the boring causes first
- Units. Seconds against milliseconds, bytes against kilobytes, cents against whole currency.
- Boundaries. The first item, the last item, the empty list, less-than against less-than-or-equal.
- State that never resets, or that is shared between calls.
- The missing limit. A value that grows forever because nothing caps it.
- The wrong variable in a copied line.
An example of the first one
allow(userId: string): boolean {
const now = Date.now();
const bucket = this.buckets.get(userId) ?? { tokens: this.capacity, updatedAt: now };
const elapsed = now - bucket.updatedAt; // milliseconds
bucket.tokens += elapsed * this.refillPerSec; // per second
bucket.updatedAt = now;
if (bucket.tokens < 1) return false;
bucket.tokens -= 1;
this.buckets.set(userId, bucket);
return true;
}This rate limiter refills a thousand times too fast, because the elapsed time is in milliseconds and the refill rate is per second. It has a second bug of the list above: nothing caps the tokens at the capacity, so an idle user can save up a burst of any size.
Fix the smallest thing, then say how you would prove it
Change as little as possible: divide by a thousand, add the cap. Then name the test you would write, with the input and the expected result. Interviewers often care more about that sentence than about the fix.