Data Structures & Algorithms / Module 3: Recursion
Topic 3.2
Base cases and stack overflow
When recursion has to stop, and what happens when it never does.
Watch: with a stopping rule, the pile rises and falls again. Without it, the pile keeps rising until it hits the limit.
- moving now
- finished / the result
Like two mirrors facing each other
Two mirrors facing each other reflect a reflection inside a reflection, forever. A recursive function with no base case is the same: every call makes a new call, and none ever finishes. The difference is that a computer's memory is limited. After around ten thousand calls have piled up, the browser gives up with RangeError: Maximum call stack size exceeded.
Try both options in the figure. With a base case, the pile rises to count(0) and comes back down. Without one, it keeps rising until it hits the limit.
Code, for programmersWith and without a base case
function countGood(n) {
if (n === 0) return; // base case: stop here
countGood(n - 1);
}
function countBad(n) {
countBad(n - 1); // never stops: stack overflow
}A base case that is never reached
A base case that exists but gets skipped is just as dangerous. For example:
if (n === 0), and then the function is called withn = -1orn = 2.5. n never hits exactly 0. Usen <= 0.- A recursive step that doesn't shrink, such as calling
f(n)again instead off(n - 1). - Data that loops, such as a folder containing a shortcut to itself. Keep what you have visited in a Set.
Quiz
What happens if a recursive function has no base case?
A function's base case is if (n === 0). Which call still causes a stack overflow?
The base case is right, but the data is a linked list of 1 million nodes. Safest fix?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.