I understood the basic that if I have a function like this:
int sum(int x, int y, int z) {
int r = x + y + z;
return r;
}
it requires 3 units of space for the parameters and 1 for the local variable, and this never changes, so this is O(1)
.
But what if I have a function like this:
void add(int a[], int b[], int c[], int n) {
for (int i = 0; i < n; ++i) {
c[i] = a[i] + b[0]
}
}
Which requires N units for a
, M units for b
and L units for c
and 1 unit for i
and n
. So it will need N+M+L+1+1
amount of storage.
So what will the big-O for space complexity here? The one which takes higher memory?
I.e. if N takes more higher momery than M and L (from much higher means suppose larger than 10**6
) - so is it safe to say space complexity is O(N)
or not like we do for time complexity ?
But if all three i.e a, b, c are not very much different
Like this function
void multiply(int a[], int b[], int c[][], int n) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
c[i] = a[i] + b[j];
}
}
}
Then what will be the space complexity? O(N+M+L)
? Or still the biggest one?
Space complexity is the total amount of memory space used by an algorithm/program including the space of input values for execution. So to find space-complexity, it is enough to calculate the space occupied by the variables used in an algorithm/program.
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 a function of characteristics of the input. It is the memory required by an algorithm until it executes completely.
o(1) space complexity means that the amount of memory that you use is constant and does not depends on the data that it is processing, more information here.
Space complexity refers to the total amount of memory space used by an algorithm/program, including the space of input values for execution. Calculate the space occupied by variables in an algorithm/program to determine space complexity. However, people frequently confuse Space-complexity with auxiliary space.
When we talk about space complexity, we don't consider the space used by the input.
This allows us to talk about algorithms which are constant space, O(log n) space etc. If we started counting the input, then all algorithms will be at least linear space!
The standard multi-tape Turing machine definition of space complexity also does not count the output.
The input is read only and output is write only and do not count towards the space complexity.
So to answer your question: look for what memory your method allocates, including stack space for recursion/local variables etc, and that will determine the space complexity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With