In this section, we’ll explore how to analyze the complexity of recursive functions, a topic often perceived as challenging, but highly important in computer science.
To determine the complexity of a recursive function, we follow these general steps:
- Compute the complexity of a single recursive call.
- Count the total number of recursive calls as a function of input size.
- Multiply the number of calls by the single call complexity.
Example 1: A Simple Recursive Chain
Consider the following function:
def foo(n):
if n == 1:
return
foo(n - 1)
Here’s how to evaluate its complexity:
- The body of the function does not depend on
n, so:
- Let’s draw the recursive call chain for
:
foo(4)
└── foo(3)
└── foo(2)
└── foo(1)
As we see, there are
recursive calls. Therefore:
![]()
![]()
Example 2: A Recursive Tree with Multiple Calls
Now consider a slightly different function:
def bar(n):
if n == 1:
return
bar(n - 1)
bar(n - 1)
Again, the body doesn’t depend on
, so:
![]()
Let’s analyze the recursive call tree for
:
bar(4)
├── bar(3)
│ ├── bar(2)
│ │ ├── bar(1)
│ │ └── bar(1)
│ └── bar(2)
│ ├── bar(1)
│ └── bar(1)
└── bar(3)
├── bar(2)
│ ├── bar(1)
│ └── bar(1)
└── bar(2)
├── bar(1)
└── bar(1)
This forms a binary tree, where each node creates 2 recursive calls.
Let’s compute the number of nodes in this tree:
- Level 0 has
node - Level 1 has
nodes - Level 2 has
nodes - Level 3 has
nodes
So the total number of calls is:
![]()
In general, for
levels:
![]()
Thus, total complexity:
![]()
General Formula for Recursive Tree Complexity
Let:
be the number of recursive calls per invocation
be the number of levels in the recursive call tree
be the complexity of a single call
Then the total complexity is:
![]()
From the previous example:
So:
![]()
What Determines the Number of Levels?
To determine
, observe:
- Initial value of the recursive parameter — typically

- Step size — e.g.,
per call - Base case termination — e.g.,

If the recursion goes from
to
with a step of
, then:
![]()
Applying the Formula: Final Example
def baz(n):
if n == 1:
return
baz(n - 1)
baz(n - 1)
We identify:
- Single call complexity:

- Number of recursive calls:

- Number of levels:

Using the formula:
![]()
Important Observations
When the number of recursive calls per level is
, it forms a chain, and the total complexity is:
![]()
If recursion occurs inside a loop, complexity analysis depends on the loop structure.
Summary of Recursive Complexity Formula
For most recursive functions with tree structure:
![]()
This formula is widely applicable but assumes:
- Fixed number of recursive calls per invocation
- No loop-based dynamic recursion count
