AlgoTales · Roadmap

Recursive calls

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

Where you will meet this in real life

A recursive call is a function asking itself to solve a smaller copy of the same job, trusting the answer, and then using it. It suits anything with boxes inside boxes, which on the web is nearly everything: menus, comments, folders, and pages linking to pages.

Practical use cases

  • Web app: Nested blog comments. A comment can have replies, and each reply can have replies of its own. The render function prints one comment, then calls itself once for each reply. The same ten lines handle two levels or twenty, so you never write one loop per level of nesting.
  • Web app: Category menu in a shop. Electronics contains Phones, which contains Android, which contains brands. Rather than guessing how deep it goes, a function prints a category then calls itself for each child. When the shop adds a new level next season, the menu keeps working unchanged and nobody has to touch the code.
  • System: Crawlers and file search. A web crawler visits a page, collects its links, and then repeats the same visit for every link. A file search tool does the same with folders inside folders. Both are the same small job repeated on smaller or newer pieces.

The story: The Russian Doll Messenger

Grandma gave Kabir a set of nesting dolls and a question: "How many dolls are in there?" Kabir opened the biggest one. Inside was a smaller doll, and inside that, another. He sighed. "That is too many to hold in my head."

So he made a deal with himself: "I will say: 1 + however many are inside this one." Then he opened the next doll and said the exact same sentence. And the next. Each doll waited, politely, for the answer from the doll inside it.

Finally he reached a tiny solid doll that opens no more. "Zero inside!" And now the answers flew back up the chain: 0, then 1 + 0, then 1 + 1... until the biggest doll could finally say the total. That is recursion: solve a big problem by asking a slightly smaller copy of the same problem, until it is so small the answer is obvious.

How to spot this problem, and where you need it

The data is shaped like a tree of unknown depth, and loops with a fixed number of levels either miss deeper items or become a tangled mess of nested foreach blocks.

Signs you need it

  • Each item can contain more items of the same kind: replies, sub-categories, sub-folders, child employees.
  • You find yourself writing a foreach inside a foreach inside a foreach and still worry about the next level.
  • The problem statement describes a thing made of smaller versions of itself, or asks for all, total or deepest.

Where to use it in a project

  • Rendering threaded comments, nested navigation menus, category breadcrumbs and organisation charts.
  • Walking JSON returned from an API, scanning directories, or searching a nested settings object.

The solution

Write down the job for one item. Then say how it uses the same job on its children. Code it as: if there is nothing left, stop; otherwise do the small job for this item and call the same function for each child. Trust that the call handles its piece correctly. The structure of the code now mirrors the structure of the data, so any depth works.

Payoff: Before: a menu supporting only three levels with nested loops. After: ten lines that handle any depth, including ones added later.

Explain it like I am 8

It is like standing between two mirrors, but with a stop sign. You keep doing the same small job over and over, each time with a smaller piece, until you hit the stop sign (the "base case"). Then everyone who was waiting hands their answer back, one by one.

How it works, step by step

  1. Find the stop sign (base case). The smallest version of the problem where the answer is obvious. For dolls: "no doll inside = 0".
  2. Make the problem smaller. Each call must move toward the stop sign: n - 1, the rest of the list, a smaller piece.
  3. Trust the helper. Pretend the smaller call already works, and combine its answer with your tiny bit of work.
  4. The computer remembers who is waiting. Each unfinished call sits on the call stack, like pending doll-openers. Too many waiting calls and the stack overflows.

The code in four languages

PHP

<?php
// How many dolls? (sum of 1..n works the same way)
function sumTo(int $n): int {
    if ($n === 0) return 0;          // 1. base case = the stop sign
    return $n + sumTo($n - 1);       // 2. smaller problem, 3. trust the helper
}

echo sumTo(4);   // 4 + 3 + 2 + 1 + 0 = 10

// Classic: factorial
function fact(int $n): int {
    return $n <= 1 ? 1 : $n * fact($n - 1);
}

JavaScript

// How many dolls? (sum of 1..n works the same way)
function sumTo(n) {
  if (n === 0) return 0;        // 1. base case = the stop sign
  return n + sumTo(n - 1);      // 2. smaller problem, 3. trust the helper
}

console.log(sumTo(4));   // 4 + 3 + 2 + 1 + 0 = 10

// Classic: factorial
const fact = n => (n <= 1 ? 1 : n * fact(n - 1));

Java

public class Main {
    // How many dolls? (sum of 1..n works the same way)
    static int sumTo(int n) {
        if (n == 0) return 0;          // 1. base case = the stop sign
        return n + sumTo(n - 1);       // 2. smaller problem, 3. trust the helper
    }

    // Classic: factorial
    static int fact(int n) {
        return n <= 1 ? 1 : n * fact(n - 1);
    }

    public static void main(String[] args) {
        System.out.println(sumTo(4));   // 4 + 3 + 2 + 1 + 0 = 10
        System.out.println(fact(5));    // 5 * 4 * 3 * 2 * 1 = 120
    }
}

Go

package main

import "fmt"

// sumTo: how many dolls? (sum of 1..n works the same way)
func sumTo(n int) int {
	if n == 0 {
		return 0 // 1. base case = the stop sign
	}
	return n + sumTo(n-1) // 2. smaller problem, 3. trust the helper
}

// fact is the classic factorial.
func fact(n int) int {
	if n <= 1 {
		return 1
	}
	return n * fact(n-1)
}

func main() {
	fmt.Println(sumTo(4)) // 4 + 3 + 2 + 1 + 0 = 10
	fmt.Println(fact(5))  // 5 * 4 * 3 * 2 * 1 = 120
}

Time: O(n) · Extra space: O(n). n calls are made, and n calls wait on the stack at the deepest moment.

Watch out for

  • Forgetting the base case. The calls never stop and you get "Maximum call stack size exceeded" (JS) or a memory error (PHP).
  • Not shrinking the problem. Calling sumTo($n) instead of sumTo($n - 1) loops forever.

Quick check

  1. What is the job of the base case?
    • Make the code shorter
    • Stop the recursion with an obvious answer
    • Speed up the CPU
  2. In sumTo(3), which call finishes first?
    • sumTo(3)
    • sumTo(1)
    • sumTo(0)
  3. What happens if you forget the base case?
    • It returns 0
    • The stack overflows
    • It runs faster