Time and Space Complexity: Steps, Memory and the Trade-Off
Every algorithm spends two resources: time and memory. Time complexity counts the basic steps an algorithm takes as a function of the input size n. Space complexity counts the memory it needs. The two are analyzed with the same notation (see the Big O guide), and they often pull against each other: the fastest way to solve a problem frequently uses more memory, and the most frugal way is often slower.
Time complexity: counting steps
Time complexity is a count, not a stopwatch reading. You pick a constant-time basic operation, such as a comparison, and express how many times it runs for an input of size n. Scanning a list once is O(n). Comparing every pair of items is O(n^2). The count says nothing about seconds, but it predicts how the running time scales: double n, and an O(n^2) algorithm does about four times the work.
Space complexity: counting memory
Space complexity counts memory in the same spirit, in units such as "one integer" or "one list slot". There are two conventions, and you should say which one you mean:
- Auxiliary space is the extra memory the algorithm uses beyond its input: temporary variables, new lists, hash tables, the call stack. This is what people usually mean by "O(1) space".
- Total space includes the input itself. Any algorithm that reads a list of n items has total space at least O(n), so this measure is less useful for comparing algorithms.
The output is usually counted separately. A function that returns a sorted copy of its input has to build an n-item list; whether you call that O(n) space depends on whether you count the output, so state it.
Examples: finding the largest value with one running variable uses O(1) auxiliary space. Building a set of all values seen uses O(n). Merge sort on an array uses O(n) auxiliary space for merging.
The call stack is space too
Every function call that has not yet returned keeps a frame on the call stack, holding its local variables and where to resume. A recursive function that calls itself n levels deep therefore uses O(n) stack space even if each call stores only a couple of numbers. The same task written as a loop uses O(1).
Python makes this visible because it limits how deep the stack can go (1000 frames by default in CPython) and raises RecursionError when you exceed it. The sample below shows both versions; the recursion guide explains the stack in detail.
A second hidden cost in Python is slicing. items[1:] builds a new list of n - 1 items, so a recursive function that passes items[1:] down at every level does O(n^2) total copying and holds O(n^2) memory at its deepest point. Passing an index instead, as below, avoids both.
Trading memory for time
The most common trade is to spend O(n) memory on a hash-based structure so that lookups become constant time on average:
- A set for membership. Checking
x in some_listis O(n) per check. Putting the items in a set once costs O(n) time and O(n) space, after which each check is O(1) on average. - A cache. If a function is called repeatedly with the same arguments, store each result the first time and look it up after that.
functools.cachedoes this for you. The memory grows with the number of distinct arguments, and the time saved can be enormous when the same subproblems recur: that is the core idea of dynamic programming. - Precomputed tables. Prefix sums let you answer "sum of items i to j" in O(1) after an O(n) pass that stores n + 1 running totals.
The trade goes the other way when memory is the constraint: recomputing a value instead of storing it, or streaming through data once instead of loading it all.
In-place algorithms
An algorithm is in place if it rearranges the input using only a small, fixed amount of extra memory (O(1), or by a looser convention O(log n) for a recursion stack). Reversing a list by swapping items[i] and items[n - 1 - i] for i up to the middle is in place. list(reversed(items)) is not: it builds a new list. Heap sort is the standard example of an in-place O(n log n) sort; merge sort on arrays is not in place.
In-place algorithms modify their input. If the caller still needs the original, it has to make a copy, and the space saving disappears.
Average time of common Python operations
These are the average-case costs for CPython's built-in containers, where n is the number of items in the container. The Python wiki keeps a longer "TimeComplexity" page with the same figures.
| Operation | list | dict | set |
|---|---|---|---|
| read or write by index or key | O(1) | O(1) | not applicable |
add at the end (append) or insert a key (d[k] = v, add) | O(1) amortized | O(1) | O(1) |
membership (x in c) | O(n) | O(1) | O(1) |
delete (pop() at the end; del d[k]; remove) | O(1) at the end | O(1) | O(1) |
insert or delete at the front (insert(0, x), pop(0)) | O(n) | not applicable | not applicable |
| copy, or iterate over everything | O(n) | O(n) | O(n) |
The dict and set figures are averages. In the worst case, when many keys collide in the hash table, a lookup can take O(n); with ordinary keys this is rare. "Amortized" on append means the occasional expensive resize is spread over many cheap appends, which the amortized analysis guide works through with numbers.
One task, two trade-offs
Examples use Python 3.10 or later and only the standard library. The task: does a list contain any value twice? The nested-loop version compares every pair: O(n^2) time, O(1) auxiliary space. The set version remembers what it has seen: O(n) time on average, O(n) auxiliary space. The script then sums a list recursively and with a loop to show the stack cost.
def has_duplicate_nested(items):
for i in range(len(items)):
for j in range(i + 1, len(items)):
if items[i] == items[j]:
return True
return False
def has_duplicate_set(items):
seen = set()
for x in items:
if x in seen:
return True
seen.add(x)
return False
def sum_recursive(items, i=0):
if i == len(items):
return 0
return items[i] + sum_recursive(items, i + 1)
def sum_loop(items):
total = 0
for x in items:
total += x
return total
data = [4, 8, 15, 16, 23, 42, 8]
print(has_duplicate_nested(data), has_duplicate_set(data))
print(has_duplicate_nested(data[:-1]), has_duplicate_set(data[:-1]))
print(sum_recursive(data), sum_loop(data))
big = list(range(5000))
print(sum_loop(big))
try:
sum_recursive(big)
except RecursionError as err:
print("RecursionError:", err)
Output:
True True
False False
116 116
12497500
RecursionError: maximum recursion depth exceeded
Both duplicate checks agree on both inputs. Both sums agree on the short list, but on a 5,000-item list the recursive version needs 5,000 stack frames and Python stops it at its recursion limit, while the loop finishes using one running total. The loop is O(n) time and O(1) space; the recursion is O(n) time and O(n) space.
Choosing between time and space
- State both bounds for any algorithm you write: "O(n) time, O(n) extra space" is a complete answer; "O(n)" alone is not.
- Memory is usually cheaper than time for inputs that fit comfortably in RAM, which is why the set version is the normal choice.
- When the input is huge, streamed, or the environment is tight on memory, an O(1)-space method may be the only option, even if it is slower.
- Watch for hidden space: recursion depth, slices,
sorted()returning a new list, and caches that grow without bound.
The Big O Complexity Analyzer evaluates the standard growth functions at an n you pick, which helps when you are deciding whether an O(n^2) time bound or an O(n) space bound is the bigger problem at your input size.