Recursion, trees and heaps · core
Recursion
A recursive function solves a small case directly (the base case) and calls itself on a smaller input, and every call waits on the call stack. So always state the base case, the shrinking step and the depth limit.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Three parts: base case, recursive case on a smaller input, combine the results.
- The call stack: each call keeps its own local variables until it returns; code after the recursive call runs on the way back up (post-order).
- Memoisation: store the result of each argument in a hash map (Python functools.cache, Java HashMap, C++ unordered_map or a vector) when the same call repeats (fib, grid paths). It turns exponential time into polynomial time.
- Depth limits: Python about 1000 calls by default (RecursionError), Java a StackOverflowError after some thousands of calls, C++ a crash. For deep data, change the recursion to a loop with an explicit stack.
- Real uses: walk a nested list, a file system or a JSON document, and tree questions (next topics).
- Fast power: x^n = (x^(n/2))² gives O(log n) calls; handle a negative n with 1 / x^(-n), and in Java and C++ store n in a long because -n overflows for the smallest int.
- Big results overflow: fib(47) is larger than the largest Java or C++ 32-bit int (2,147,483,647); use a 64-bit type. Python has no limit.
The red pen
Common traps: mistake → fix
Mistake: Recursion is always slower
Fix: it is often the clearest; the issue is depth and repeated work, not speed.
Mistake: A missing base case returns an empty result
Fix: it recurses until the stack overflows.
Mistake: Memoising with a mutable object as the key is fine
Fix: use a value that compares by content (a tuple in Python, a string or an encoded number in Java and C++).
Easy to hard
Questions interviewers ask, easy to hard
- Sum all numbers in a nested list.
- What is the space complexity of your recursion?
- Your input is nested 100,000 levels deep. What happens and how do you fix it?
- Compute fib(50) quickly. Why is plain recursion too slow?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.