Sub topic 11
Trading space for time and time for space
This chapter assumes you know Big O for time, can read basic Python, and have seen auxiliary space and the call stack in earlier chapters. Here you will learn to treat memory and running time as two costs you can exchange, and to decide which one to spend.
The core idea
Many problems can be solved in more than one way. One solution stores extra data so it can skip repeated work. Another stores almost nothing and repeats work. The first spends space to save time. The second spends time to save space.
Neither choice is correct in general. The right one depends on which resource is scarcer for your program: memory, or time.
Spending space to save time
A classic case is checking whether a list has a duplicate. The version with no extra storage compares every pair.
def has_duplicate_slow(nums):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] == nums[j]:
return True
return False
def has_duplicate_fast(nums):
seen = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return Falsehas_duplicate_slow runs in O(n²) time and O(1) auxiliary space. has_duplicate_fast runs in O(n) average time and O(n) auxiliary space, because the set seen can grow to hold every element. A set lookup takes O(1) on average, which is what removes the inner loop.
| Version | Time | Auxiliary space |
|---|---|---|
| Compare all pairs | O(n²) | O(1) |
| Hash set | O(n) average | O(n) |
Memoization, covered in the next chapter, is the same trade applied to recursion. A lookup table, a cache, and a precomputed index all follow this pattern.
Spending time to save space
The reverse trade appears when memory is the limit. The Fibonacci functions below show it.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib_memo(n):
if n < 2:
return n
return fib_memo(n - 1) + fib_memo(n - 2)
def fib_iter(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return aBoth run in O(n) time. fib_memo stores n + 1 cached results and recurses to depth n, so it uses O(n) space. fib_iter keeps two variables and uses O(1) space. Here the iterative version wins on both axes, so this is not a true trade. It shows that the cache is not free, and that you can often discard values you no longer need.
A real time-for-space trade is recomputation. If a program needs a value many times and the value is cheap to compute, recomputing it avoids holding it in memory.
Choosing between them
Use these questions:
- Which limit are you hitting, running time or memory? Measure before changing anything.
- How large can n get? An O(n) cache of 1,000 items is trivial. One of 500 million items may not fit.
- How often is each result reused? A cache helps only when values repeat.
- Is the recomputation cheap? Recomputing a sum is cheap. Recomputing a database query is not.
Common errors
- Adding a cache without checking reuse. If every input is unique, the cache fills with entries that are never read. You pay the space and gain no time.
- Forgetting that a cache can grow without bound.
lru_cache(maxsize=None)never evicts entries. A long-running service should set amaxsize. - Counting only time. A change from O(n²) to O(n) time that moves space from O(1) to O(n) is only a win if the memory is available.
- Assuming a trade always exists. Sometimes a better algorithm improves both costs, as
fib_iterdoes.
Exercise
A function checks whether any two numbers in a list sum to a target. Version A tries every pair. Version B stores each number in a set and checks whether target - x is already there. Give the time and auxiliary space of each, and say which resource Version B spends and which it saves.
Show answer
Version A takes O(n²) time and O(1) auxiliary space. Version B takes O(n) average time and O(n) auxiliary space. Version B spends space, since the set can hold every element, to save time, since each lookup is O(1) on average and no inner loop is needed.
Exercise
A service caches results with lru_cache(maxsize=None) and slowly runs out of memory. Name the cause and one fix.
Show answer
The cache never evicts entries, so it grows with every distinct input. Set a finite maxsize so least recently used entries are dropped, or stop caching if inputs rarely repeat.