SproutStackSproutStack home

Recursion Intuition

6 min readBeginner-friendlyFree to read

Read a little, play a little. No scary maths, and no rush.

Share:

Russian dolls

A recursive function is a set of Russian dolls: each doll contains a smaller version of the same problem, down to a tiny solid doll that contains nothing — the base case. Two ingredients, no more: (1) an answer for the tiniest input, (2) a rule that shrinks every other input toward it.

def fact(n):
    if n <= 1:
        return 1          # base: the solid doll
    return n * fact(n - 1)  # leap: trust fact(n-1), finish the job

The leap of faith (the whole skill)

Don't trace five levels deep — you'll drown. Instead ask one question: "If the smaller call returns the right answer, can I finish?" For factorial: if fact(n−1) is correct, multiplying by n is obviously correct. Draw one level, trust the rest. This mindset is what makes tree and DP recursion readable later.

Fibonacci and the price of naivety

def fib(n):
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)

Beautiful, correct — and exponential, because subproblems overlap (fib(3) recomputed endlessly). The fix previews two huge topics: memoize results (top-down DP) or iterate bottom-up. When an interviewer asks "can you make it faster?", that is the expected answer.

Watching the call stack

Each recursive call gets its own copy of its variables, stacked on top of the caller's. Here is fact(3):

  1. fact(3) needs fact(2), so it waits.
  2. fact(2) needs fact(1), so it waits too.
  3. fact(1) hits the base case and returns 1.
  4. fact(2) receives 1 and returns 2 × 1 = 2.
  5. fact(3) receives 2 and returns 3 × 2 = 6.

Calls pile up on the way down and resolve on the way back up. The stack is n calls deep at its peak, which is why this recursion uses O(n) space even though it creates no lists.

Where recursion feels natural: trees

Some problems are recursive by nature. The depth of a binary tree is one more than the depth of its deeper subtree:

def depth(node):
    if node is None:
        return 0                                      # empty tree
    return 1 + max(depth(node.left), depth(node.right))

Base case: an empty tree has depth 0. Leap of faith: if depth is right for both subtrees, adding 1 for the current node is right for the whole tree. Writing this with a loop is possible but noticeably clumsier, which is why trees and recursion are taught together.

The two ways recursion dies

  • No base case (or one never reached): infinite descent → stack overflow.
  • No progress: calling f(n) from f(n) — every call must shrink toward the base.

Recursion versus loops

Any recursive function can be rewritten as a loop with an explicit stack, and the reverse is true too. Choose whichever reads more clearly, with one practical caution: Python limits recursion depth to about 1,000 calls by default. A recursive walk over a 100,000-item linked list will crash where a loop would not. In interviews either style is accepted if it is correct, and mentioning the depth limit when inputs are large is a good sign of experience. For memoization, Python's functools.lru_cache decorator adds a cache to a recursive function in one line.

Remember this

  • Base + shrink + trust. Trace one level, never five.
  • Overlapping subcalls → memoize: you've just discovered dynamic programming.

Check your understanding

5 questions · first-try answers earn the most XP

1. What two ingredients does every correct recursive function need?
2. Why does naive Fibonacci become exponentially slow?
3. What does a stack overflow in a recursive function usually indicate?
4. The chapter says to trace one level of recursion and trust the rest. Why?
5. What is the key structural difference between factorial and naive Fibonacci?

My notes

Saved in this browser. Highlight a line above and save it, or write it in your own words.

Nothing saved yet. Your highlights will live here.

References

Finished reading?

Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.

End of Warmup (Code Confidence)

Take the section checkpoint

A short mixed quiz on all 3 chapters, to check you are ready to move on.

Related chapters

Spotted a mistake or want a topic covered? Report an issue

📬 An occasional email when new lessons land

New lessons and showdowns, no more than a few times a month. No spam, unsubscribe anytime. We store your email only to send the newsletter.