Recursion

A function solves a problem by calling itself on a smaller piece of the same problem. It is the base for tree and graph traversal, divide and conquer, backtracking and dynamic programming.

Overview

A recursive function solves a problem by handing a smaller copy of the same problem to itself, then using the answer. It needs two parts and one guarantee, and it breaks without any of them. Backtracking and dynamic programming each have their own topic; this one is the base both build on.

Each section below follows the same shape: the rule first, then the rule on a small example, then the trap to avoid.

The idea

The rule: every recursive function has a base case, a recursive case and progress toward the base. Factorial shows all three.

  • The base case answers the smallest input directly, with no further call. For factorial, n <= 1 returns 1.
  • The recursive case makes the input smaller, calls itself, then combines the result. For factorial, that is n * factorial(n - 1).
  • Progress is the guarantee that every call moves closer to the base case. In factorial, n drops by 1 each call.

With those three in place, every call runs the same short routine.

  • Check whether the input is a base case. If it is, return the answer directly and stop.
  • If not, shrink the input.
  • Call the function on the smaller input and wait for its answer.
  • Combine that answer with this call's own work, and return the result.

Step 3 is the interesting one. While a call waits, it is still alive, and the computer has to remember where it was. That memory is the call stack.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio