Junior — Middle
Explain the concept of tail recursion and how it differs from regular recursion.
sobes.tech AI
Answer from AI
Tail recursion is a special case of recursion where the recursive call is the last operation in the function, meaning no further computations are performed after it. This allows the compiler or interpreter to optimize calls by replacing recursive calls with loops, thereby saving stack memory.
In regular recursion, additional operations may be performed after returning from the recursive call, causing the call stack to grow with each call.
Example of tail recursion in C++:
int factorialTail(int n, int acc = 1) {
if (n == 0) return acc;
return factorialTail(n - 1, n * acc);
}
// Call: factorialTail(5) will return 120
Here, the recursive call factorialTail is the last statement in the function, which allows for recursion optimization.