0% completed
In this lesson, we’ll explore how to analyze the space requirements of algorithms by looking at two examples. We’ll start with an algorithm that uses constant space O(1) and then move to one that requires O(n^2) space. Through these examples, we’ll learn how to calculate space complexity by examining variables, data structures, and other memory requirements.
Example 1: Finding the Maximum Element (Constant Space – O(1))
Let’s begin with a simple algorithm to find the maximum element in a list. This algorithm only needs a small, fixed amount of memory, regardless of the input size.
Algorithm Code
Step-by-Step Space Complexity Analysis
-
Input Storage:
- The input array
arr
has n elements, where n is the length of the list. However, input space is not counted in auxiliary space complexity, so we focus on the additional memory used by the algorithm.
- The input array
-
Auxiliary Space:
- Variable
max_val
: We use this variable to store the current maximum value. No matter how largen
is, this variable only takes up one unit of memory. - Loop Variable
num
: This variable stores each element inarr
as we iterate through it. Again, this requires only one unit of memory, asnum
is overwritten in each iteration.
- Variable
-
Total Space Complexity:
- Since we’re only storing a fixed number of variables (
max_val
andnum
), the memory required does not increase withn
. Therefore, the space complexity is O(1).
- Since we’re only storing a fixed number of variables (
Example 2: Matrix Multiplication (Quadratic Space – O(n^2))
Now, let’s look at an algorithm for multiplying two matrices. Here, we’ll require memory that grows with the size of the input, leading to a quadratic space complexity.
Algorithm Code
Step-by-Step Space Complexity Analysis
-
Input Storage:
- The matrices
A
andB
are both n \times n matrices, so each one requires n^2 memory units. But as with the first example, we focus on auxiliary space and ignore the memory used to store inputs.
- The matrices
-
Auxiliary Space:
- Output Matrix
result
: The result of multiplying two n \times n matrices is another n \times n matrix. We need to create this matrix to store the final product. Sinceresult
has n \times n elements, it takes up O(n^2) memory. - Loop Variables
i
,j
, andk
: These variables are used for iteration and only occupy a fixed amount of memory, which is O(1).
- Output Matrix
-
Total Space Complexity:
- The dominant space usage here is the
result
matrix, which requires n^2 memory units. Therefore, the space complexity is O(n^2).
- The dominant space usage here is the
.....
.....
.....
Table of Contents
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible