Skip to main content

Functions

Recursion

Complete lesson for Recursion using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.

L1

Basics — Recursion

Section: Functions. Recursion in Python — base case, recursive case, call stack, types of recursion, memoization with @lru_cache, and when to prefer a loop.

What is recursion?

  • Recursion is when a function calls itself (directly or indirectly) to solve a problem by breaking it into smaller copies of the same problem.
  • Every useful recursive function has two parts: a base case that stops, and a recursive case that calls itself with a smaller input.
  • Each call waits for the smaller call to finish. Results combine as the call stack unwinds.
  • Real-life analogy: Russian nesting dolls — open until the smallest doll (base case), then close in reverse order.
  • Real-life analogy: asking "how many people are ahead?" — each person asks the next; the front says 0; answers add 1 on the way back.
PartRoleExample (factorial)
Base caseStops further callsif n <= 1: return 1
Recursive caseCalls itself with a smaller inputreturn n * fact(n - 1)
ProgressEvery call must move toward the basen decreases by 1 each call
UnwindingCombine results while returning5 * 4 * 3 * 2 * 1 = 120
def fact(n: int) -> int:
    if n < 0:
        raise ValueError("n must be >= 0")
    if n <= 1:                       # base case
        return 1
    return n * fact(n - 1)           # recursive case

print(fact(5))                       # 120

How recursion works (call stack)

  • Every function call pushes a new frame on the CPython call stack: arguments, locals, and the return address.
  • When the base case returns, frames pop one by one and each caller finishes its pending work.
  • Too many frames (missing base case, or very deep input) raises RecursionError.
  • Trace small inputs (n = 0, 1, 2, 3) on paper before trusting large ones.
# Trace fact(4):
# fact(4) -> 4 * fact(3)      push
# fact(3) -> 3 * fact(2)      push
# fact(2) -> 2 * fact(1)      push
# fact(1) -> 1                base case, start popping
# fact(2) = 2 * 1  = 2        pop
# fact(3) = 3 * 2  = 6        pop
# fact(4) = 4 * 6  = 24       pop

How recursion works — flowchart, call stack & trace

Recursion solves a problem by calling the same function on a smaller input until a base case stops. Each call pushes a frame on the CPython call stack; when the base returns, frames pop and pending work finishes. The poster below traces fact(4) from push to unwind.

How recursion works in Python: flowchart with base case decision and recursive call, call stack frames for fact(4) pushing down to the base case then popping, Python factorial code, and an unwinding trace that multiplies back to 24.
How recursion works — base case, stack push/pop, and fact(4) → 24
  • Base case: stops further calls (n <= 1 → return 1).
  • Recursive case: call with a smaller input (n * fact(n - 1)).
  • Call stack: push frames going deeper; pop and combine on the way back.
  • Safety: missing base or huge depth → RecursionError (prefer a loop).

Design rules for a recursive function

  • Write the base case first. Then make a call that moves toward it (n - 1, mid, a shorter string, a child node).
  • Multiple base cases are normal: empty tree, n == 0 and n == 1 for Fibonacci, lo > hi for binary search.
  • Use a private helper (_search(arr, key, lo, hi)) and a clean public function (search(arr, key)).
  • Do not do the same work twice: if two branches need the same sub-result, compute it once or memoize.

Types of recursion

  • Interviewers often ask you to name and identify these.
TypeMeaningPython example
DirectA function calls itselffact(n) calls fact(n - 1)
Indirect (mutual)Functions call each other in a cycleis_even(n) calls is_odd(n - 1)
TailRecursive call is the last actionreturn gcd(b, a % b)
Non-tail (head)Work remains after the call returnsreturn n * fact(n - 1)
LinearOne recursive call per invocationSum of list, linked-list length
Tree (multiple)Two or more calls per invocationfib(n - 1) + fib(n - 2), tree walk
NestedArgument is itself a recursive callAckermann A(m - 1, A(m, n - 1))

Classic recursion examples

