Space complexity is all very well on something like a Turing machine: you just define the space complexity to be the number of different tape cells that the tape head visits. For real computers, things get much more complicated and very implementation-dependent.
It is possible that the algorithm you describe runs in constant space. If the array a
is stored earlier in memory than the string b
, the system could, in principle, delete the last character of a
, shuffle everything after it back one memory cell, then add a character onto the end of b
, so no extra memory is used.
In reality, though, it's much more likely that the system doesn't keep moving things around and just allocates new memory each time a character is added to b
, which is probably linear space. Except it could be worse. Maybe, every time you try to make b
bigger, the system actually allocates completely new storage for the extended string, which could give quadratic space usage. Or maybe it's not that dumb and, each time you extend the string beyond its current memory allocation, it allocates a new chunk of memory that's double the size, so it can do lots of appends without reallocating memory every time. That would be linear, again.
And in real reality, what actually happens probably depends very much on what else is running on the machine. If there's lots of free memory, the system might be very happy to allocate fresh memory each time you extend the string, and it might only free the memory used by the old versions right at the end. If there is little free memory, it might free up unused memory much more aggressively.
So your code probably uses at least a linear amount of memory, but it's not really possible to be more precise than that.
a.pop()
, which is not obvious at all? – John L. Feb 23 '19 at 20:05