Sub topic 5
Constant and linear space in loops
This chapter assumes you can read Python, know what a list is, and understand Big O notation for time. It also assumes you know the difference between input space and auxiliary space from the previous chapter. Here you will learn to look at a loop and decide whether it uses O(1) or O(n) auxiliary space.
The rule of thumb
A loop does not use memory by running many times. It uses memory only when each iteration keeps something alive after the iteration ends. Ask one question: what is still stored when the loop finishes?
- If the loop only updates a fixed number of variables, auxiliary space is O(1).
- If the loop adds to a collection that grows with the input, auxiliary space is O(n).
Constant space: one accumulator
def total(nums):
s = 0
for x in nums:
s += x
return sThe function stores s and the loop variable x. Both are single numbers, and the count of variables does not change when nums gets longer. The auxiliary space is O(1). The input list itself is not counted, because it belongs to the caller.
Linear space: a growing result
def doubled(nums):
result = []
for x in nums:
result.append(2 * x)
return resultEach iteration adds one element to result. After the loop, result holds as many items as nums. The auxiliary space is O(n).
The two functions have the same time complexity, O(n). Only the space differs, which is why time and space must be analyzed separately.
Common errors
Counting loop iterations as space
A loop that runs n times does not use n units of memory if each iteration reuses the same variables. Python frees the old value of x when x is rebound to the next element.
Ignoring nested loops
Nested loops multiply time, but not always space. This function runs n² steps but still uses O(1) auxiliary space:
def count_pairs_with_sum(nums, target):
count = 0
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
count += 1
return countIt keeps only count, i and j. If it instead stored every pair in a list, the space would be O(n²), because there are about n²/2 pairs.
Forgetting that range is lazy
In Python 3, range(n) does not build a list of n numbers. It stores only its start, stop and step, so looping over range(n) costs O(1) space. Wrapping it in list(range(n)) makes it O(n).
Mistaking the output for auxiliary space
Some conventions count the returned list as part of the space and some do not. When you state a bound, say which convention you use. In this tutorial, doubled is O(n) auxiliary space because it builds a new structure, even though that structure is also the return value.
Comparing the two patterns
| Pattern | What the loop keeps | Auxiliary space |
|---|---|---|
| Running total, count, min or max | A fixed number of variables | O(1) |
| Appending one item per element | A list that grows with n | O(n) |
| Adding keys to a dictionary or set | A container that grows with n | O(n) |
| Nested loop that only counts | A fixed number of variables | O(1) |
A dictionary or set can stay small if many inputs map to the same key. For example, counting the letters of a lowercase English word needs at most 26 keys, so that is O(1) with respect to word length. The bound depends on how many distinct values are possible.
Turning linear space into constant space
Often you can replace a collection with a running value. To find the largest number, you do not need a sorted copy of the list:
def largest(nums):
best = nums[0]
for x in nums:
if x > best:
best = x
return bestThis keeps one value, best, so the auxiliary space is O(1). Building sorted(nums) and reading the last item would cost O(n) space and more time.
Exercise
What are the time and auxiliary space complexities of this function? def evens(nums): out = []; for x in nums: if x % 2 == 0: out.append(x); return out. Explain why the space is not always n.
Show answer
Time is O(n), because it visits each element once. Auxiliary space is O(n) in the worst case, because out can grow to hold every element when all numbers are even. For a given input it may hold fewer, but Big O describes the worst case as the input grows.
Exercise
A function loops over a list of n words and adds each word to a set. Another loops over n integers between 0 and 9 and adds each to a set. What is the auxiliary space of each?
Show answer
The first is O(n), because n distinct words can produce n set entries. The second is O(1), because the set can never hold more than 10 values, no matter how large n is.