TimeComplexityandSpace 2
TimeComplexityandSpace 2
and Complexity
Algorithm Analysis
Space Complexity
-The amount of working storage an algorithm
need
volume of memory
Why do we need Algorithm Analysis
Knowing efficiency of an algorithm is very vital on mission critical tasks
Algorithm analysis does not give you accurate/exact values (time, space, etc),
however it gives estimates which can be used to study the behavior of the
algorithm.
What is Space Complexity
The space complexity of an algorithm or a computer program is the amount of
memory space required to solve an instance of the computational problem as
function of the size of the input
It is the memory required by an algorithm to execute a program and produce output
Auxiliary Space: is the temporary space (excluding the input size) allocated by your
algorithm to solve the problem with respect to input size
Space complexity includes both Auxiliary space and space used by input
Space Complexity
An algorithm generally requires space for following components:
1.Instruction Space
2. Data Space
3. Environment Space
Big O notation
Linear Space or O( n )
Constant Space or O( 1 )
Quadratic Space or O( n2 )
n1 à 4bytes
O(1)
n2 à 4bytes
sum à 4bytes
Aux à 4bytes constant space
Total à 16bytes
arr à N x 4bytes
sum à 4bytes
i à 4bytes O(N)
Aux à 4bytes
Linear Space
Total à 4N + 12 bytes Complexity
n=5
fact à 4 bytes
O(1)
n à 4 bytes Constant Space Complexity
i à 4 bytes
Aux à 4 bytes
Space à 12 bytes + 4 bytes
{ variables a, b, c and z are all integer types
int z = a + b + c; they will take up 4 bytes each
return(z);
so total memory requirement will be (4(4) + 4) = 20 bytes
}
the additional 4 bytes is for return value
space requirement is fixed
Constant Space Complexity.
// n is the length of array a[] 4*n bytes of space is required for the array a[] elements
int sum(int a[], int n) 4 bytes each for x, n, i and the return value.
{ the total memory requirement will be (4n + 16)
int x = 0; // 4 bytes for x
for(inti=0;i<n;i++) //4bytesfori
{
x = x + a[i];
}
return(x);
increasing linearly with the increase in the input value n
}
Linear Space Complexity
Time Complexity
Linear Time or O( n )
Constant Time or O( 1 )
Quadratic Time or O( n2 )
Constant Time or O( 1 )
statement;
we have a single statement. Its Time Complexity will be constant. The running time
of the statement will not change in relation to N.
Linear Time or O( n )
time complexity for the above algorithm will be Linear. The running time of the
loop is directly proportional to N. When N doubles, so does the running time.
Quadratic Time or O( n2 )
This time, the time complexity for the code above will be Quadratic. The running time of the
two loops is proportional to the square of N. When N doubles, the running time increases by N
* N.
O(log2n)