What is Tail Recursion, and how does it differ from non-tail recursion?

Instruction: Explain the concept of tail recursion and compare its benefits over traditional recursion.

Context: This question tests the candidate's knowledge of tail recursion, a special case of recursion where the recursive call is the last operation in the function.

Updated

Official answer

A recursive call is in tail position when its result is returned directly with no pending work in the caller. In factorial, return n * factorial(n-1) is not tail recursive because multiplication remains after the call returns.

An accumulator moves that multiplication before the next call:

def factorial_tail(n, acc=1):
    if not isinstance(n, int) or n < 0:
        raise ValueError('n must be a nonnegative integer')
    if n == 0:
        return acc
    return factorial_tail(n - 1, acc * n)

With the default accumulator this computes n!. The final operation is the recursive call, not the multiplication used to prepare its arguments.

A language/compiler that optimizes this tail call can reuse the control stack frame. That does not make the growing result constant-size, nor does source-level tail recursion guarantee the optimization. Standard Python does not eliminate these recursive frames; this example still has O(n) call depth and can hit the recursion limit. For large n in Python, use a loop or the standard factorial function. In another language, verify its exact tail-call rules rather than inferring them from the language name.

Related Questions