AlgoPlusAlgoPlus
Learn/Problem-Solving Patterns
Lesson

Recursion

A function that solves a problem by calling itself on a smaller version of the same problem.

8 min read Watch it move Build it

Recursion is when a function calls *itself* to solve a smaller instance of the same problem, until the problem is small enough to answer directly. It feels like magic at first — but it's just a stack of paused function calls, each waiting on the next.

Two parts every recursion needs

  1. 1Base case — the smallest input you can answer immediately, with no further recursion. This is what stops the chain.
  2. 2Recursive case — reduce the problem toward the base case and call yourself on the smaller piece.
The mental model
Trust that the recursive call already returns the correct answer for the smaller problem. Then you only have to combine it — you never trace the whole thing in your head.
function factorial(n) {
  if (n <= 1) return 1;        // base case
  return n * factorial(n - 1); // recursive case
}

How it actually runs — the call stack

Each call is *pushed* onto the call stack and pauses, waiting for the call below it to return. When the base case returns, the stack *unwinds* — each paused call resumes, multiplies, and returns up the chain.

No base case = stack overflow
If the recursion never reaches a base case, calls pile up forever until the stack runs out of memory. Always make sure each step moves *toward* the base case.
OperationTimeSpace
factorial(n) · n stacked callsO(n)O(n)
Check yourself
What happens if a recursive function has no reachable base case?