2. Introduction to Space complexity
Calculation of Space Complexity
for an Algorithm
Example of Space Complexity for
an Algorithm
3. INTRODUCTION TO SPACE COMPLEXITY
Space complexity refers to the amount of memory or storage
space required by an algorithm to solve a problem.
Space complexity is usually measured in terms of the number of
bits or bytes required to store the data used by the algorithm.
This includes both the input data and any additional memory
used by the algorithm during its execution.
4. CALCULATION OF SPACE COMPLEXITY FOR AN ALGORITHM
Space complexity of an algorithm is sum of space required for fixed part of algorithm and space
required for variable part of algorithm.
Space Complexity = Space required for fixed part +Space required for
variable part
Space Complexity = Space required for fixed part + Space required for variable
part
To estimate the memory requirement we need to focus on two parts:
(1) A fixed part: It is independent of the input size. It includes memory for instructions
(code), constants, variables, etc.
(2) A variable part: It is dependent on the input size. It includes memory for recursion stack,
referenced variables, etc.
5. Under fixed part, the space for the following is considered
1) Codeofalgorithm
2) Simplevariablesorlocalvariables
3) Definedconstants
Under variable part, the space for the following is considered
1) Variableswhosesizevariesfromoneinstanceoftheproblemtoanotherinstance(arrays,structuresandsoon)
2) Globalorreferencedvariables
3) Recursionstack
Recursion stack space is considered only for recursive algorithms. For each call of recursive
algorithm, the following information is stored in recursion stack
1) Valuesofformalparameters
2) Valuesoflocalvariables
3) Returnvalue
6. Example: Calculate space complexity of the following algorithm
Algorithm Add(a, b)
{
c := a + b;
write c;
}
Space complexity=space for fixed part + space for variable part
Space for fixed part:
Space for code=c words
Space for simple variables=3 (a, b, c) words
Space for defined constants=0 words
7. Space for variable part:
Space for arrays=0 words
Space for global variables=0 words
Space for recursion stack=0 words
Space complexity=c+3 +0+0+0+0=(c+3) words
8. Example : calculate space complexity for the following recursive algorithm
Algorithm Rsum(a, n)
// a is an array of size
{
if n = 0 then
return 0;
else
return a[n] + Rsum(a, n-1);
}
Space for fixed part:
Space for code=c words
Space for simple variables=1 (n) word
Space for defined constants=0 words
9. Space for variable part:
Space for arrays=n words
Space for global variables=0 words Space for recursion
stack=3(n+1) words
For each call of the algorithm, three values are stored in recursion stack (formal parameters: n,
starting address of array and return value). The algorithm is called for n+1 times. Total space
required by the recursion stack is (n+1)*3 words.
Space complexity = c+1+0+n+0+(n+1)3=(c+4n+4) words