Sub topic 8
Hidden costs: slices, copies and string concatenation
This chapter assumes you can read Big O notation, know Python lists and strings, and have seen the difference between input space and auxiliary space. Some lines of code look cheap but allocate a whole new object. These hidden costs change the space complexity of a function, so you have to count them.
Slices copy
In Python, a slice of a list creates a new list. It copies references to the elements, so the cost is proportional to the slice length.
def sum_slices(nums):
if not nums:
return 0
return nums[0] + sum_slices(nums[1:])This function looks like it only recurses. Each call builds nums[1:], a list of length n-1, n-2, and so on. The copies are alive at the same time, because each caller waits for its callee. The total is about n²/2 references, so auxiliary space is O(n²), plus O(n) for the call stack. Passing an index instead avoids the copies:
def sum_index(nums, i=0):
if i == len(nums):
return 0
return nums[i] + sum_index(nums, i + 1)This version needs only O(n) stack space and no copies.
Common hidden copies
| Expression | New memory | Auxiliary space |
|---|---|---|
| `a[1:]`, `a[::-1]` | New list | O(n) |
| `list(a)`, `a.copy()` | New list | O(n) |
| `sorted(a)` | New list | O(n) |
| `a.sort()` | Sorts the same list | O(1) extra at most for this call, not counting sort internals |
| `a + b` | New list | O(len(a) + len(b)) |
| `a += b` | Extends `a` | Amortized O(len(b)) |
| `for x in a` | None | O(1) |
A shallow copy duplicates the references, not the objects they point to. A list of n large objects still costs O(n) for the copy, but the large objects are shared.
String concatenation
Strings in Python are immutable, meaning they cannot be changed after creation. Each + builds a new string.
def join_slow(words):
out = ""
for w in words:
out += w
return out
def join_fast(words):
return "".join(words)In join_slow, each step creates a string longer than the last. Older strings are freed, so the peak memory at any moment is O(total length). The cost that grows is time: copying can total O(n²) characters. CPython sometimes resizes the string in place and hides this, but other interpreters do not, so you should not rely on it. "".join(words) computes the final size once and builds the result in one pass.
The point is to separate two questions. Peak space asks how much memory is alive at once. Total allocation asks how much memory is requested over the whole run. Repeated concatenation has a bad total allocation but a modest peak.
Finding hidden costs
- Look for
[:],[a:b],+on sequences,list(),sorted(),copy(), andstrbuilding in loops. - For each one, find the size of the new object.
- Decide whether it is alive together with other copies (recursion) or freed each iteration (loop).
- Add the sizes of everything alive at the peak.
Exercise
The function def count(s): return 0 if s == "" else 1 + count(s[1:]) is called on a string of length n. What is its auxiliary space, and how would you reduce it?
Show answer
Each call creates a slice of length n-1, n-2, and so on, and all of them stay alive during the recursion. That is O(n²) characters, plus O(n) stack frames. Pass an index instead of slicing, which cuts it to O(n) stack space. A loop with a counter reduces it to O(1).