Chapters in this video
- 0:00 Intro
- 0:19 What is recursion?
- 0:47 Cinema queue example
- 1:09 Factorial in Java
- 1:32 The call stack
- 1:55 Fibonacci & the recursion tree
- 2:20 Memoization
- 2:44 Complexity of recursion
- 3:10 3 questions for any recursion
- 3:32 Quiz
- 3:52 Practice list
- 4:03 Recap
In simple words
Recursion is a function that calls itself on a smaller version of the same problem. Every recursive function has two parts:
1. Base case — the smallest input where you already know the answer (stop here).
2. Recursive case — break the problem into a smaller piece, call yourself, and combine the result.
The trick is to trust that the smaller call works, just like you trust a library method.
Think of it like…
You are in a cinema queue and want to know your position. You ask the person in front, who asks the person in front of them… The first person says "1" (base case). Each person adds 1 and passes it back.
You are in a cinema queue and want to know your position. You ask the person in front, who asks the person in front of them… The first person says "1" (base case). Each person adds 1 and passes it back.
Key ideas
- Each call is stored on the call stack. Too deep (roughly 10,000+ in default Java) →
StackOverflowError. - Draw the recursion tree to find complexity: (number of calls) × (work per call).
- Naive Fibonacci makes ~2ⁿ calls because it solves the same subproblem again and again → fix with memoization (store answers). This is the doorway to Dynamic Programming.
- Java does not optimize tail recursion; convert very deep recursion to a loop or an explicit stack.
- Recursion is the backbone of trees, graphs (DFS), backtracking, divide & conquer, and DP.
Operations & cost
| Example | Time | Space (stack) |
|---|---|---|
| factorial(n) | O(n) | O(n) |
| naive fib(n) | O(2ⁿ) | O(n) |
| memo fib(n) | O(n) | O(n) |
| fast power(x, n) | O(log n) | O(log n) |
Java code
// Factorial long fact(int n) { if (n <= 1) return 1; // base case return n * fact(n - 1); // recursive case } // Fibonacci with memoization: O(n) instead of O(2^n) long[] memo = new long[100]; long fib(int n) { if (n <= 1) return n; if (memo[n] != 0) return memo[n]; return memo[n] = fib(n - 1) + fib(n - 2); } // Fast power: x^n in O(log n) double myPow(double x, long n) { if (n == 0) return 1; if (n < 0) return 1 / myPow(x, -n); double half = myPow(x, n / 2); return (n % 2 == 0) ? half * half : half * half * x; }
Spot it when
- The problem is defined in terms of itself (tree, nested structure, 'for each choice…').
- You can say: 'if I knew the answer for n-1, I could get n'.
Practice problems
| Problem | Level |
|---|---|
| Fibonacci Number | Easy |
| Reverse Linked List | Easy |
| Merge Two Sorted Lists | Easy |
| Pow(x, n) | Medium |
| K-th Symbol in Grammar | Medium |
Interview tip
★ On the whiteboard, draw the recursion tree for n = 3 or 4. It makes the complexity obvious and shows the interviewer how you think.