“I'm confused with the last line especially because if n = 5 for example, then fibonacci(4) + fibonacci(3) would be called and so on but I don't understand how this algorithm calculates the value at index 5 by this method.”
asked on Stack Exchange · 568,773 views
Most explanations of recursion focus on the function calling itself. That part is easy to say and easy to nod along to.
The part that actually breaks people is what happens after the base case — when all those paused calls have to unwind, in order, each one finishing the piece of work it left half-done.
If you can trace one call going down but lose the thread on the way back up, you haven't finished learning recursion. You've learned to write it, not to predict it.
Predict before you check
function f(n) {
if (n <= 1) return n;
return f(n - 1) + f(n - 2);
}
f(4)Without running it — what does f(4) return?
Getting the right answer here doesn't mean you understand recursion. It means you can simulate a call stack once, carefully, under no time pressure. Vectra checks whether you can do it on a version you haven't seen — that's the difference between recognizing recursion and being able to use it.
The gap underneath the gap
Almost everyone who says 'I understand recursion but this problem confuses me' is actually missing something one level down: tracing a single call's stack frame all the way through — what it's waiting on, and what it does the instant that answer comes back. Recursion is just that, repeated. If the frame-by-frame unwind is fuzzy, no amount of re-reading the recursion definition will fix it — you're studying the wrong layer.
it doesn't move on until you get it.
Not ready to sign up? Name any concept and Vectra will show you what it sits on — for recursion that is usually the stack-frame unwind, not the definition you have already read twice.
See what recursion sits on, free →