"Time isn't the only bill. Every algorithm also rents memory — and the cheapest-in-time solution is often the most expensive in space. You're always trading one for the other."
Same Idea, Different Resource
Space complexity asks the exact same question as time complexity, just about memory instead of steps: as the input grows, how much extra memory does the algorithm need? Same ladder, same notation:
- O(1) space — uses a fixed amount of extra memory no matter the input. Reversing a list in place with two pointers: just a couple of variables.
- O(n) space — extra memory grows with the input. Building a set of all seen items, or making a copy of the list.
- O(n²) space — a full 2D table, like the grids you'll build in Dynamic Programming.
Note "extra" — we usually count the memory the algorithm allocates on top of the input, not the input itself.
The Trade Is the Whole Point
Here's the relationship that runs through all of algorithms: you can very often buy time with space, and buy space with time. Remember the duplicate-check from earlier?
- Nested loops: O(n²) time, but O(1) space — no extra memory.
- A
setof seen items: O(n) time, but O(n) space — you spent memory to skip the rework.
Neither is "right." If memory is plentiful (your laptop, most servers), spend it to save time. If memory is the hard limit (a 50 GB file, an embedded chip, a streaming pipeline), you take the slower in-place version and like it. Memoization — the heart of Dynamic Programming — is this trade made into a technique: store past answers (more space) so you never recompute them (less time).
The Hidden Space: the Call Stack
One space cost beginners forget entirely: recursion uses memory. Every pending recursive call sits on the call stack, holding its local variables, until it returns. A recursion that goes n levels deep uses O(n) space even if it allocates nothing else — and if it goes too deep, Python raises RecursionError when the stack overflows. We'll dig into this in the Recursion track; for now, just know that "no arrays allocated" does not always mean "O(1) space."