![]() |
VOOZH | about |
Space complexity and Auxiliary space are two of the most often confused and interchangeably used terms when talking about the space complexity of a certain algorithm:
Let us understand with the help of an example:
Example: Program to find the sum of an Array
Consider the below code to find the sum of an Array.
Sum of given array is 34
In this program, as you can see, we have an Array, a variable to store the size of the Array, and the variable to store the sum of Array. So the space occupied by each variable will be:
Now let us try to compute the overall space complexity of the above code. It will be:
max(all space used by variables) = max (n, 1, 1) = O(n)
Now let us try to compute the overall auxiliary space complexity of the above code.
Note: In this case, we cannot consider the space occupied by the Array itself, as it is required as an input in this problem.
Therefore, the auxiliary space for above code will be:
max(all space used by variables) = max (1, 1) = O(1)
Now although the code remains the same, the Space complexity for the above code will be O(n), whereas Auxiliary space for the same will be O(1), as the initial input space is not considered.