Search code examples
algorithmloopsmemorybig-ospace-complexity

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;
}

Solution

  • 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).