ProblemBase caseRecursive idea
Factorialn <= 1 returns 1n * fact(n - 1)
Fibonaccin <= 1 returns nfib(n - 1) + fib(n - 2) (slow without memo)
Sum of digitsn == 0 returns 0n % 10 + sum_digits(n // 10)
Power x**nn == 0 returns 1x * power(x, n - 1) or halve n
GCD (Euclid)b == 0 returns agcd(b, a % b)
Binary searchlo > hi returns -1Recurse into the left or right half
List lengthxs == [] returns 01 + length(xs[1:])
Tower of Hanoin == 0 does nothingMove n-1, move largest, move n-1

Tower of Hanoi

  • Move n disks from peg A to peg C using helper peg B. Only one disk moves at a time and a larger disk never sits on a smaller one.
  • Recursive idea: move n - 1 disks to the helper, move the largest disk to the target, then move the n - 1 disks onto it.
  • Number of moves is 2**n - 1 (3 disks need 7 moves).
def hanoi(n: int, src: str, dst: str, via: str) -> None:
    if n == 0:                       # base case
        return
    hanoi(n - 1, src, via, dst)
    print(f"Disk {n}: {src} -> {dst}")
    hanoi(n - 1, via, dst, src)

hanoi(3, "A", "C", "B")              # 7 moves

Applications of recursion

  • Use recursion when the problem or the data naturally splits into smaller copies of itself.
  • It is strongest for hierarchical data (trees, folders, JSON), search with undo (backtracking), and divide-and-conquer algorithms.
Application areaWhy recursion fitsPython example
MathematicsDefinition refers to a smaller nFactorial, Fibonacci, GCD, power
SearchingEach step halves the search spaceRecursive binary search
Sorting (divide and conquer)Split, solve halves, combineMerge sort, quick sort
Tree / ASTEvery child is a smaller treeInorder walk, height, expression trees
Graph algorithmsVisit a node, then neighboursDFS, cycle detection
BacktrackingChoose, recurse, undoN-Queens, Sudoku, maze, subsets
CombinatoricsInclude / exclude decisionsPermutations, power set
Dynamic programmingRecursion plus a cachefunctools.lru_cache, memo dict
File systemsFolders contain folderspathlib.Path.rglob, recursive size
ParsingGrammar rules are nestedRecursive-descent expression parser

Differences between recursion and iteration

  • Both repeat work. Choose based on clarity, input depth, and performance.
PointRecursionIteration (loops)
ApproachFunction calls itselfUses for / while
TerminationBase caseLoop condition becomes false
MemoryOne stack frame per active callUsually constant extra memory
Failure modeRecursionError if too deepInfinite loop if condition never fails
SpeedCall overhead; can repeat workUsually faster for simple counting
Best forTrees, graphs, backtracking, D&CLinear scans, counters, very deep inputs

When to use recursion vs a loop

  • Prefer recursion when the data is hierarchical (trees, folders, JSON) or the problem is self-similar (Hanoi, merge sort, backtracking).
  • Prefer a loop for simple 1..n accumulation, list scans, and any input whose depth could reach thousands.
  • Any recursion can be rewritten as a loop with an explicit stack (list used as a stack). That is the standard fix for deep inputs in CPython.
L2

Advanced — Recursion

Memoization with @lru_cache

  • Naive fib(n) makes about φ^n calls (exponential). Memoize to get O(n).
  • functools.lru_cache(maxsize=None) caches results by arguments. Arguments must be hashable.
  • Interviewers expect you to mention memoization or bottom-up DP as the fix for exponential recursion.
from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n: int) -> int:
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)

print(fib(90))                       # 2880067194370816120
print(fib.cache_info())

Direct vs indirect recursion

  • Direct: f calls f. Indirect (mutual): f calls g and g calls f.
  • Indirect recursion appears in recursive-descent parsers: expression() → term() → factor() → expression() for brackets.
def is_even(n: int) -> bool:
    if n == 0:
        return True
    return is_odd(n - 1)

def is_odd(n: int) -> bool:
    if n == 0:
        return False
    return is_even(n - 1)

print(is_even(10), is_odd(7))        # True True

Divide and conquer: merge sort

  • Divide the list into halves, sort each half recursively, then merge the two sorted halves.
  • Recursion depth is only about log2(n), so it is safe even for large lists.
  • Time O(n log n); extra memory O(n) for the temporary lists.
def merge_sort(a: list[int]) -> list[int]:
    if len(a) <= 1:                  # base case
        return a
    mid = len(a) // 2
    left = merge_sort(a[:mid])
    right = merge_sort(a[mid:])
    return merge(left, right)

def merge(left: list[int], right: list[int]) -> list[int]:
    out: list[int] = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            out.append(left[i]); i += 1
        else:
            out.append(right[j]); j += 1
    out.extend(left[i:])
    out.extend(right[j:])
    return out

print(merge_sort([38, 27, 43, 3, 9, 82, 10]))

