PDSA Interactive Book
Bonus chapter

Recursion & Backtracking

Calls that call themselves, trees of choices, and undoing a step to try the next one.

After this chapter you can…
  • trace a recursive call and its stack frames
  • write subsets and permutations with choose-explore-un-choose
  • solve N-Queens and explain how pruning helps
  • decide when to avoid recursion in Python

Anatomy of a recursive function

A recursive function solves a problem by calling itself on a smaller version of the same problem. Two parts are always needed:

  • Base case β€” an input so small that the answer is immediate. Without it the calls never stop.
  • Recursive case β€” express the answer using the answer for a smaller input, and make sure each call really moves toward the base case.
Python Β· editable
Expected output: 15

Each call waits for the call below it, so Python keeps a call stack of unfinished calls. total(3) pushes total(3), total(2), total(1), total(0); then the answers flow back up: 0, 1+0, 2+1, 3+3.

Call stack β€” watch calls pile up and unwindInteractive
Predict the output

What does this print?

def f(n):
    if n == 0:
        return "x"
    return f(n - 1) + str(n)
print(f(3))
Check yourself

What happens if a recursive function has no reachable base case?

Recursion as a tree of choices

Draw each call as a node and each recursive call as a child. For problems that ask for all arrangements, the tree is a map of decisions: at every node you choose one of several options, and a leaf is a finished answer.

Take the subsets of [a, b, c]. At each element you make one decision: include it or skip it. Three elements, two choices each: 2Β³ = 8 leaves β€” the 8 subsets. For permutations of 3 items you choose which unused item goes next: 3 Γ— 2 Γ— 1 = 6 leaves.

Decision tree β€” subsets and permutations, one call at a timeInteractive
ProblemLeavesTree width at depth d
subsets of n items2ⁿ2 choices each (include / skip)
permutations of n itemsn!n βˆ’ d unused items remain
combinations C(n, k)n! / (k!(nβˆ’k)!)choose in increasing order
Check yourself

How many subsets does a set of 5 elements have?

Check yourself

How many permutations does a 4-letter word with all different letters have?

Backtracking: choose, explore, un-choose

Backtracking is recursion over a tree of choices, with one extra habit: after exploring a choice you undo it, so the shared state is exactly as it was before you try the next choice.

Put in order

The backtracking template

Python Β· editable
Expected output: [[], ['c'], ['b'], ['b', 'c'], ['a'], ['a', 'c'], ['a', 'b'], ['a', 'b', 'c']]
Python Β· editable
Expected output: [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
Always record a copy

out.append(path) stores a reference to the one list that keeps changing, so every entry ends up empty at the end. Write out.append(path[:]) (or list(path)).

Check yourself

Why do we call path.pop() after the recursive call?

Predict the output

What does this print?

out, path = [], []
def go(i):
    if i == 2:
        out.append(path[:])
        return
    for v in (7, 8):
        path.append(v)
        go(i + 1)
        path.pop()
go(0)
print(out)
Predict the output

What does this (buggy) version print?

out, path = [], []
def go(i):
    if i == 2:
        out.append(path)         # no copy!
        return
    for v in (7, 8):
        path.append(v)
        go(i + 1)
        path.pop()
go(0)
print(out)

N-Queens: backtracking with pruning

Place n queens on an n Γ— n board so none attack another (same row, column or diagonal). One queen per row, so the choice at row r is the column. Instead of trying all nⁿ placements, stop as soon as a queen is attacked β€” that is pruning.

N-Queens β€” watch the search place, fail and backtrackInteractive
Python Β· editable
Expected output: [1, 0, 0, 2, 10, 4, 40, 92]

The three sets make the attack test O(1): squares on the same β†˜ diagonal share r βˆ’ c, and squares on the same ↙ diagonal share r + c.

Check yourself

Two queens at (r1, c1) and (r2, c2) attack along a diagonal exactly when…

Check yourself

How many solutions does the 6-queens puzzle have?

Pruning: the difference between usable and hopeless

Backtracking is exponential in the worst case, so everything depends on cutting branches early. Compare two ways to count subsets of positive numbers that add up to a target:

Python Β· editable
Expected output: (59, 116661) (59, 4323)

With positive numbers, once the running total exceeds the target no extension can ever repair it β€” so the pruned search skips whole subtrees. Good pruning rules are cheap to test and never discard a valid answer. Sorting the input first often makes pruning much stronger (stop the loop when the next number is already too big).

Check yourself

Which rule is a valid prune when all numbers are positive and you need a sum of exactly target?

Check yourself

Which of these are typical backtracking problems?

Python limits and when to avoid recursion

Python allows about 1000 nested calls by default. A recursion that goes n deep for n = 10⁡ raises RecursionError. You have three options:

  • Convert to a loop (when the recursion is just a counter, like total(n) above)
  • Use an explicit stack (depth-first search over a big graph)
  • Raise the limit with sys.setrecursionlimit β€” only when you are sure the depth stays modest, because very deep recursion can crash the interpreter.
Python Β· editable
Expected output: RecursionError at depth 5000 23416728348467685 1000

lru_cache remembers results, so overlapping calls (as in Fibonacci) are computed once β€” that is memoisation, the first half of dynamic programming.

Check yourself

Why does naive recursive Fibonacci take exponential time?

Chapter challenge β€” Recursion & Backtracking

…
Check yourself

Every correct recursive function needs…

Predict the output

What does this print? (type the exact output)

def f(n):
    if n <= 1:
        return 1
    return f(n - 1) * n
print(f(5))
Check yourself

How many subsets of {1, 2, 3, 4} are there (including the empty set)?

Put in order

Order the steps inside the loop of a backtracking function.

Check yourself

A permutation generator stores out.append(path) instead of out.append(path[:]). What goes wrong?

Check yourself

What does pruning do?

Check yourself

How many permutations of 6 distinct items exist?

Check yourself

Which problems fit backtracking?

Practice on LeetCode

Generate-all problems: subsets, permutations, parentheses and N-Queens.

How to practise

Try each problem first with a brute-force idea and estimate its cost, then improve it using this chapter's technique. Links open LeetCode in a new tab; all problems listed are free. Levels follow LeetCode's own labels.

0 / 6 solvedTick a problem when you have solved it β€” saved in this browser.
ProblemLevelPractises
Subsets β†—Mediuminclude / skip decision tree: 2^n leaves
Permutations β†—Mediumchoose an unused item at each level
Combination Sum β†—Mediumchoose-explore-un-choose with pruning on the running total
Generate Parentheses β†—Mediumprune when closes would exceed opens
Letter Combinations of a Phone Number β†—Mediumone choice per digit
N-Queens β†—Hardbacktracking with row, column and diagonal sets

Key takeaways

  • A recursive function needs a base case and a call on a smaller input. The call stack remembers unfinished calls.
  • Draw the calls as a tree of choices: subsets have 2ⁿ leaves, permutations n!.
  • Backtracking = choose, explore, un-choose, and record a COPY of the path when it is complete.
  • Pruning cuts branches that cannot succeed; it is what makes N-Queens and Sudoku practical.
  • Python recursion is limited to about 1000 frames; use loops, an explicit stack or lru_cache (memoisation) when needed.

PDSA Interactive Book Β· Programming, Data Structures and Algorithms using Python (BSCS2002), IIT Madras BS Degree Programme.
Created by Ammar Hashmi Β· Β© 2026. An unofficial study companion β€” the syllabus follows the official course page and the examples are built around the PDSA Online Textbook; lectures by Prof. Madhavan Mukund (CMI). Always cross-check with the official course material.
Found a mistake or have a suggestion? Report it on GitHub β†— Β· Press / to search.