π Recursion
One-line summary: Solve a problem by breaking it into smaller instances of itself β the foundation of DFS, divide-and-conquer, backtracking, and tree algorithms.
Diagramβ
Conceptβ
Every recursive function needs:
- Base case β stops the recursion.
- Recursive case β reduces the problem toward the base case.
- Trust the recursion β assume the recursive call returns the correct answer.
Common Patternsβ
Factorialβ
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
Fibonacci (memoised)β
function fib(n, memo = {}) {
if (n <= 1) return n;
if (memo[n]) return memo[n];
return (memo[n] = fib(n - 1, memo) + fib(n - 2, memo));
}
Power (fast exponentiation)β
function power(base, exp) {
if (exp === 0) return 1;
if (exp % 2 === 0) {
const half = power(base, exp / 2);
return half * half;
}
return base * power(base, exp - 1);
}
Pitfallsβ
- Missing base case β infinite recursion / stack overflow
- Redundant subproblem calls β add memoisation
- Deep recursion in JS β stack size ~10k; consider iterative with explicit stack
Practice Problemsβ
Related Topicsβ
- Backtracking β recursion with undo
- Dynamic Programming β memoised recursion
- Trees β most tree algorithms are recursive
β Back to Home Β· Β© sparshjaswal