AlgoTales · Roadmap

Base cases

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

Where you will meet this in real life

Base cases are the smallest, obvious answers, like the best result for zero items or an empty string, which everything else is built upon. They are the starting point of every table and the stopping point of every recursion. Forgetting them is the most common cause of crashes and wrong totals.

Practical use cases

  • Web app: Checkout crashing on an empty cart. A billing function worked for every test, then crashed in production when a customer opened the cart page with nothing in it. Nobody had defined what the total for zero items should be. Adding a base case, "no items means a total of 0", fixed the crash and the empty-cart page showed properly. The team also added a test for a cart with exactly one item, because the smallest inputs are where this kind of bug hides.
  • Web app: Search or autocomplete with empty input. A search box calls a text-matching function on every keypress, including when the box is empty or has a single letter. Defining the answer for an empty string avoids errors and shows a clean list of suggestions. A one-line check for empty text, plus a test, saves a flood of error reports on a busy night, and the search box simply shows popular products instead.
  • System: Recursion in general. Any function that calls itself, such as a folder-size calculator, needs a case where it stops. Without it, the program calls itself until the machine runs out of memory. In all of these systems, the tiniest case is defined first and every bigger answer is built on top of it, so a missing one breaks everything above it.

The story: The First Domino

At Zoya's cousin's wedding the kids set up a long line of dominoes. Aarav pushed the 10th domino and nothing happened. "Of course," laughed Grandpa Bhaskar. "Nobody pushed the first one. Every domino falls because the one before it fell. But somebody has to start the chain."

Zoya was in the same trouble with her coin puzzle. The corner shop accepted only ₹3 and ₹5 coins. For each amount she wrote: "take the cheaper of (amount minus 3) or (amount minus 5), then add one coin." But for ₹3 the rule said "look at ₹0", and her notebook had nothing on ₹0!

"Put in the starting facts," said Grandpa. "₹0 needs 0 coins. And things that cannot be paid, like ₹1, ₹2 or ₹4, get a big warning sign: impossible." With those, the whole table filled itself, and the impossible amounts never fooled anyone into building on them.

Those starting facts are the base cases: the tiny answers you write down by hand so that every other answer has something solid to stand on. Forget them, or get them wrong, and the whole chain collapses like the dominoes.

How to spot this problem, and where you need it

Your recursive or table-based code crashes, loops forever, or gives off-by-one answers, especially on tiny or empty inputs.

Signs you need it

  • The error mentions "maximum call stack" or "index not found", or the program hangs on inputs of size 0 or 1.
  • The answers are right for large inputs but wrong for the smallest ones, or off by exactly one.
  • You cannot say what your function returns for an empty list, empty string or zero amount.

Where to use it in a project

  • Edge-case testing of billing, cart and discount code: zero items, one item, zero amount.
  • Handling empty strings and empty arrays in search, validation and text features.

The solution

Before writing the main logic, ask what the answer is for the smallest possible input: zero items, empty text, amount zero. Write those answers down as the first cells of your table or the first lines of your function. Also check what happens when an index would go below zero. Then confirm the main rule only ever uses values that are already known.

Payoff: Before: a production crash for every customer with an empty cart. After: the same case handled in one line, and tests for size 0 and 1 always pass.

Explain it like I am 8

Base cases are the first domino and the "nothing to do" answers. You knock the first domino with your finger, because no domino stands behind it. After that, every domino pushes the next. If you forget the first push, nothing moves at all.

How it works, step by step

  1. Find the smallest questions whose answer you can say without any calculation (size 0, size 1, one item...).
  2. Write those answers into the table first. They are not worked out; they are given.
  3. Mark the impossible. If a box can have no valid answer, store a special value (a huge number for "min", or -1/null for "none") so it is never used by accident.
  4. Check the transition's reach. Does it ever look before the start of the table (like dp[-1])? Then guard it or add more base cases.
  5. Test the smallest inputs by hand (0, 1, 2) before trusting the loop.

The code in four languages

PHP

<?php
// Fewest coins to make 'amount' exactly; coins can be reused.
function fewestCoins(array $coins, int $amount): int {
    $INF = 1000000000;                           // "impossible" marker
    $dp = array_fill(0, $amount + 1, $INF);
    $dp[0] = 0;                                  // BASE CASE: zero rupees needs zero coins
    for ($a = 1; $a <= $amount; $a++) {
        foreach ($coins as $c) {
            // Only build on a smaller amount that is reachable (not impossible).
            if ($a >= $c && $dp[$a - $c] < $INF) {
                $dp[$a] = min($dp[$a], $dp[$a - $c] + 1);
            }
        }
    }
    return $dp[$amount] >= $INF ? -1 : $dp[$amount];   // -1 means impossible
}

