I have a simple C++ algorithm that processes elements from a vector. I am passing my function the vector by reference, and accessing the vector's element by reference using a foreach loop like this:
vector<int>& gradingStudents(vector<int>& grades) {
for(int& grade : grades) {
if (grade > 37) {
int n = grade % 5;
if (n >= 3)
grade += (5 - n);
}
}
return grades;
}
My question is, considering that space complexity consists of both auxiliary space and input space, is it correct to say that my algorithm's space complexity is linear (because of the input size, which may vary)? Or is the space complexity constant because the input already exists in memory (it's simply referenced) and no extra space is needed except for my temporary n
variable?
Since you are only using references in regards to your vector, you do not need any more memory. The only write you have is grade += (5-n)
, and like any int
(or number type) this happens where the variable is currently addressed - in this case the vector itself.
You have a single extra int allocated here as far as I can tell, and no other "auxiliary" space is used. Perhaps another one for the reference (like a pointer), though I'm not sure of that since the implementation may be using grades+int_offset
to directly access the variable without an extra pointer.