Recursion examples are functions that call themselves on a smaller input until a base case stops them. Start with factorial and sum of digits, move to fast power, string reversal, GCD and Fibonacci, then try Tower of Hanoi, permutations, subsets and flood fill. Each example needs a base case, a smaller call and a way to combine results.
On this page
Examples 1 to 3: shrink the numberExamples 4 to 7: strings, GCD and number conversionExamples 8 to 10: two calls, nesting and binary searchExamples 11 to 14: choices and gridsCommon recursion bugs and what they look likeFrequently asked questionsThis page is examples only. If you need the definition of recursion, the call stack and the base case idea, read what is recursion first; it is not repeated here. Here you get 14 programs in order of difficulty, each with its real output and a note on the base case or call tree.
All code was run with Python 3 on 1 December 2026. Interview-style versions of several of these appear in DSA interview questions.
- 1Counting downFactorial, digit sum
- 2HalvingFast power, GCD, binary
- 3StringsReverse, palindrome
- 4Two callsFibonacci, memo
- 5StructuresFlatten, binary search
- 6ChoicesHanoi, permutations, subsets
- 7GridsFlood fill
Examples 1 to 3: shrink the number
Each of these calls itself with a smaller number. Check the base case first: it is what stops the recursion, and every example below has one.
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1)
def sum_digits(n):
if n < 10: # base case: one digit left
return n
return n % 10 + sum_digits(n // 10)
def power(x, n):
if n == 0:
return 1
half = power(x, n // 2) # halve the exponent: O(log n) calls
return half * half if n % 2 == 0 else half * half * x
print(factorial(5))
print(sum_digits(4821))
print(power(2, 10), power(3, 5))Output: 120, 15, then 1024 243.
| # | Example | Base case | Recursive step | Calls for input size n |
|---|---|---|---|---|
| 1 | factorial(5) | n is 1 or less returns 1 | n times factorial(n - 1) | n calls, a straight line: 5, 4, 3, 2, 1 |
| 2 | sum_digits(4821) | one digit left | last digit plus sum_digits(n // 10) | one call per digit: 4821, 482, 48, 4 |
| 3 | power(2, 10) | exponent 0 returns 1 | square the half-power, times x if odd | about log n calls: 10, 5, 2, 1, 0 |
Factorial is the standard first example, but the fast power one is the better habit: halving the input, as in power, takes about log n calls where a naive loop takes n. Any loop over an integer can be written this way, but see recursion vs iteration for when you should not.
Examples 4 to 7: strings, GCD and number conversion
def reverse(s):
if len(s) <= 1:
return s
return reverse(s[1:]) + s[0]
def is_palindrome(s):
if len(s) < 2:
return True
return s[0] == s[-1] and is_palindrome(s[1:-1])
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b) # Euclid's algorithm
def to_binary(n):
if n < 2:
return str(n)
return to_binary(n // 2) + str(n % 2)
print(reverse("masai"))
print(is_palindrome("level"), is_palindrome("masai"))
print(gcd(48, 18))
print(to_binary(10))Output: iasam (example 4), then True False, then 6, then 1010.
| # | Example | Base case | Call-tree note |
|---|---|---|---|
| 4 | reverse('masai') | length 0 or 1 returns itself | Each call drops the first character: 5, 4, 3, 2, 1 characters; slicing copies, so total work is O(n squared) |
| 5 | is_palindrome | fewer than 2 characters is True | Compares ends, recurses on the middle; stops early at the first mismatch |
| 6 | gcd(48, 18) | b is 0 returns a | gcd(48, 18), gcd(18, 12), gcd(12, 6), gcd(6, 0) returns 6; the second argument shrinks fast |
| 7 | to_binary(10) | n below 2 returns the digit | 10, 5, 2, 1: builds the string on the way back up, left digit first |
The habit is the same in all four: say what the function returns for the smallest input first, then trust it for the smaller call.
Examples 8 to 10: two calls, nesting and binary search
Example 8: Fibonacci, naive and memoised
Here each call makes two calls, so the call tree branches. The naive version recomputes the same values again and again; remembering results (memoisation) removes the repeats. Counting the calls shows the gap in numbers.
calls = 0
def fib_naive(n):
global calls
calls += 1
if n < 2:
return n
return fib_naive(n - 1) + fib_naive(n - 2)
memo_calls = 0
def fib_memo(n, memo={}):
global memo_calls
memo_calls += 1
if n < 2:
return n
if n not in memo:
memo[n] = fib_memo(n - 1) + fib_memo(n - 2)
return memo[n]
print(fib_naive(20), "naive calls:", calls)
print(fib_memo(20), "memo calls:", memo_calls)Output: 6765 naive calls: 21891 and 6765 memo calls: 39. For n = 20, naive Fibonacci made 21,891 calls and the memoised one 39. The naive count grows exponentially with n. The memoised version is linear, which is the first idea of dynamic programming. One warning: the default dictionary in fib_memo is created once and shared across calls, which is useful here and a classic bug elsewhere.
Examples 9 and 10: flatten a nested list and recursive binary search
def flatten(items):
out = []
for x in items:
if isinstance(x, list):
out.extend(flatten(x)) # a nested list is a smaller copy of the problem
else:
out.append(x)
return out
def binary_search(a, target, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo > hi: # base case: empty range
return -1
mid = (lo + hi) // 2
if a[mid] == target:
return mid
if a[mid] < target:
return binary_search(a, target, mid + 1, hi)
return binary_search(a, target, lo, mid - 1)
print(flatten([1, [2, [3, 4]], 5, [[6]]]))
a = [2, 5, 8, 12, 16, 23, 38]
print(binary_search(a, 23), binary_search(a, 7))Output: [1, 2, 3, 4, 5, 6], then 5 -1. Flatten has no explicit base case: when the list has no nested lists the loop simply ends. Binary search has two exits: found (return the index) and empty range (return -1). Each call halves the range, so a 7-item list needs at most 3 calls. The loop version is in binary search explained.
Examples 11 to 14: choices and grids
Example 11: Tower of Hanoi
Move n discs from peg A to peg C using peg B, one at a time, never putting a larger disc on a smaller one. To move n discs, move n - 1 out of the way, move the biggest, then move the n - 1 back on top. The number of moves is 2 to the power n, minus 1.
moves = []
def hanoi(n, src, dst, spare):
if n == 0:
return
hanoi(n - 1, src, spare, dst) # move n-1 discs out of the way
moves.append(f"{src}->{dst}") # move the biggest disc
hanoi(n - 1, spare, dst, src) # put the n-1 discs back on top
hanoi(3, "A", "C", "B")
print(len(moves), "moves:", " ".join(moves))
print("moves for n=10:", 2**10 - 1)Output: 7 moves: A->C A->B C->B A->C B->A B->C A->C and moves for n=10: 1023. The call tree has depth n and 2 to the n minus 1 calls that do work. Base case: n is 0, do nothing.
Examples 12 and 13: permutations and subsets
Both build answers by making a choice and recursing on what remains, which is the core of backtracking. Permutations picks each item as the first element in turn; subsets decides, for the first item, whether it is in or out.
def permutations(items):
if len(items) <= 1:
return [items[:]]
result = []
for i in range(len(items)):
rest = items[:i] + items[i + 1:]
for p in permutations(rest):
result.append([items[i]] + p)
return result
def subsets(items):
if not items:
return [[]]
without_first = subsets(items[1:])
with_first = [[items[0]] + s for s in without_first]
return without_first + with_first
print(permutations([1, 2, 3]))
print(subsets(["a", "b", "c"]))Output: all six permutations of [1, 2, 3], starting [1, 2, 3], [1, 3, 2], [2, 1, 3], then the eight subsets of a, b, c, starting with []. A list of n items has n factorial permutations and 2 to the n subsets, so both explode quickly: n = 10 gives 3,628,800 permutations.
Example 14: flood fill on a grid
Recolour all cells connected to a start cell that share its colour, as the paint bucket tool does. Each call spreads to four neighbours. It needs two base cases, off the grid and wrong colour, and the fill itself acts as the visited marker. This is the recursive form of the BFS vs DFS grid traversals.
def flood_fill(image, r, c, new):
old = image[r][c]
if old == new:
return image
def fill(r, c):
if not (0 <= r < len(image) and 0 <= c < len(image[0])):
return # base case 1: off the grid
if image[r][c] != old:
return # base case 2: different colour
image[r][c] = new
fill(r + 1, c); fill(r - 1, c); fill(r, c + 1); fill(r, c - 1)
fill(r, c)
return image
image = [
[1, 1, 0],
[1, 0, 0],
[1, 1, 1],
]
for row in flood_fill(image, 0, 0, 7):
print(row)Output: three rows, [7, 7, 0], [7, 0, 0], [7, 7, 7]. The cells with 1 connected to the top-left corner became 7; the zeros stayed.
Common recursion bugs and what they look like
The most common failure is a missing or unreachable base case. The next block runs a function with no base case and shows what Python does.
import sys
def broken(n):
return n * broken(n - 1) # no base case
try:
broken(5)
except RecursionError as e:
print("RecursionError:", str(e)[:40])
print("default limit:", sys.getrecursionlimit())
def total(n):
return 0 if n == 0 else n + total(n - 1)
try:
total(5000)
except RecursionError:
print("total(5000) fails; total(500) =", total(500))Output: RecursionError: maximum recursion depth exceeded, default limit: 1000, then total(5000) fails; total(500) = 125250. CPython's default limit is 1000 frames, per the sys module docs, so correct code can also fail on large input.
| Bug | Symptom | Fix |
|---|---|---|
| No base case | RecursionError | Write the smallest-input return first |
| Base case never reached (n - 1 skipped, or n goes below 0) | RecursionError or wrong answer | Check that every call strictly shrinks the input toward the base |
| Forgetting to return the recursive call | Function returns None | Write return f(...) or combine and return |
| Two overlapping calls (naive Fibonacci) | Slow, exponential time | Memoise, or turn it into a loop |
| Mutating a shared list or default argument | Results leak between calls | Copy before changing, or undo the choice after the call |
| Deep but correct recursion | RecursionError on big input | Convert to a loop with a stack, or use a smaller input |
| Slicing strings and lists in every call | Slow, O(n squared) | Pass indexes instead of slices |
A reliable way to debug is to print the arguments on entry for a tiny input, then read the printed lines as the call tree. For more practice questions, the coding practice websites list has problem sets, and DSA interview questions shows which of these appear most often.
Frequently asked questions
What are some simple examples of recursion?
The simplest are factorial, sum of digits, reversing a string, checking a palindrome and Fibonacci. Each has a clear base case (n is 0 or 1, or a string of length 0 or 1) and a call on a smaller input. Start with factorial, then try the digit sum, which shrinks by a digit each call.
How do you write a recursive function in Python?
Write the base case first, the smallest input and its answer. Then write the recursive step: call the function on a smaller input and combine the result with the current one. Make sure every call moves strictly toward the base case, and remember Python's default limit of 1000 frames.
What is the base case in recursion?
The base case is the input for which the function returns directly without calling itself. In factorial it is n less than or equal to 1, and in binary search it is an empty range. Without a reachable base case the calls never stop and Python raises RecursionError.
Why is recursive Fibonacci slow?
Each call makes two more calls, and the same values are computed many times over. For n = 20 the naive version makes 21,891 calls, and the count grows exponentially. Caching each result with memoisation cuts that to 39 calls here, one computation per value.
Is recursion better than a loop?
Neither is better in general. Recursion matches problems that split into smaller copies, such as trees, permutations and flood fill, and reads clearly. Loops are faster in Python and avoid the recursion limit. For simple counting and summing, use a loop; for branching structures, recursion is natural.
How do I stop RecursionError in Python?
First check the base case and that the input shrinks on every call. If the code is correct but the depth is large, rewrite it with a loop and an explicit stack. You can raise the limit with sys.setrecursionlimit, but a very deep recursion can still crash the interpreter, so use it with care.
Learn this with mentors
Programmes for builders and engineers with admissions open: live classes, mentors and project work.


