Data Structures & Algorithms / Module 3: Recursion
Topic 3.3
Recursion vs iteration
Two ways to solve the same problem: when recursion is clearer, and when a loop is safer.
Watch: both ways give the same number, but recursion piles up five notes while the loop needs just two.
- moving now
- finished / the result
Two ways to climb stairs
The first way, recursion: "to reach step 5, first reach step 4, then take one more step", with every step remembering that it is still waiting. The second way, a loop: "start at the bottom, take a step, repeat until five". Both get you to the top. The first carries a note for every step; the second only needs to know which step it is on.
In the figure, both work out 1 + 2 + 3 + 4 + 5 = 15. Watch the memory number in the bottom-right corner.
Code, for programmersSame answer, different memory
// Recursion: n calls wait on the stack, O(n) memory
function sumRec(n) {
if (n === 0) return 0;
return n + sumRec(n - 1);
}
// Loop: two variables, O(1) memory
function sumLoop(n) {
let total = 0;
for (let i = 1; i <= n; i++) total += i;
return total;
}So which do you pick?
- Pick recursion when the data branches (trees, folders, nested JSON) and its depth is reasonable. The code is usually shorter and closer to how we think about the problem.
- Pick a loop when the data is long and straight (lists, linked lists, numbers into the millions), or when you don't control the depth, such as data from users.
- For branching data that can be very deep, a loop still works: keep the waiting work yourself on a stack (an array). That is how DFS is usually written without recursion.
Quiz
sumRec(10000) above risks a stack overflow, sumLoop(10000) doesn't. Why?
How much extra memory does sumLoop(n) use?
Walking a folder structure of reasonable depth is most naturally written with…
0 of 3 answered.
Built on
Used in
No follow-up topics yet.