Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do variables declared in loop make space complexity O(N)?

Would variables declared inside of a for loop that loops N times make the space complexity O(N) even though those variables fall out of scope each time the loop repeats?

for(var i = 0; i < N; i++){
  var num = i + 5;
}
like image 891
spencer.sm Avatar asked Jun 11 '17 04:06

spencer.sm


2 Answers

Would variables declared inside an O(N) for loop make the space complexity O(N)

No, since variables go out of scope at the end of every iteration, thus they are destroyed.

As a result the space complexity remains constant, i.e. O(1).

like image 76
gsamaras Avatar answered Nov 11 '22 05:11

gsamaras


1 (fixed-size) variable that you change n times (which could include unallocating and reallocating it) is still just 1 variable, thus O(1) space.

But this may possibly be somewhat language-dependent - if some language (or compiler) decides to keep all of those earlier declarations of the variable in memory, that's going to be O(n), not O(1).

Consider, for example, two ways of doing this in C++:

for (int i = 0; i < N; i++)
   int num = i + 5;

for (int i = 0; i < N; i++)
   int* num = new int(i + 5);

In the former case, the variable can be reused and it will be O(1).

When you use new, that memory will not be automatically freed, so every iteration in the latter case will assign more memory instead of reusing the old (technically the pointer will get reused, but what it pointed to will remain), thus it will use O(n) space. Doing this is a terrible idea and will be a memory leak, but it's certainly possible.

(I'm not too sure what the C++ standard says about what compilers are or are not required to do in each case, this is mostly just meant to show that this type of in-loop assignment is not necessarily always O(1)).

like image 25
Bernhard Barker Avatar answered Nov 11 '22 05:11

Bernhard Barker