Backtracking pattern

  • Backtracking: choose, recurse, undo, try the next choice.
  • Used for N-Queens, Sudoku, maze paths, subsets, and permutations.
def subsets(nums: list[int], i: int = 0, cur: list[int] | None = None) -> None:
    if cur is None:
        cur = []
    if i == len(nums):               # base case: decided every element
        print(cur)
        return
    subsets(nums, i + 1, cur)        # exclude nums[i]
    cur.append(nums[i])              # choose
    subsets(nums, i + 1, cur)        # include
    cur.pop()                        # undo (backtrack)

subsets([1, 2, 3])

sys.getrecursionlimit and RecursionError

  • CPython default recursion limit is typically 1000 (sys.getrecursionlimit()).
  • sys.setrecursionlimit can raise it, but a crash (stack overflow in C) is possible — prefer iteration for deep inputs.
  • Never "fix" a RecursionError by catching it and continuing blindly; fix the algorithm.
import sys

print(sys.getrecursionlimit())       # often 1000

def boom(n: int) -> int:
    return boom(n + 1)

try:
    boom(0)
except RecursionError as e:
    print(type(e).__name__, "-", e)

Recursion safety checklist

  • Write the base case first and test it alone.
  • Make sure every recursive path moves closer to the base.
  • Test n = 0, n = 1, and one medium value with a paper trace.
  • Use @lru_cache or a dict when the call tree repeats sub-problems.
  • If depth may reach thousands, use iteration or an explicit stack.
  • Prefer pathlib / os.walk for directory trees instead of hand-rolled deep recursion when possible.
L3

Tricky Interview Points

Q1) What is recursion?

Answer A technique where a function solves a problem by calling itself on a smaller sub-problem until a base case stops the calls.

Q2) What are the base case and the recursive case?

Answer The base case returns a result without another recursive call. The recursive case calls the function again with a smaller input and combines the result.

Q3) What happens if there is no base case?

Answer The calls never stop. Each call adds a stack frame until Python raises RecursionError.

Q4) Recursion vs iteration?

Answer Recursion uses function calls and stack memory; iteration uses loops and usually constant memory. Recursion is clearer for trees and backtracking; iteration is safer for deep linear work. Any recursion can be converted to iteration with an explicit stack.

Q5) Does CPython optimize tail recursion?

Answer No. Even a tail-recursive function uses one frame per call. Prefer a loop for large n.

Q6) Why is naive recursive Fibonacci slow? How do you fix it?

Answer It recomputes the same sub-problems (exponential calls). Fix with functools.lru_cache, a memo dict, bottom-up DP, or a simple loop — all O(n).

Q7) What is backtracking?

Answer A recursive search that makes a choice, recurses, and undoes the choice before trying the next option. Used for N-Queens, Sudoku, subsets, and permutations.

Q8) How many moves does Tower of Hanoi need for n disks?

Answer 2**n - 1 moves. For 3 disks that is 7.

Q9) Direct vs indirect recursion?

Answer Direct: a function calls itself. Indirect (mutual): functions call each other in a cycle, such as is_even calling is_odd and is_odd calling is_even.

Q10) What is the default recursion limit? How do you change it?

Answer Typically 1000 via sys.getrecursionlimit(). sys.setrecursionlimit(n) changes it, but deep recursion can still crash the interpreter; prefer iterative solutions.

Q11) What is the space complexity of recursive factorial?

Answer O(n), because n stack frames are active at the deepest point. An iterative loop uses O(1) extra space.

Q12) When should you avoid recursion in Python?

Answer When input depth can exceed a few hundred/thousand (long linked lists, deep folder trees with naive recursion), or when a simple loop is clearer and faster.

L4

Simple Programs

Factorial and sum of digits

def fact(n: int) -> int:
    if n <= 1:
        return 1
    return n * fact(n - 1)

def sum_digits(n: int) -> int:
    if n == 0:
        return 0
    return n % 10 + sum_digits(n // 10)

print(fact(10))          # 3628800
print(sum_digits(1234))  # 10

Fibonacci: naive vs memoized

from functools import lru_cache

def fib_naive(n: int) -> int:
    if n <= 1:
        return n
    return fib_naive(n - 1) + fib_naive(n - 2)

@lru_cache(maxsize=None)
def fib_memo(n: int) -> int:
    if n <= 1:
        return n
    return fib_memo(n - 1) + fib_memo(n - 2)

print(*(fib_naive(i) for i in range(10)))  # 0 1 1 2 3 5 8 13 21 34
print(fib_memo(50))                        # 12586269025

Reverse a string and check palindrome

def reverse(s: str) -> str:
    if len(s) <= 1:
        return s
    return reverse(s[1:]) + s[0]

def is_palindrome(s: str) -> bool:
    if len(s) <= 1:
        return True
    if s[0] != s[-1]:
        return False
    return is_palindrome(s[1:-1])

print(reverse("recursion"))       # noisrucer
print(is_palindrome("madam"))     # True
print(is_palindrome("python"))    # False

Tower of Hanoi with move count

moves = 0

def hanoi(n: int, src: str, dst: str, via: str) -> None:
    global moves
    if n == 0:
        return
    hanoi(n - 1, src, via, dst)
    moves += 1
    print(f"Move disk {n} from {src} to {dst}")
    hanoi(n - 1, via, dst, src)

hanoi(3, "A", "C", "B")
print("Total moves =", moves)  # 7

Recursive binary search

def binary_search(a: list[int], key: int, lo: int = 0, hi: int | None = None) -> int:
    if hi is None:
        hi = len(a) - 1
    if lo > hi:
        return -1
    mid = lo + (hi - lo) // 2
    if a[mid] == key:
        return mid
    if key < a[mid]:
        return binary_search(a, key, lo, mid - 1)
    return binary_search(a, key, mid + 1, hi)

data = [2, 4, 6, 8, 10, 12]
print(binary_search(data, 10))  # 4
print(binary_search(data, 5))   # -1

N-Queens (backtracking)

def n_queens(n: int) -> int:
    cols: list[int] = [-1] * n
    solutions = 0

    def safe(row: int, col: int) -> bool:
        for r in range(row):
            if cols[r] == col or abs(cols[r] - col) == row - r:
                return False
        return True

    def place(row: int) -> None:
        nonlocal solutions
        if row == n:
            solutions += 1
            return
        for c in range(n):
            if safe(row, c):
                cols[row] = c
                place(row + 1)

    place(0)
    return solutions

print("8-Queens solutions:", n_queens(8))  # 92

Flood fill (paint bucket)

def flood_fill(grid: list[list[str]], r: int, c: int, target: str, repl: str) -> None:
    rows, cols = len(grid), len(grid[0])
    if r < 0 or c < 0 or r >= rows or c >= cols:
        return
    if grid[r][c] != target:
        return
    grid[r][c] = repl
    flood_fill(grid, r + 1, c, target, repl)
    flood_fill(grid, r - 1, c, target, repl)
    flood_fill(grid, r, c + 1, target, repl)
    flood_fill(grid, r, c - 1, target, repl)

g = [list(row) for row in ["..##", ".#..", "...."]]
flood_fill(g, 0, 0, ".", "*")
for row in g:
    print("".join(row))
# **##
# *#**
# ****
L5

Problem Solving Tricks

  • Write the base case first, then the recursive step that moves toward it.
  • Ask "what is the smallest version of this problem?" — that is your base case.
  • Trust the recursion: assume the smaller call already works, and only write how to combine its answer.
  • Print a depth-indented trace while learning: print(" " * depth, n).
  • If you see the same arguments twice in a call tree, add @lru_cache or a memo dict.
  • Use a helper with extra parameters (lo, hi, index, depth) and keep the public API simple.
  • For trees, always ask: can the node be None? Handle that as the base case.
  • For backtracking, remember three steps: choose, recurse, undo.
  • CPython does not do TCO — rewrite deep tail recursion as a loop.
  • If depth might exceed a few thousand, use an explicit stack before it fails in production.
L6

Practice Programs List

  1. Write recursive sum_list(a, i) that sums the list from index i to the end.
  2. Find the maximum element of a list recursively.
  3. Count the number of digits in an integer recursively.
  4. Compute GCD and LCM with Euclid recursion.
  5. Compute nCr using Pascal identity, then add @lru_cache.
  6. Convert a decimal number to binary using recursion.
  7. Print all permutations of a string; handle duplicates for input "AAB".
  8. Generate all subsets of {1, 2, 3, 4} whose sum is 5.
  9. Solve a maze in a list[list[str]] grid with backtracking and mark the path.
  10. Write recursive inorder / preorder / postorder for a binary tree.
  11. Count all .py files under a folder using pathlib recursion.
  12. Evaluate a simple expression like 2 * (3 + 4) with a recursive-descent parser.
  13. Rewrite recursive folder-size iteratively using a list as a stack.
  14. Draw the call tree for fib(5) on paper, count the calls, then memoize and count again.