Explain the concept of Recursion and provide an example of its use.

Instruction: Define recursion, explain the base case and progress toward it, and implement factorial for nonnegative integers. Discuss invalid inputs, stack usage, and when iteration or memoization is preferable.

Context: This question assesses the candidate's understanding of recursion, a fundamental concept in algorithms and programming. Candidates should explain how a function calls itself in a controlled fashion and should provide an example, such as calculating factorials or implementing the Fibonacci sequence, to illustrate how recursion can be a powerful tool for certain kinds of problems.

Updated

Example answer

Recursion solves a problem by calling the same function on a smaller instance. It needs a reachable base case and progress toward that case. Tree traversal is a natural application because each subtree has the same structure as the whole tree.

Factorial is a compact illustration: 0! = 1, 1! = 1, and n! = n × (n−1)! for n ≥ 2.

def factorial(n):
    if isinstance(n, bool) or not isinstance(n, int):
        raise TypeError("n must be an integer")
    if n < 0:
        raise ValueError("n must be nonnegative")
    if n <= 1:
        return 1
    return n * factorial(n - 1)

assert factorial(0) == 1
assert factorial(1) == 1
assert factorial(5) == 120

For 5, calls descend to the base case and return through 2 × 1, 3 × 2, 4 × 6, and 5 × 24. There are O(n) calls and O(n) stack depth; the cost of large-integer multiplication grows with the operands. Python imposes a recursion limit, so this teaching example can raise RecursionError for sufficiently large n even though n is mathematically valid. An iterative version avoids linear stack growth; math.factorial is preferable for production factorial calculations.

Recursion is not inherently faster than iteration. Naive recursive Fibonacci repeats work exponentially, whereas memoization or an iterative solution avoids those repeated subproblems. For graph traversal, track visited nodes to avoid cycling indefinitely.

Related Questions