AlgoTales · Roadmap

Base cases

Beginner · 7 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A base case is the stop sign of a self-repeating function: the simplest situation where the answer is known without asking again. Without it, the function calls itself forever until the program crashes, so every recursive solution starts by deciding what the stopping point is.

Practical use cases

  • Web app: Folder scanner that never stopped. A file manager page lists a folder and all its sub-folders. The developer forgot to stop at folders with no sub-folders, so the function kept calling itself on empty folders until the server ran out of memory. Adding a base case, stop when there is nothing left to open, made the scanner finish.
  • Web app: Nested comment thread. A blog shows replies inside replies. The rendering function asks, does this comment have replies? If not, it just prints the comment and stops; that is the base case. Without it, the function would keep looking for replies that do not exist and crash.
  • System: Binary search and parsers. Binary search stops when the range is empty or the item is found. A JSON parser stops at a plain number or string rather than another bracket. Each recursive tool relies on such a smallest case to end the chain of calls.

The story: The Last Matryoshka

Grandpa Bhaskar brought back a set of wooden nesting dolls from a trip. Mira opened the big one. Inside was a smaller one. Inside that, a smaller one. "How many dolls are there?" Grandpa grinned. "Keep opening and you will find out."

She opened and opened, until she reached a tiny doll that was solid wood, with no doll inside. "That is it!" she cried. "This one cannot be opened." Grandpa nodded. "That last doll is your base case: the place where you stop opening and start answering."

Kabir wondered, "What if the tiny doll was missing?" Grandpa chuckled. "Then you would keep trying to open a doll that does not exist. A computer in that spot keeps asking helpers for ever, and finally crashes with a stack overflow."

Every recursive function needs two things: a recursive step that makes the problem smaller, and a base case that answers the smallest problem directly. Miss the second and the first runs wild.

How to spot this problem, and where you need it

A function that calls itself either crashes with a stack overflow, runs forever, or returns wrong answers for the smallest inputs like an empty list or a single item.

Signs you need it

  • The error says maximum call stack size exceeded, allowed memory exhausted, or maximum function nesting level reached.
  • The code works for normal data but fails on an empty array, an empty folder, zero, or a single element.
  • A function calls itself with an input that is not clearly smaller, so each call looks just like the last one.

Where to use it in a project

  • Any code that walks nested menus, categories, comments, org charts or folders of unknown depth.
  • Recursive helpers that sum, count or search in arrays and trees, where the empty case must return a value directly.

The solution

Before writing the recursive call, finish this sentence: it is so small that I can answer without asking again when... That is your base case, for example the list is empty, the folder has no children, or the number is zero. Write that check first and return the answer immediately. Then make sure each recursive call hands over a strictly smaller piece, so it is guaranteed to reach the base case.

Payoff: Before: a category tree page crashes the server with a stack overflow. After: it renders every level and stops cleanly in milliseconds.

Explain it like I am 8

You ask your friend a question, and your friend asks another friend, and so on down the line. Someone at the very end must finally say "I know this one!" instead of asking again. That last person is the base case.

How it works, step by step

  1. Find the smallest version of the problem you can answer without thinking, such as sumTo(0) = 0.
  2. Write the base case first, at the top of the function: if (n === 0) return 0;.
  3. Write the recursive step, which must move towards the base case (here n becomes n-1).
  4. Check every input path: can any input skip past the base case? Negative numbers often do.
  5. Some problems need two base cases, like Fibonacci where both fib(0) and fib(1) are answered directly.

The code in four languages

PHP

<?php
// One base case is enough here: asking for 0 numbers sums to 0.
function sumTo(int $n): int {
    if ($n <= 0) return 0;          // base case (also catches negatives safely)
    return $n + sumTo($n - 1);      // recursive step: smaller problem
}

// Fibonacci needs TWO base cases because the step looks back two places.
function fib(int $n): int {
    if ($n === 0) return 0;         // base case 1
    if ($n === 1) return 1;         // base case 2
    return fib($n - 1) + fib($n - 2);
}

echo "sumTo(4) = " . sumTo(4) . "
";
echo "sumTo(0) = " . sumTo(0) . "
";
echo "fib(7)   = " . fib(7) . "
";

JavaScript

// One base case is enough here: asking for 0 numbers sums to 0.
function sumTo(n) {
  if (n <= 0) return 0;          // base case (also catches negatives safely)
  return n + sumTo(n - 1);       // recursive step: smaller problem
}

// Fibonacci needs TWO base cases because the step looks back two places.
function fib(n) {
  if (n === 0) return 0;         // base case 1
  if (n === 1) return 1;         // base case 2
  return fib(n - 1) + fib(n - 2);
}

console.log("sumTo(4) = " + sumTo(4));
console.log("sumTo(0) = " + sumTo(0));
console.log("fib(7)   = " + fib(7));

Java

public class Main {
    // One base case is enough here: asking for 0 numbers sums to 0.
    static int sumTo(int n) {
        if (n <= 0) return 0;          // base case (also catches negatives safely)
        return n + sumTo(n - 1);       // recursive step: smaller problem
    }

    // Fibonacci needs TWO base cases because the step looks back two places.
    static int fib(int n) {
        if (n == 0) return 0;          // base case 1
        if (n == 1) return 1;          // base case 2
        return fib(n - 1) + fib(n - 2);
    }

    public static void main(String[] args) {
        System.out.println("sumTo(4) = " + sumTo(4));
        System.out.println("sumTo(0) = " + sumTo(0));
        System.out.println("fib(7)   = " + fib(7));
    }
}

Go

package main

import "fmt"

// sumTo: one base case is enough here, asking for 0 numbers sums to 0.
func sumTo(n int) int {
	if n <= 0 {
		return 0 // base case (also catches negatives safely)
	}
	return n + sumTo(n-1) // recursive step: smaller problem
}

// fib needs TWO base cases because the step looks back two places.
func fib(n int) int {
	if n == 0 {
		return 0 // base case 1
	}
	if n == 1 {
		return 1 // base case 2
	}
	return fib(n-1) + fib(n-2)
}

func main() {
	fmt.Println("sumTo(4) =", sumTo(4))
	fmt.Println("sumTo(0) =", sumTo(0))
	fmt.Println("fib(7)   =", fib(7))
}

Time: O(n) for sumTo · Extra space: O(n). Each pending call waits on the stack until the base case answers, so depth grows with n.

Watch out for

  • Forgetting the base case entirely, which gives infinite recursion and a stack overflow.
  • Writing a base case the input can jump over, like n === 0 when n can be negative.
  • A recursive step that does not shrink the problem, so you never get closer to the base case.

Quick check

  1. What is a base case?
    • The first call of the program
    • The simplest input answered directly without recursion
    • The slowest case
  2. sumTo(n) = n + sumTo(n-1) has no base case. What happens?
    • It returns 0
    • It runs until stack overflow
    • It returns n
  3. Why does fib need two base cases?
    • Because it calls itself with n-1 and n-2
    • Because it is slow
    • Because it returns two values