Recursion vs Iteration in DSA: Which to Write in an Interview
Master recursion and iteration for coding interviews. Learn call stack limits, DFS, tree traversals, and dynamic programming trade-offs.
On this page
Write the iterative version unless recursion is the only clean way to touch every node in a tree. Interviews in service companies and product startups often test your comfort with both, but writing recursive code for linear data structures like vector<int> nums signals an engineer who does not know how the machine runs. A recursive function on a flat array of size 100000 risks a segmentation fault on standard GCC stack sizes, whereas a for loop runs without touching memory limits.
The Call Stack Mental Model
Every time a function calls itself, the CPU pushes a stack frame containing local variables, parameters, and the return address onto the call memory. When you compute factorial(4), the runtime creates four separate frames stacked vertically. Frame four waits for frame three, which waits for frame two, until the base case returns 1. If your input n is 1000000, that stack grows until the operating system kills the process. Iteration avoids this entirely by reusing a single stack frame with local variables updated in place.
When Recursion Wins
Trees and graphs demand recursion because their shapes are self-similar and branch unpredictably. Writing an iterative depth-first search on a binary tree requires managing an explicit stack and handling null pointers manually, which turns a five-line function into a twenty-line debugging puzzle. For invertTree(TreeNode* root), recursion matches the definition of the structure itself: invert the left subtree, invert the right subtree, swap their pointers, and return. The maximum recursion depth equals the height of the tree, which for a balanced tree of 1000000 nodes is only 20, well within safe memory limits.
Turning Recursion Into Iteration
You can convert any tail-recursive function into a loop by replacing the call stack with a data structure in heap memory. Consider a binary search tree search function. Instead of calling search(node->left), you assign node = node->left inside a while (node != nullptr) loop. For general depth-first search, push nodes onto a std::stack or std::vector manually. You pop the top element, process it, and push its children. This keeps memory usage explicit and prevents stack overflows when processing deep graphs.
Dynamic Programming and Memoization
Top-down dynamic programming starts with a recursive function and adds a memoization table to cache results. For fibonacci(5), the naive recursion repeats calculations for fib(2) multiple times, yielding an exponential time complexity. Adding a lookup array dp[6] reduces this to linear time. Interviewers accept top-down memoization for complex state transitions, but bottom-up tabular iteration using a simple array is always safer because it eliminates overhead from function calls entirely.
A Hand-Traced Example
Consider finding the maximum value in an array arr = {3, 1, 4, 1, 5} using both approaches. The iterative version initializes max_val = arr[0], loops from index 1 to 4, and updates max_val = max(max_val, arr[i]) using a single block of memory. The recursive version checks if (n == 1) return arr[0], and returns max(arr[n-1], find_max(arr, n-1)), which creates five distinct stack frames. Both run in O(n) time, but the loop uses O(1) auxiliary space while the recursion uses O(n) space.
Your Interview Checklist
- Use iteration for arrays, strings, and linear linked lists.
- Use recursion for trees and graphs where explicit stacks add clutter.
- Check if your recursion depth exceeds
1000calls on maximum constraints. - Practice converting a memoized solution into a bottom-up table on DSA Tracker.
Open your local compiler right now and rewrite your last recursive tree traversal using an explicit stack.
Practice what you just read
Keep reading
LeetCode vs GeeksforGeeks vs Codeforces: Where Should You Practise for Placements?
LeetCode is the primary tool for Indian campus placements. Use GeeksforGeeks for theory and Codeforces only if you have spare time. Here is the specific breakdown.
Striver A2Z vs Love Babbar 450 vs Apna College: Which Sheet Should You Follow?
Striver A2Z, Love Babbar 450 and Apna College sheets overlap more than they differ. Here is how they compare and which one fits your time and level.