echo fewestCoins([3, 5], 11), "\n";             // 3  (3 + 3 + 5)
echo fewestCoins([3, 5], 4), "\n";              // -1 (cannot be paid)
echo fewestCoins([3, 5], 0), "\n";              // 0  (base case)

JavaScript

// Fewest coins to make 'amount' exactly; coins can be reused.
function fewestCoins(coins, amount) {
  const INF = 1e9;                               // "impossible" marker
  const dp = new Array(amount + 1).fill(INF);
  dp[0] = 0;                                     // BASE CASE: zero rupees needs zero coins
  for (let a = 1; a <= amount; a++) {
    for (const c of coins) {
      // Only build on a smaller amount that is reachable (not impossible).
      if (a >= c && dp[a - c] < INF) {
        dp[a] = Math.min(dp[a], dp[a - c] + 1);
      }
    }
  }
  return dp[amount] >= INF ? -1 : dp[amount];    // -1 means impossible
}

console.log(fewestCoins([3, 5], 11));            // 3  (3 + 3 + 5)
console.log(fewestCoins([3, 5], 4));             // -1 (cannot be paid)
console.log(fewestCoins([3, 5], 0));             // 0  (base case)

Java

import java.util.*;

public class Main {
    // Fewest coins to make 'amount' exactly; coins can be reused.
    static int fewestCoins(int[] coins, int amount) {
        final int INF = 1_000_000_000;               // "impossible" marker
        int[] dp = new int[amount + 1];
        Arrays.fill(dp, INF);
        dp[0] = 0;                                   // BASE CASE: zero rupees needs zero coins
        for (int a = 1; a <= amount; a++) {
            for (int c : coins) {
                // Only build on a smaller amount that is reachable (not impossible).
                if (a >= c && dp[a - c] < INF) {
                    dp[a] = Math.min(dp[a], dp[a - c] + 1);
                }
            }
        }
        return dp[amount] >= INF ? -1 : dp[amount];  // -1 means impossible
    }

    public static void main(String[] args) {
        System.out.println(fewestCoins(new int[]{3, 5}, 11));   // 3  (3 + 3 + 5)
        System.out.println(fewestCoins(new int[]{3, 5}, 4));    // -1 (cannot be paid)
        System.out.println(fewestCoins(new int[]{3, 5}, 0));    // 0  (base case)
    }
}

Go

package main

import "fmt"

// Fewest coins to make 'amount' exactly; coins can be reused.
func fewestCoins(coins []int, amount int) int {
	const INF = 1_000_000_000 // "impossible" marker
	dp := make([]int, amount+1)
	for i := range dp {
		dp[i] = INF
	}
	dp[0] = 0 // BASE CASE: zero rupees needs zero coins
	for a := 1; a <= amount; a++ {
		for _, c := range coins {
			// Only build on a smaller amount that is reachable (not impossible).
			if a >= c && dp[a-c] < INF {
				dp[a] = min(dp[a], dp[a-c]+1)
			}
		}
	}
	if dp[amount] >= INF {
		return -1 // -1 means impossible
	}
	return dp[amount]
}

func main() {
	fmt.Println(fewestCoins([]int{3, 5}, 11)) // 3  (3 + 3 + 5)
	fmt.Println(fewestCoins([]int{3, 5}, 4))  // -1 (cannot be paid)
	fmt.Println(fewestCoins([]int{3, 5}, 0))  // 0  (base case)
}

Time: O(amount × coins) · Extra space: O(amount). Base cases are free: they cost nothing but save the whole table from being wrong.

Watch out for

  • Using 0 as the "impossible" marker for a minimum problem. It looks like the best possible answer! Use a huge number or -1 (and check for it).
  • Adding 1 to the "impossible" marker. A huge number plus 1 can look like a legal answer; skip impossible boxes instead.
  • Setting the base case to the wrong value, such as dp[0] = 1 for a "fewest coins" table. Ask the question out loud for the empty case.

Quick check

  1. Why do we need base cases?
    • To make the code look longer
    • They are the starting answers that every other box is built from
    • To sort the table
  2. For the fewest-coins table, what should dp[0] be?
    • 0
    • 1
    • Impossible
  3. Why store a big "impossible" value instead of 0 for unreachable amounts?
    • 0 uses more memory
    • Zero looks like a great (best) answer and could be wrongly chosen by min
    • PHP does not allow 0