Core Module
12 min forge
Recursion Basics
Master the art of solving complex problems by breaking them down into smaller, identical sub-problems.
π Recursion: Thinking in Loops
Recursion is a technique where a function calls itself to solve a smaller version of the same problem. It's the foundation for many advanced algorithms like DFS, Merge Sort, and Dynamic Programming.
π‘ The Logic (ELI5)
Think of a Russian Nesting Doll:
- To open the biggest doll, you have to open the one inside it.
- To open that one, you open the next one.
- Eventually, you reach the smallest doll that cannot be opened.
- You then close them all back up.
The "smallest doll" is what we call the Base Case.
π The Deep Dive
The Three Laws of Recursion
- The Base Case: A condition where the recursion stops. Without this, you'll get a "Stack Overflow" error.
- The Recursive Step: The function calling itself with a "smaller" or "closer to base case" input.
- State Management: Knowing what data to pass down and what to return back up.
How the Call Stack Works
When a recursive call is made, the current function's execution is paused, and its state is saved on the "Stack". Only when the child function returns can the parent resume.
π οΈ Code Forge: Recursion Patterns
javascript Standard/** * Classic Example: Factorial (n!) * n! = n * (n-1) * (n-2)... * 1 */ function factorial(n) { // 1. Base Case: smallest possible 'n' if (n <= 1) return 1; // 2. Recursive Step: n * factorial of (n-1) return n * factorial(n - 1); } /** * Visualizing the Call Stack for factorial(3): * -> factorial(3) returns 3 * factorial(2) * -> factorial(2) returns 2 * factorial(1) * -> factorial(1) returns 1 (Base Case) * <- factorial(2) resumes, returns 2 * 1 = 2 * <- factorial(3) resumes, returns 3 * 2 = 6 */ /** * Finding the Sum of an Array recursively */ function recursiveSum(arr, index = 0) { // Base case: we've looked at all elements if (index === arr.length) return 0; // Recursive step: current element + sum of the rest return arr[index] + recursiveSum(arr, index + 1); }
π― Interview Pulse
Recursion vs. Iteration
- Recursion: Easier to read and write for tree-like or complex structures (e.g., File systems).
- Iteration: More memory-efficient as it doesn't build up a call stack.
Pro-Tip
If your recursive solution is too slow due to repeated work (like in Fibonacci), use Memoization (storing results in a Map) to speed it up. This is the first step toward Dynamic Programming!