PyCodeItPython trace & interview prep
python

Why Dry-Running Beats LeetCode Rote Memory

Pattern decks fail when interviewers change types, side effects, or control flow.

AA

Ameer Abdullah

Data Science & AI/ML Graduate-GitHub-Dev.to

5 min read

Concept in Simple Words: Memorizing LeetCode patterns is like learning templates. It works great until the interviewer makes a small tweak to the rules. A minor change, like using a generator instead of a list or adding mutable defaults, completely breaks memorized templates. Dry-running is the skill of executing code step-by-step in your head or on paper, allowing you to adapt to any modification.

Deep Walkthrough & Code: Let's look at how a memorized depth-first search (DFS) template can fail if the graph representation has side effects or dynamic attributes:

class Node:
    def __init__(self, val):
        self.val = val
        self.visited = False
        self.neighbors = []

def dfs(node):
    if not node: return
    node.visited = True
    for neighbor in node.neighbors:
        if not neighbor.visited:
            dfs(neighbor)

Step-by-Step Dry Run: If you dry-run this code, you notice that `node.visited` is mutated directly on the nodes. If the same graph is traversed multiple times, or in parallel, the second traversal will fail because `visited` remains `True` from the first traversal. A trace table tracking the visited state would show that nodes are never reset.

Production Level Issue & Fix: Mutating state directly on input nodes is a bad production practice. It causes race conditions in multi-threaded code. The correct fix is to use an independent `visited = set()` to track visited nodes: `if node in visited: return; visited.add(node)`.

Practice what you just learned

Apply these concepts in PyCodeIt's interactive sandbox with real problems.

Start Python Practice

Related Python Tutorials