๐๏ธ Day 16: Recursion
๐ง Concept Deep Dive
Recursion is a method of solving problems where a function calls itself.
A recursive function typically solves a small piece of the problem and delegates the rest to itself.
To be valid, every recursive function must follow two rules:
- Base Case โ the condition to stop recursion
- Recursive Case โ how the problem is reduced and the function calls itself
๐ก๏ธ Think Like a Stack
Each recursive call is added to the call stack, and the function pauses until the recursive call finishes. After reaching the base case, calls start unwinding from the stack.
๐ฆ Stack Trace Example:
factorial(3)
-> 3 * factorial(2)
-> 2 * factorial(1)
-> 1 (base case)๐ Classic Recursion Pattern
function recurse(problem: Problem): ReturnType {
if (baseCase(problem)) {
return baseResult;
}
// reduce the problem
return combine(
currentWork,
recurse(smallerProblem)
);
}๐ก Example: Factorial
function factorial(n: number): number {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive call
}๐ช Example
Input: factorial(5)
Output: 120
Explanation:
5 * 4 * 3 * 2 * 1 = 120๐ก Example: Fibonacci
function fibonacci(n: number): number {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}๐ช Example
Input: fibonacci(6)
Output: 8โ ๏ธ Note: This has exponential time complexity. Use memoization (covered later) to improve.
๐ง Real-world Analogy
Recursion is like stacking dinner plates.
- Every plate you stack is like a function call.
- When you're done stacking (base case), you start removing them in reverse order โ just like unwinding the recursive stack.
๐ Big O Complexity
| Function | Time Complexity | Space Complexity (stack) |
|---|---|---|
| Factorial | O(n) | O(n) |
| Fibonacci (naive) | O(2โฟ) | O(n) |
๐ช LeetCode-style Homework
Problem: Reverse a String (recursive)
Write a function to reverse a string using recursion.
function reverseString(str: string): string {
if (str.length <= 1) return str;
return reverseString(str.slice(1)) + str[0];
}Example
Input: "hello"
Output: "olleh"โ ๏ธ Common Pitfalls
- Missing a base case causes infinite recursion (stack overflow)
- Forgetting to return the result of the recursive call
- Not reducing the problem each time
๐ Summary
- Recursion solves a big problem by breaking it into smaller versions of itself
- Every recursion needs a base case
- Stack memory is a major constraint
- Learn to visualize how recursion flows
๐ฎ Up Next
โถ๏ธ Day 17: Backtracking