4

Imagine you loop n times, and every iteration you create a string of space n with scope only within that iteration (thus it is no longer accessible in the next iteration). I would look and say that I use O(n^2) space because, for n iterations, I use n space.

However, logically, if every loop you destroy the previous iteration's string (of n space) and overwrite it with this iteration's string (of n space), throughout the entire loop, you would only be using O(n) space. I am confused about whether to confirm O(n) or O(n^2) space?

Take this example:

s = "hello"
for _ in range(len(s)):
    newString = s[:]
return newString

I am primarily asking this question for the space of a DS + Algo interview.

1 Answers1

6

I can't answer that question reliably, because it depends on the behavior of the memory allocator in Python, and I don't think we're provided any guarantees about that. The memory allocator might deallocate the space after the function returns, or it might deallocate in every iteration.

What we can say is that it is possible to implement this algorithm using $O(n)$ space, and it is possible to implement it in a way that uses $O(n^2)$ space. If we were presented with an algorithm (not with code) and we cared about space, one might reasonably make the implicit assumption that you will implement it in a way that uses $O(n)$ space and thus describe the algorithm as having $O(n)$ space complexity.

D.W.
  • 167,959
  • 22
  • 232
  • 500