Recursion and Divide and Conquer
Break problems into smaller copies of themselves with a clear base case, trace the call stack, and apply divide and conquer.
Beginner · about 6 hours · difficulty 3/5
Learn first: Complexity Analysis
Recursion solves a problem by solving smaller instances of the same problem. It is the foundation for trees, graphs, backtracking and dynamic programming, so time spent here pays off everywhere.
The recipe
- Base case: the smallest input you can answer directly.
- Recursive case: assume the function already works for smaller inputs (the "leap of faith") and combine those results.
- Progress: every call must move toward a base case, or you get infinite recursion and a stack overflow.
Tracing and cost
Draw the recursion tree. Time is roughly the number of nodes times the work per node; space is the maximum depth of the call stack. Naive Fibonacci has about 2^n nodes, which is why it is slow and why memoization (later, in DP) helps so much.
Divide and conquer
Split the input, solve each part recursively, combine. Examples: merge sort, quick sort, binary search, fast power, counting inversions, and closest pair of points. The combine step usually determines the complexity.
Pitfalls
- Returning nothing from a branch in a function that should return a value.
- Mutating shared state without undoing it (a classic backtracking bug).
- Very deep recursion (10^5 levels) can overflow the stack in Java and Python; switch to iteration if needed.
Good enough to move on: you can write recursive power, reverse a string, generate all subsets and print the recursion tree for small inputs by hand.
Key concepts
- Base case and recursive case
- Call stack and recursion tree
- Time and space of recursive code
- Divide and conquer paradigm
- Tail recursion and iteration
- Counting inversions: Merge-sort based
Mini project
Solve 7 problems recursively: Pow(x, n), Reverse Linked List (recursive), Fibonacci with and without memo, Tower of Hanoi, K-th Symbol in Grammar, Merge Two Sorted Lists, and Count Inversions of an array.
Check yourself
What is the space complexity of a recursive function that makes one recursive call on n - 1, and why is it not O(1)?
Free resources
- LeetCode Explore: Recursion I (LeetCode)
- Jeff Erickson, Algorithms (Ch. 1) (UIUC)
- Introduction to recursion (GeeksforGeeks)