What is Space Complexity?
Space complexity is the amount of memory required by an algorithm to run to completion. It is concerned with the amount of memory an algorithm uses as the size of the input data increases.
There are two types of space complexity: static and dynamic. Static space complexity is the amount of memory required by an algorithm for a specific input size. Dynamic space complexity is the amount of memory required by an algorithm as the input size increases.
Static space complexity is usually easy to calculate. For example, if an algorithm requires an array of size n, then the static space complexity is O(n).
Dynamic space complexity is usually more difficult to calculate. For example, if an algorithm requires an array of size n and the size of the array increases by 1 each time the algorithm is run, then the dynamic space complexity is O(n).
To calculate the space complexity of an algorithm, we need to know the following:
For example, let's say we have an algorithm that requires an array of size n. If the size of the array increases by 1 each time the algorithm is run, then the dynamic space complexity is O(n).
To calculate the space complexity of an algorithm, we need to know the following:
For example, let's say we have an algorithm that requires an array of size n. If the size of the array increases by 1 each time the algorithm is run, then the dynamic space complexity is O(n).
To calculate the space complexity of an algorithm, we need to know the following:
For example, let's say we have an algorithm that requires an array of size n. If the size of the array increases by 1 each time the algorithm is run, then the dynamic space complexity is O(n).
Let's take a look at an example.
Consider the following algorithm:
int findMax(int array[], int n) {
int max = array[0];
for (int i = 1; i < n; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
This algorithm has a static space complexity of O(1), because it only requires one variable to store the maximum value.
Now, let's say we have an algorithm that requires an array of size n and the size of the array increases by 1 each time the algorithm is run. In this case, the dynamic space complexity is O(n).
To calculate the space complexity of an algorithm, we need to know the following:
For example, let's say we have an algorithm that requires an array of size n. If the size of the array increases by 1 each time the algorithm is run, then the dynamic space complexity is O(n).