Back to website
Mayank Aggarwal Learning Center

Phase 03 · DSA & Problem SolvingLesson 3 of 4

Recursion from Basics to Advanced

Solve problems by having a function call itself on smaller inputs.

  • 2:29:42 video
  • 2 min read
  • Intermediate
  • Deep dive
01

The problem

Some problems are naturally made of smaller copies of themselves: a folder containing folders, a tree of comments with replies, a list whose sum is "the first item plus the sum of the rest". Recursion solves these by having a function call itself on a smaller version of the problem.

02

The concept

Deep dive: 2h 30m video. You don’t need it all in one sitting. Watch the first 20 minutes for the core idea, read the write-up below, and come back for the rest when you need it.

The two essential parts#

Every recursive function needs:

  1. A base case: the smallest version of the problem, answered directly, with no further calls.
  2. A recursive case: break the problem into a smaller piece and call the function on it.
Python
def factorial(n):
    if n <= 1:              # base case
        return 1
    return n * factorial(n - 1)   # recursive case

factorial(4)   # 4 * 3 * 2 * 1 = 24

What actually happens: the call stack#

Each call waits for the call it made to finish. Python keeps these waiting calls on the call stack:

The call stack for factorial(4)

  1. factorial(4)waits on 4 * factorial(3)
  2. factorial(3)waits on 3 * factorial(2)
  3. factorial(2)waits on 2 * factorial(1)
  4. factorial(1) returns 1base case reached
  5. factorial(2) returns 22 * 1 = 2
  6. factorial(3) returns 63 * 2 = 6
  7. factorial(4) returns 244 * 6 = 24

The calls go down until the base case, then the results flow back up.

Recursion with lists#

Python
def sum_list(nums):
    if not nums:                         # base case: empty list
        return 0
    return nums[0] + sum_list(nums[1:])  # first + sum of the rest

sum_list([3, 5, 2])   # 10

Thinking pattern: "If I already had the answer for the smaller list, how would I use it?"

When to use recursion#

Recursion shines when data is hierarchical or a problem divides into similar sub-problems:

  • Walking a folder tree or a JSON structure of unknown depth
  • Tree and graph traversal (depth-first search)
  • Divide-and-conquer algorithms such as merge sort and quick sort
  • Generating combinations and permutations (backtracking)
Python
def count_files(folder):
    total = 0
    for item in folder.children:
        if item.is_file:
            total += 1
        else:
            total += count_files(item)   # same problem, smaller folder
    return total

Why it matters#

Recursion is a core interview topic and the foundation of the sorting algorithms in the next lesson. It also appears in AI work, for example when recursively splitting long documents into chunks for RAG, or traversing a nested JSON response from an API.

03

Try it

Your task · about 10 minutes

Write factorial(n) and sum_list(nums) recursively, and identify the base case in each.

Use the interactive visual above to explore it step by step
04

Recap & next

Key takeaways

  1. A recursive function calls itself on a smaller version of the problem.
  2. Every recursion needs a base case that stops it; without one you get a RecursionError.
  3. Each call waits on the call stack until the calls it made return.
  4. Many tree, graph and divide-and-conquer problems are naturally recursive.

Quick check

2 questions · instant feedback

1What stops a recursive function from running forever?
2Where are pending recursive calls stored?

Finished this lesson?

Mark it complete to track your progress and keep your streak going.

Next