Understand recursive function execution, base cases, call stack frame allocation, and stack overflow limits.
Learn how dynamic arrays achieve O(1) amortized insertion, contiguous memory layout, and geometric doubling strategies.
Recursion is a problem-solving technique where a function solves a smaller sub-instance of the same problem by calling itself.
Every recursive function MUST have two parts:
function factorial(n) {
// Base Case
if (n <= 1) return 1;
// Recursive Step
return n * factorial(n - 1);
}
console.log(factorial(4)); // Output: 24 (4 * 3 * 2 * 1)
Each recursive call allocates a new stack frame in memory storing local variables:
[ factorial(1) -> returns 1 ] ◄── Base Case Reached (Stack Unwinds)
[ factorial(2) -> 2 * 1 ]
[ factorial(3) -> 3 * 2 ]
[ factorial(4) -> 4 * 6 ] ◄── Initial Invocation
Recursive functions consume $O(D)$ auxiliary space on the call stack, where $D$ is the maximum recursion depth.
RangeError: Maximum call stack size exceeded (Stack Overflow!).fib(n) = fib(n-1) + fib(n-2)) runs in horrific $O(2^N)$ exponential time due to repeating identical subproblems. Use memoization or dynamic programming to reduce to $O(N)$!Mastering recursion is required for trees and backtracking. Next, let's explore Backtracking Patterns!