AlgoTales · Roadmap

Recursion

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

Where you will meet this in real life

Recursion solves a problem by having a function call itself on a smaller version of the same problem, until the problem is so small the answer is obvious. It fits anything shaped like boxes inside boxes.

Practical use cases

  • Web app: Total size of a folder. A file-manager page shows the size of a folder that contains files and more folders. A function adds up the files and calls itself for each subfolder, stopping when there are none, so the page shows the right total however deeply the folders are nested.
  • Web app: Nested comments and category menus. A blog renders replies to replies, and a shop shows categories inside categories. One function that renders an item and then calls itself for each child handles any depth of nesting. Add a new level of nesting tomorrow and the code still works without any changes.
  • Web app: Reading JSON or config of any depth. An API client must clean or search through a JSON response whose structure nests unpredictably. A recursive function visits every level without needing to know how deep it goes. The client can clean or search any response, even when the API changes how deep it nests.
  • System: The browser DOM and puzzles. Browsers walk the page tree recursively to find elements, so a search in a huge page needs only a short function. Games and puzzle apps use the same idea, solving a position by first solving the smaller positions that follow it.

The story: The Box Inside the Box

Raju’s cousin sent a parcel from Surat for the chai stall. Inside the big box was a smaller box. Inside that, a still smaller one, and inside that, a tiny box with a note: "Counting how many sachets are in all the boxes together." Each box held some loose sachets and maybe one more box.

Mira started opening boxes and writing numbers on her hand, until she ran out of hand. Kabir laughed: "Don’t track everything yourself. Just give the rule to yourself: to count a box, count its loose sachets, then ask the same question about the box inside."

And when does it stop? When a box has no box inside: just add its loose sachets and you are done. That stopping spot is the base case. Everything else hands a slightly smaller copy of the same question to a helper, waits, and adds the answer.

That is recursion. The smell: "nested", "tree", "folder inside folder", "smaller version of the same problem", or a definition that mentions itself. Whenever the input is built from smaller copies of itself, let a function call itself.

How to spot this problem, and where you need it

Your data or task contains smaller copies of itself (folders in folders, replies to replies), and you do not know in advance how many levels there are.

Signs you need it

  • Data has children of the same type as the parent, such as a tree of categories, comments, menus or folders.
  • You find yourself writing loops inside loops inside loops, and still the depth is not covered.
  • The problem can be said as "answer for the whole = this item plus the answer for each smaller part".

Where to use it in a project

  • Nested menus, comment threads and category trees of unknown depth.
  • File-system and JSON processing where items contain more items of the same type.
  • Puzzle and combination generators that try one choice and then solve what is left.

The solution

Write the function with two parts. First, the base case: the simplest input (no children, empty list) and its direct answer. Second, the recursive case: do a small piece of work, call the same function on each smaller piece, and combine the results. Make sure every call moves closer to the base case so it always stops.

Payoff: Before: fixed-depth loops that break on level 4. After: one short function that works for any depth.

Explain it like I am 8

Imagine a set of Russian dolls. To find the smallest doll, you say: "open this doll; if there is another doll inside, ask my friend to do the same". The friend asks another friend. When someone opens a doll with nothing inside, that friend shouts the answer back up the line.

How it works, step by step

  1. Spot the clue: the data or the problem contains a smaller copy of itself (nested lists, folders, trees, "n" depends on "n-1").
  2. Write the base case first: the smallest input you can answer directly (a plain number, an empty list). Without it the calls never stop.
  3. Write the recursive case: do a little work, then call yourself on a smaller piece and combine the answers.
  4. Trust the helper. Assume the call on the smaller piece already works. Do not trace every level in your head.
  5. Watch the call stack: each unfinished call waits in a pile; the deepest finishes first and the pile unwinds.

The code in four languages

PHP

<?php
// Classic: add up every number inside arbitrarily nested lists.
function sumNested(array $box): int {
    $total = 0;
    foreach ($box as $item) {
        if (is_array($item)) {
            $total += sumNested($item);   // recursive case: same question, smaller box
        } else {
            $total += $item;              // base case: a plain number just adds
        }
    }
    return $total;
}
echo sumNested([1, [2, [3]], 4]), "
";          // 10
echo sumNested([[], [[5]], 5]), "
";            // 10  (empty boxes are fine)

JavaScript

// Classic: add up every number inside arbitrarily nested lists.
function sumNested(box) {
  let total = 0;
  for (const item of box) {
    if (Array.isArray(item)) {
      total += sumNested(item);   // recursive case: same question, smaller box
    } else {
      total += item;              // base case: a plain number just adds
    }
  }
  return total;
}
console.log(sumNested([1, [2, [3]], 4]));   // 10
console.log(sumNested([[], [[5]], 5]));     // 10  (empty boxes are fine)

Java

import java.util.*;

public class Main {
    // Classic: add up every number inside arbitrarily nested lists.
    // A box holds Integers and/or smaller boxes (Lists).
    static int sumNested(List<?> box) {
        int total = 0;
        for (Object item : box) {
            if (item instanceof List<?> inner) {
                total += sumNested(inner);   // recursive case: same question, smaller box
            } else {
                total += (Integer) item;     // base case: a plain number just adds
            }
        }
        return total;
    }

    public static void main(String[] args) {
        System.out.println(sumNested(List.of(1, List.of(2, List.of(3)), 4)));         // 10
        System.out.println(sumNested(List.of(List.of(), List.of(List.of(5)), 5)));    // 10  (empty boxes are fine)
    }
}

Go

package main

import "fmt"

// sumNested adds up every number inside arbitrarily nested lists.
// A box holds ints and/or smaller boxes ([]any).
func sumNested(box []any) int {
	total := 0
	for _, item := range box {
		if inner, ok := item.([]any); ok {
			total += sumNested(inner) // recursive case: same question, smaller box
		} else {
			total += item.(int) // base case: a plain number just adds
		}
	}
	return total
}

func main() {
	fmt.Println(sumNested([]any{1, []any{2, []any{3}}, 4}))    // 10
	fmt.Println(sumNested([]any{[]any{}, []any{[]any{5}}, 5})) // 10  (empty boxes are fine)
}

Time: O(n) · Extra space: O(d). Every number is touched once (n); the call stack is as deep as the nesting (d).

Watch out for

  • Forgetting the base case, or writing one that is never reached: the stack overflows ("maximum call stack size exceeded").
  • Calling yourself on the same input instead of a smaller one, which loops forever.
  • Trying to simulate the whole recursion in your head. Check base case, then check one step.

Quick check

  1. Which phrase smells like recursion?
    • "sorted array"
    • "folders inside folders"
    • "find two numbers with a target sum"
    • "shortest time slot"
  2. What must every recursive function have?
    • A loop
    • A global variable
    • A base case
    • Two parameters
  3. What is the call stack?
    • A sorted list of results
    • A copy of the input
    • The output of the program
    • The pile of unfinished calls waiting for their helpers