Call stack
The memory area that stores a frame for each running function, with its variables and where to return. The last frame in is the first out.
Example
When computing a recursive f(3), the stack holds f(3), f(2) and f(1) at once. When f(1) finishes, its frame is removed and f(2) continues.
Test yourself: Call stack
Iteration and recursion
Why does recursion usually use more memory than a loop?
When f(1,000) reaches its base case there are 1,000 frames stored at once. A loop that adds 1 to 1,000 always uses the same 2 variables.
Space complexity
If 2 functions have the same time complexity, they also have the same space complexity.
Adding 1 to n with a loop and with recursion are both O(n) in time, but the loop uses O(1) space and the recursion O(n).
Stacks
In a recursion, the last call to start is the ___ to finish.
f(3) calls f(2) and f(2) calls f(1). f(1) started last and finishes first: just like a stack.
0/3
â–¶ Play