VOOZH about

URL: https://www.geeksforgeeks.org/dsa/what-is-the-difference-between-auxiliary-space-and-space-complexity/

⇱ What is the difference between Auxiliary space and Space Complexity? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

What is the difference between Auxiliary space and Space Complexity?

Last Updated : 6 Dec, 2023

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:

  • Auxiliary Space: The extra space that is taken by an algorithm temporarily to finish its work
  • Space Complexity: Space complexity is the total space taken by the algorithm with respect to the input size plus the auxiliary space that the algorithm uses.

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.


Output
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:

  • arr[]: Since this variable will store n elements of Array, so the space for arr[] will be O(n)
  • n: This variable will store only the size of the Array, so the space for n will be O(1)
  • sum: Similarly, sum stores only the sum of Array, so its space will also be O(1)

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.

Comment