Base case and recursive case
corebeginnerEvery recursive function needs a base case that returns directly, with no further recursive call, and a recursive case that calls itself on a smaller version of the same problem — the base case is what stops the calls.
Think of it as
A recursive function is a promise: 'hand me a smaller version of this problem and I already know how to combine your answer into mine — that is the recursive call. Once the problem is small enough, I can answer immediately, with no help — that is the base case.' Skip the base case, or never actually shrink the input, and the promise never resolves.
What we're doing: Compute a factorial recursively, with the base case stopping the recursion at n <= 1.
- 2
- n <= 1 (not just n == 0) covers both the natural stopping point and the smallest valid input in one check.
- 4
- Each call passes n - 1 — strictly smaller than n — guaranteeing the base case is eventually reached.
120
1Why this works: factorial(5) expands to 5 * 4 * 3 * 2 * 1 = 120. factorial(0) hits the base case immediately, returning 1 with no recursive call at all.
A base case that exists but is never reachable, because the input never shrinks
Wrong
Better
What you see: factorial_wrong(5) raises RecursionError: maximum recursion depth exceeded — it never returns at all.
Why: The recursive call passes n unchanged instead of n - 1, so every call sees the exact same n. n == 0 is a real base case, but it is never reached from n = 5, since n never gets any smaller.
- Fibonacci NumbereasyLeetCode
Two base cases (n <= 1) and one recursive case — the smallest complete example of the pattern beyond factorial.
- Pow(x, n)mediumLeetCode
The base case is n == 0 (return 1); the recursive case can halve n each call instead of just subtracting 1, for O(log n) depth instead of O(n).
Remember: A base case only stops recursion if every recursive call actually moves the input closer to it — a base case that is never reached is no different from having none at all.