PyCodeItPython trace & interview prep
DashboardMastery MapSQL PracticeDailyInterviewBlogLeaderboardCommunity

Loading PyCodeIt workspace...

PyCodeIt

Free interactive learning platform for Python code tracing, SQL queries, and technical interviews. Built for bootcamp grads, computer science students, and engineers.

Python Practice

  • Learning Center
  • For loop tracing
  • List tracing
  • Dictionary tracing
  • Decorators practice
  • Python Tracing Guide
  • Python Output Questions

SQL Practice

  • SQL Fundamentals
  • Relational JOINs
  • Window Functions
  • CTEs & Set Operators
  • SQL JOINs Guide
  • Window Functions Guide

Legal

  • About
  • Contact
  • Privacy Policy
  • Terms of Service

© 2026 PyCodeIt 2026. All rights reserved.

Tracing Recursion: factorial(n)

Recursion creates multiple stack frames. We show a frame-by-frame trace and describe how memoization reduces repeated work.

def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

print(factorial(4))  # expected 24

Frame trace

  1. Frame1: factorial(4) calls factorial(3)
  2. Frame2: factorial(3) calls factorial(2)
  3. Frame3: factorial(2) calls factorial(1)
  4. Frame4: factorial(1) returns 1; Frame3 returns 2; Frame2 returns 6; Frame1 returns 24

Memoization tip

from functools import lru_cache

@lru_cache(maxsize=None)
def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n-1)

Memoization stores previously computed results and prevents repeated recursive work. For factorial, it isn't strictly necessary, but for Fibonacci-style trees it reduces O(2^n) to O(n).

Companion video:
TRACING RECURSIVE ALGORITHMS: How to use a trace table and a tree to ...
Timestamps: 00:00 Introduction · 02:10 Single-call trace table · 06:30 Two-call tree trace
Return to Practice