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
In theory, worst-case space usage is O(n^2) as you mentioned: n copies of n-length strings.
But in practice, it'll be lower due to implementation details like garbage collection (i.e. reference counting) and string interning (i.e.
s[:]
can return the same object ass
). For example in CPython 3.8.12: