Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

Algorithms & Competitive Programming — Alpha School

Lesson 9: Thinking Recursively

Recursion is the idea of solving a problem by solving smaller versions of the same problem. A recursive function calls itself with a smaller input, until it reaches a base case — an input so small the answer is obvious — and then the answers combine on the way back up. It is one of the most powerful ideas in programming, and also one of the most confusing at first, because the function seems to be defined in terms of itself. The trick is to trust the contract: assume the recursive call works for the smaller input, and only worry about your own step.

The classic example is the factorial. The factorial of n is n times the factorial of n - 1, and the factorial of 0 is 1. That is the whole definition, and it translates directly into code. The same pattern solves many problems: the sum of a list is the first item plus the sum of the rest; a palindrome check compares the outer characters and recurses on the middle. The example below shows factorial and a recursive list sum side by side.

def factorial(n):
    if n == 0:          # base case
        return 1
    return n * factorial(n - 1)   # recursive case


def list_sum(items):
    if not items:       # base case: empty list
        return 0
    return items[0] + list_sum(items[1:])


print(factorial(5))       # 120
print(list_sum([1, 2, 3, 4]))  # 10

Two rules, and the classic mistakes

Every correct recursive function obeys two rules. First, it must have a base case that stops the recursion — without one, the function calls itself forever until Python hits its recursion limit and crashes. Second, every recursive call must move toward the base case: the input must get smaller in a way you can measure. If either rule is broken, the result is either an infinite recursion or a wrong answer. When a recursive function misbehaves, the first thing to check is always the base case, and the second is whether the input really shrinks.

Recursion is not just a coding trick; it is a way of thinking that the rest of this course depends on. Backtracking (Lesson 10) is recursion with a choice at each step. Dynamic programming (Lessons 11–12) is recursion with memory. Tree and graph traversals (Lessons 13–16) are recursion over a structure instead of a number. The habit to build now is the recursive leap of faith: write the base case, write the step assuming the smaller case works, and test it on the smallest inputs by hand. If it works for 0 and 1, and each step is correct, it works for everything.

Going further

Some languages optimise tail recursion — a recursive call that is the very last thing a function does — by reusing the current stack frame instead of adding a new one. Python does not do this, deliberately: the language's designers decided that the traceback, which shows the full chain of calls, is more valuable than the optimisation. The practical consequence is that deeply recursive Python code can hit the recursion limit, and the usual fixes are to rewrite the function iteratively, to raise the limit with sys.setrecursionlimit (which is safe only if you understand the risk), or to use an explicit stack.

Every recursive function can be rewritten as a loop with an explicit stack, and sometimes that is the right thing to do — for example, when the recursion would go thousands of calls deep. But the recursive version is usually clearer, and clarity is worth a great deal. A good rule is to write the recursive version first, understand the problem through it, and only convert to a loop if the depth or the speed demands it. The recursive form is the thinking tool; the loop is the optimisation.

A good way to build recursive thinking is to solve the same small problem twice: once with a loop, and once recursively. Take the sum of the numbers from 1 to n, or the task of reversing a string, and write both versions. The loop version will feel more direct, and the recursive version will feel like a trick — until you meet a problem where the recursive version is the direct one, such as walking a tree or exploring a maze. The two forms are equivalent in power, and the skill is knowing which one fits the shape of the problem in front of you, rather than forcing every problem into the shape you already know.

Key Terms

Recursion
Solving a problem by calling the same function on a smaller version of the problem.
Base case
The smallest input, where the answer is given directly and the recursion stops.
Recursive case
The step that breaks the problem into a smaller version of itself and combines the result.
Recursive leap of faith
Trusting that the recursive call works for the smaller input, and only reasoning about your own step.
Call stack
The stack of active function calls; each recursive call adds a frame.
Recursion limit
Python's cap on call-stack depth (usually 1,000 frames); deep recursion hits it.
Divide and conquer
A recursive pattern that splits a problem into independent smaller problems and combines their answers.

Discussion Questions

  1. Why is it safe to assume the recursive call works for the smaller input? What kind of reasoning makes that legitimate?
  2. What happens if you forget the base case in factorial? Trace factorial(2) without it.
  3. Some problems are naturally recursive (factorial, tree traversal) and some are not. What makes a problem a good fit for recursion?

Practice Questions

  1. What is the base case in the factorial function, and why is it needed?
  2. Trace list_sum([1, 2, 3]) by hand. What does the deepest call return?
  3. Write a recursive function countdown(n) that returns a list [n, n-1, ..., 1]. What is its base case?
  4. Why does recursion use stack space?
  5. A recursive function calls itself with the same input it received. What goes wrong?
Show answers
  1. n == 0 returns 1. Without it the function would call itself forever, decreasing n past zero.
  2. 0, for the empty list. Then the calls unwind: 3 + 0 = 3, 2 + 3 = 5, 1 + 5 = 6.
  3. def countdown(n): if n == 0: return [] return [n] + countdown(n - 1) The base case is n == 0, returning an empty list.
  4. Each call adds a frame to the call stack until it returns. A recursion n calls deep uses O(n) stack space.
  5. It never moves toward the base case, so it recurses forever. Every recursive call must shrink the problem in a measurable way.
Keep reading to complete this lesson