Sub topic 10
Analyzing the space of a function step by step
This chapter assumes you know Big O notation for time, can read Python, and understand the difference between input space and auxiliary space. It also assumes you know how recursion uses the call stack. Here you combine those ideas into one repeatable procedure.
The procedure
Apply these steps in order. Each step produces a number you add to the total at the end.
- Set the input aside. Decide what counts as input space, and count only auxiliary space.
- Count named variables. Scalars such as counters and accumulators cost O(1).
- Count new data structures. Ask how many elements each one holds at its largest.
- Check for hidden copies. Slices,
list(...),sorted(...)and string concatenation in a loop can allocate memory that no variable name reveals. - Find the recursion depth. Each active call holds a stack frame, so the deepest chain of calls sets the stack cost.
- Take the peak, not the sum of everything ever allocated. Memory that is freed before the next allocation does not add up.
- Keep the dominant term and drop constants.
Worked example: a simple loop
def total(nums):
s = 0
for x in nums:
s += x
return sWalk through the steps. The input nums is excluded. The variables s and x are scalars. No new structure is built, there are no copies, and there is no recursion. The result is O(1) auxiliary space.
Compare it with a function that builds output.
def doubled(nums):
result = []
for x in nums:
result.append(2 * x)
return resultStep 3 finds a list that grows to n elements, so the auxiliary space is O(n).
Worked example: recursion
def sum_recursive(nums, i=0):
if i == len(nums):
return 0
return nums[i] + sum_recursive(nums, i + 1)No list is created, so steps 3 and 4 add nothing. Step 5 matters here. The call with i = 0 waits for the call with i = 1, and so on until i = n. That is n + 1 frames alive at once, so the space is O(n).
Worked example: a hidden copy
def reverse_copy(a):
return a[::-1]There is no visible variable, but the slice allocates a new list of n elements. Step 4 catches it, so the space is O(n). The in-place version swaps elements within the input and uses only i and j, so it is O(1).
def reverse_in_place(a):
i, j = 0, len(a) - 1
while i < j:
a[i], a[j] = a[j], a[i]
i += 1
j -= 1Common errors
- Counting the input. If the question asks for auxiliary space, a function that only reads its input is O(1), even though the input has n items. State which definition you use.
- Missing the stack. A recursive function with no data structures is not automatically O(1).
- Adding instead of taking the peak. Two phases that run one after the other, each using O(n), still give O(n) overall, not a larger bound.
- Forgetting the return value. Some conventions count the returned structure and some do not. Say which one you chose.
- Ignoring multiple variables of different sizes. If a function takes a list of length n and a string of length m, the answer may be O(n + m), not O(n).
Quick reference
| Pattern | Auxiliary space |
|---|---|
| Loop with scalar accumulators | O(1) |
| Loop that appends one item per pass | O(n) |
| Recursion of depth n, no extra structures | O(n) |
| Slice or copy of the input | O(n) |
| Swaps inside the input | O(1) |
Exercise
What is the auxiliary space of this function, and which step of the procedure reveals it? def f(s): return s + "!" for a string s of length n.
Show answer
O(n). The concatenation creates a new string of length n + 1, which is a hidden copy found in step 4. The input string is not counted, but the result is a new allocation of size proportional to n.
Exercise
A function recurses to depth log n and, at each level, creates a list of size 10. What is its auxiliary space?
Show answer
O(log n). Each of the log n active frames may hold a list of constant size, so the total is 10 times log n, and the constant is dropped.