DEV Community

Ankit Kumar
Ankit Kumar

Posted on

Dry run recursion line by line before your interview does it for you

Most recursion bugs I make are not in the idea. They are in the order things happen: which call returns first, what the list looks like when the inner call changes it, why the answer comes back one too big.

Interviewers ask for a dry run for exactly this reason. Here is the method I use, on a small example.

def subsets(nums, i=0, cur=None, out=None):
    if cur is None: cur, out = [], []
    if i == len(nums):
        out.append(cur[:])
        return out
    cur.append(nums[i])
    subsets(nums, i + 1, cur, out)
    cur.pop()
    subsets(nums, i + 1, cur, out)
    return out

print(subsets([1, 2]))
Enter fullscreen mode Exit fullscreen mode

Step 1. Write the call stack as a column, newest call on top. Each row holds i and cur.

Step 2. Move one line at a time. When a call starts, add a row. When it returns, cross it out and go back to the line after the call in the row below.

Step 3. Watch the shared list. cur is ONE list passed down, so cur.append in a deep call changes what every row sees. That is why out.append(cur[:]) copies it; append cur itself and every saved answer ends up empty after the pops.

Doing this on paper for [1, 2] gives 7 calls and the output [[1, 2], [1], [2], []]. Try [1, 2, 3] by hand before running it: 15 calls.

Two things that make the paper version faster:

  • Mark the line each row is waiting on (after first call or after second call). Most confusion is forgetting where a call resumes.
  • Draw the list once and point every row at it with an arrow, instead of copying it into every row. The arrows show the sharing bug at a glance.

If you want to check your paper trace, I built a free browser tool that does the same drawing: it steps through Python or JavaScript code line by line and draws the call stack, variables and lists, no sign-up: https://dsatracker.tech

The habit matters more than the tool. Five minutes of a hand trace on one recursion problem a day is what made base cases stop surprising me.

Top comments (0)