Space complexity
Space complexity describes how extra memory an algorithm needs as the input grows. Auxiliary space excludes the input itself; total space includes it.
Detailed Explanation
Time is not the only scarce resource. A function that builds a list of n copies uses O(n) extra memory. A function that keeps a few integers uses O(1) extra memory, even if it reads an input of size n. That difference is why an in-place reverse can run where a second list would not.
Be precise about what you count. The input list already occupies O(n). If you only allocate a handful of indices, auxiliary space is O(1). If you copy the list, auxiliary space is O(n). Recursion adds stack frames. A recursive DFS on a linked structure of n nodes can take O(n) stack even with no extra heap list.
Python objects have large constant overhead. An empty list is already tens of bytes. A list of n integers is n pointers plus n integer objects, unless you use array or NumPy. Big O still describes growth: twice the keys, twice the dict. The constant decides whether n=10⁷ fits.
Common patterns: in-place two pointers are O(1) extra. A seen set for uniqueness is O(n). Memoised dynamic programming is O(states). BFS stores a frontier that can be O(n). Generators are O(1) extra for the values they have not yielded yet; list(generator) is O(n).
Trading space for time is normal. A dict of indices turns repeated scans into lookups. A prefix-sum array spends O(n) space to answer range sums in O(1). Make the trade on purpose.
Memory leaks in long-running processes are often accidental space complexity: a cache without a bound, a list that only appends, a cycle that the collector will eventually get but not soon enough. Bound caches. Drop references.
Code Examples
# O(1) auxiliary: swap in place.
def reverse_in_place(items: list[int]) -> None:
left, right = 0, len(items) - 1
while left < right:
items[left], items[right] = items[right], items[left]
left += 1
right -= 1
nums = [1, 2, 3, 4]
reverse_in_place(nums)
print(nums) # [4, 3, 2, 1]# O(n) auxiliary: a new list.
def reversed_copy(items: list[int]) -> list[int]:
return items[::-1]
# O(n) stack: recursion depth follows n.
def rec_sum(items: list[int]) -> int:
if not items:
return 0
return items[0] + rec_sum(items[1:])# Space for time: index once, look up many times.
def index_by_sku(rows: list[dict]) -> dict[str, dict]:
return {row["sku"]: row for row in rows}Common Gotchas
Slices copy
`items[1:]` in a recursive call is O(n) time and space per call, so the "linear" recursion is quadratic. Pass an index instead.
A `seen` set is O(n)
that is fine until n is huge or the objects are large. Store ids if you only need identity.
Recursion uses space you do not see in `locals()`
`sys.getrecursionlimit()` is a depth cap, not a memory budget.
Generators postpone space
they do not delete it if the caller materialises the whole stream.