Foundations
Recursion
Master the mental model of recursion—base cases, recursive calls, call stack execution, and tree traversal intuition.
1. Introduction
What is Recursion?
Recursion is a programming technique where a method or function calls itself to solve a smaller sub-problem of the same problem.Why is it Important?
Many complex data structures—such as Trees, Graphs, Tries, and Divide & Conquer algorithms (MergeSort, QuickSort)—are naturally recursive. Writing recursive solutions often breaks down complex multi-step logic into clean, concise code.Where is it Used?
... ).
2. Mental Model
Imagine a Line of People in a Movie Theater.
You are sitting in the back row (Person 4) and want to know your row number, but it's too dark to count. 1. You ask the person in front of you (Person 3): "What row are you in?" 2. Person 3 asks Person 2. Person 2 asks Person 1. 3. Person 1 is in the front row and knows immediately: "I am in Row 1!" (Base Case). 4. Person 1 tells Person 2: "I am in Row 1." 5. Person 2 adds 1: "I must be in Row 2!" and tells Person 3. 6. Eventually, Person 3 tells you: "I am in Row 3!" You add 1 and conclude: "I am in Row 4!"
Recursion pushes questions down until someone knows the direct answer (Base Case), then passes results back up the chain!
3. Concept: Anatomy of a Recursive Function
Every valid recursive function must have two mandatory components:
1. Base Case (The Stop Condition)
The simplest possible condition that can be answered directly without further recursive calls.2. Recursive Step (The Progress Condition)
The function calls itself with a smaller or simpler input, moving closer to the base case.Trace Example: Factorial of N (N!)
Factorial of 3 (3! = 3 × 2 × 1 = 6):4. Visuals
Call Stack Lifecycle for factorial(3)
5. Real-World Examples
getFolderSize() on each subfolder.6. Interview Perspective
How Interviewers Ask This Topic
Interviewers use recursion to test tree traversals (DFS), combinations, and backtracking.Common Mistakes
n <= 1 leads to infinite recursion (factorial(-1), factorial(-2)) causing StackOverflowError.> 2. Not Making Progress: Callingsolve(n)instead ofsolve(n - 1)will loop forever.
> 3. Redundant Calculations: In plain recursive Fibonaccifib(n-1) + fib(n-2), the same values are recomputed millions of times, blowing up complexity toO(2ⁿ)!