0% completed
In this lesson, we’ll explore the space complexity of recursive algorithms. Unlike iterative algorithms, recursive algorithms often require additional space for each function call made during the recursion. This lesson will help you understand how to measure and analyze the space complexity of recursive functions.
Example: Recursive Factorial
Let’s examine a simple recursive algorithm for calculating the factorial of a number:
Step-by-Step Space Complexity Analysis
Step 1: Recognize the Depth of Recursion
The depth of recursion refers to the maximum number of recursive calls active at any one time.
- For
factorial(n)
, the recursion depth depends onn
because each call tofactorial
makes a single recursive call withn - 1
. - Starting with
factorial(n)
, the function callsfactorial(n - 1)
, thenfactorial(n - 2)
, and so on, until reaching the base case whenn = 0 or 1
. - So, if
n = 5
, the call stack will holdfactorial(5)
,factorial(4)
,factorial(3)
,factorial(2)
, andfactorial(1)
before reaching the base case.
In this case, the recursion depth is n
.
Step 2: Determine Memory Used per Recursive Call (Stack Frame)
Each recursive call to factorial
requires a stack frame. A stack frame is a memory block that stores:
- Parameters (
n
in this case) - Local variables (none here, as there’s no additional variable in the function)
- Return address (to continue execution after a recursive call)
In general, each call to factorial
has constant space usage, or O(1)
, because the amount of memory required per call does not change with n
.
Step 3: Calculate Total Space Complexity
The total space complexity is the product of the recursion depth and the space per call.
- Recursion Depth:
O(n)
(from Step 1). - Space per Call:
O(1)
(from Step 2).
Thus, the overall space complexity of factorial(n)
is:
Time Complexity = O(n) \times O(1) = O(n)
In recursive functions, each call occupies a new place in memory, even though it performs a similar task as the previous call. Each call is saved in memory until it completes, which is why the stack grows with each recursive call. For factorial(n)
, the stack holds up to n
calls at once, so it grows linearly with n
.
.....
.....
.....
Table of Contents
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible