Skip to contentKEEP THE CRAFTTHE SANCTUARY

Recursion

Define the result of one call, a complete base case and a decreasing argument. Follow descent separately from return, combine independent child results, and choose an explicit stack when Python call depth is unsafe.

1 practice exercise6 interview problems

Recognize it when The input is recursively nested or each instance naturally splits into smaller instances.

Checking your account…

Recursion Code Labs

Trust a Smaller Contract

A recursive function solves the current problem by trusting the same function on a strictly smaller input. Define what one call returns without mentally expanding the entire call tree.

Write the Base Case First

The base case must produce a complete answer without another call. It also identifies the decreasing measure—length, remaining depth, interval size, or unvisited nodes—that proves termination.

Trace Recursive Calls and Returns

Reference
def countdown_trace(n):
    events = []
    def visit(value):
        events.append(["call", value])
        if value > 0:
            visit(value - 1)
        events.append(["return", value])
    visit(n)
    return events
Practice

Implement countdown_trace(n). Return events ["call", n] while descending to zero, then ["return", n] while unwinding. n must be a nonnegative integer.

Public tests

  • Separate descent and unwind

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Recursive Calls and Returns

def countdown_trace(n):
    events = []
    def visit(value):
        events.append(["call", value])
        if value > 0:
            visit(value - 1)
        events.append(["return", value])
    visit(n)
    return events

Distinguish Descent from Unwinding

Predict the event order from the existing countdown Lab for 1. A call stack remembers where to resume; the return events reverse the descent order even though the code has only one recursive call site.

Step Executed statement State Why
Parent call events.append(["call", value]) events=[["call", 1]] The parent starts but cannot yet emit its return.
Smaller child visit(value - 1) value=0 in a new frame The decreasing argument reaches a terminal state.
Base return events.append(["return", value]) last event=["return", 0] The child completes without another call.
Resume parent events.append(["return", value]) last event=["return", 1] Execution resumes after the suspended child call, with parent value still 1.
Print Output
print(countdown_trace(1)) [['call', 1], ['call', 0], ['return', 0], ['return', 1]]

For nested_sum, trust each child return instead of expanding every nested call mentally. Count total entries and maximum nesting separately: they determine work and stack space, respectively.

Separate Work Before and After Return

Work before the recursive call happens while descending; work after it happens while the call stack unwinds. Preorder and postorder behavior differ only in this placement, but their outputs can be completely different.

Sum a Nested List

Reference
def nested_sum(value):
    if isinstance(value, int):
        return value
    return sum(nested_sum(item) for item in value)
Practice

Implement nested_sum(value). value is an integer or a nested list of values. Return the sum of all integers. Nesting must be finite and acyclic.

Public tests

  • Trust the smaller nested contract

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Sum a Nested List

def nested_sum(value):
    if isinstance(value, int):
        return value
    return sum(nested_sum(item) for item in value)

Choose Recursion or Iteration

Use recursion when the data or proof is naturally recursive and depth is safely bounded. Use iteration for a simple linear state transition or potentially deep input. Python has finite call-stack depth and does not optimize tail calls.

Explain It in an Interview

Say: “The call contract is this, the base case handles this smallest input, and every recursive argument decreases this measure.” Then combine returned values and account for both total calls and O(depth) call-stack space.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Countdown trace with n >= 0O(n + 1)O(n + 1)One descent and one return event per frame.
Nested sumO(N)O(N)N counts all visited integer and list entries in an acyclic nested input.

Space

O(depth) frames plus returned trace storage when present.

Assumptions

  • List slicing in recursive calls adds allocation and copying; index ranges avoid that extra work.
  • Repeated branching may produce exponential total calls even when maximum depth is only linear.

Invariants Worth Saying Aloud

  1. Every recursive argument moves toward a defined terminal state.
  2. A returned child value satisfies the same smaller-instance contract.
  3. Parent-local state survives while the child call executes.

When To Use Or Avoid Recursion

Use It When

  • Use recursion when the subproblem contract mirrors a tree or nested structure and depth is bounded.
  • Use iterative state for a long chain or a simple countdown.

Choose Another Tool When

  • A decreasing parameter alone does not guarantee an efficient algorithm; repeated subproblems can multiply calls.
  • Python does not eliminate tail calls, so a long recursive chain still consumes stack frames.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Recursing without reducing the argument

Calling visit(value) again for positive value never approaches the base case. The direct state transition shows no progress.

Prevent it: Reduce the same measure tested by the base case.

Avoid

next_value = value

Use instead

next_value = value - 1

Dropping a child return value

Computing a child sum and ignoring it leaves the parent total unchanged. Calling the helper is not the same as using its answer.

Prevent it: Add the returned child result to the parent aggregate.

Avoid

child_sum = sum(child)

Use instead

total += sum(child)

Rejecting an integer zero base case by truthiness

A nested integer can be zero. if value treats that valid base value as if it were a container, causing iteration over an int.

Prevent it: Check the type or structural base condition rather than truthiness.

Avoid

result = value if value else sum(value)

Use instead

result = value if isinstance(value, int) else sum(value)

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.