Loading TechCookies contentβ¦
Recursion is a function that calls itself with a smaller problem. It sounds circular but it works because every recursive call gets closer to a base case β a problem so small it has a direct answer.
Three-part recipe:
function factorial(n: number): number {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case + combine
}
// factorial(4) β 4 * factorial(3) β 4 * 3 * factorial(2) β ... β 24
Missing or unreachable base case β infinite recursion β stack overflow. Before writing the recursive case, write the base case and convince yourself every call moves toward it.
Shrinking the problem expensively. arr.slice(1) copies the whole rest of the array β O(n) per call, O(nΒ²) total. Pass an index instead and the array is never copied:
// β O(nΒ²): every call copies the array
function sum(arr: number[]): number {
if (arr.length === 0) return 0;
return arr[0] + sum(arr.slice(1));
}
// β O(n): same recursion, zero copies
function sumFrom(arr: number[], i = 0): number {
if (i === arr.length) return 0;
return arr[i] + sumFrom(arr, i + 1);
}
Why it matters for DSA: Trees are inherently recursive structures. Every tree algorithm (DFS, BFS helpers, tree DP) uses recursion. Understanding recursion deeply = understanding trees, graphs, and divide-and-conquer.