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.

7 min · beginner

Watch: with a stopping rule, the pile rises and falls again. Without it, the pile keeps rising until it hits the limit.

count(4)
  • moving now
  • finished / the result
Step 1 of 10

count(4) calls count(3).

In this figure the stack only fits 8 calls so it is easy to see. A real browser allows around ten thousand, but without a base case that limit is still reached.

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 with n = -1 or n = 2.5. n never hits exactly 0. Use n <= 0.
  • A recursive step that doesn't shrink, such as calling f(n) again instead of f(n - 1).
  • Data that loops, such as a folder containing a shortcut to itself. Keep what you have visited in a Set.

Quiz

  1. What happens if a recursive function has no base case?

  2. A function's base case is if (n === 0). Which call still causes a stack overflow?

  3. The base case is right, but the data is a linked list of 1 million nodes. Safest fix?

0 of 3 answered.