Two ways to count memory
- Total space: everything the algorithm holds, including its input.
- Auxiliary (extra) space: what it allocates beyond the input: temporary arrays, hash sets, the call stack.
Algorithm analysis almost always reports auxiliary space, because the input exists either way. The output is usually reported separately: generating every subset needs Θ(n · 2ⁿ) memory if you keep them all, but that is the size of the answer, not overhead.
Memory is counted the same way as time: choose a unit (an element, a reference, a stack frame), count how many exist at the same time at the peak, and keep the growth class. Memory that is freed and reused does not add up: a loop that allocates and drops a temporary buffer of size n on every iteration does Θ(n²) work but needs only Θ(n) space at any moment (plus whatever the garbage collector has not reclaimed yet).
The call stack is memory
Each active function call keeps a frame on the call stack: its parameters, local variables and return address. A recursion that is d levels deep holds d frames at its deepest point, so its stack space is Θ(d) frames, even if it never allocates an object.
The lab above computes a power two ways and tracks Max stack depth:
- Linear: 2^10 recurses on
e − 1: 11 frames pile up before the first one returns. Depth Θ(e). - Squaring: 2^10 recurses on
e / 2(10, 5, 2, 1, 0): 5 frames. Depth Θ(log e). - Stack overflow asks the linear version for 2^20 on a simulated stack of 12 frames: it needs 21 and fails. The squaring version would need 6.
Same answer, same idea, very different memory. The exercises show the pattern on other code:
| Exercise | Time | Stack space |
|---|---|---|
| Recursion that peels off one element | Θ(n) | Θ(n) |
| Recursion on half the input | Θ(log n) | Θ(log n) |
| Naive recursive Fibonacci | Θ(φⁿ) | Θ(n) |
| Two halves plus constant work | Θ(n) | Θ(height) |
Naive Fibonacci is the instructive one: exponentially many calls, but only n of them are ever on the stack at once, because each branch returns before its sibling starts. Space is the peak, not the total. The recursion lesson covers frames and unwinding in detail.
In place
An algorithm is in place if it needs only O(1) auxiliary space beyond the input, or, in a common looser usage, O(log n) for a recursion stack. Examples:
| Algorithm | Auxiliary space |
|---|---|
| insertion, selection, bubble sort | O(1) |
| heap sort | O(1) |
| quicksort | O(log n) stack if it recurses on the smaller part first; Θ(n) worst case if it does not |
| merge sort on arrays | Θ(n) buffer |
| reversing an array with two pointers | O(1) |
Built-in sorts differ, and their documentation says so. Java's Arrays.sort for objects (a
merge-based sort) documents temporary storage from a small constant for nearly sorted input up to
n/2 object references for random input. C++ std::stable_sort is O(n log n) comparisons when it
can allocate a buffer and O(n log² n) when it cannot: the same algorithm trading time for memory.
Trading memory for time, and back
Many speed-ups buy time with memory:
- A hash set of seen values turns an all-pairs Θ(n²) duplicate check into Θ(n) expected time, for Θ(n) extra space (badge duplicates).
- A prefix-sum array answers any range sum in O(1) after Θ(n) time and Θ(n) space (prefix sums lesson).
- Memoization stores each subproblem's answer once: Fibonacci drops from exponential to Θ(n) time, at Θ(n) space.
The reverse also works. The n × n table exercise needs Θ(n²) cells, but each row depends only on the previous one, so two rows suffice: Θ(n) space, the same Θ(n²) time. Dynamic programming (M32) uses this constantly.
Constant factors are bigger in memory
O-notation hides the size of one element, and in memory that factor varies a lot between languages:
- C#
List<int>and C++std::vector<int>store the 4-byte integers themselves, contiguously. - Java
ArrayList<Integer>stores references to separately allocatedIntegerobjects; each boxed value carries an object header, so the memory per element is several times that of anint[]. - Python
liststores references tointobjects; every element is a full object on the heap. Thearraymodule or NumPy store raw numbers when that matters.
All four are Θ(n) space. The real numbers can differ by a factor of four or more, which decides whether a dataset fits in memory or in cache. The contiguous storage lesson shows the effect on traversal speed.
Language notes: how deep can you recurse?
The stack is much smaller than the heap, so stack space is often the binding limit:
- Python stops recursion at a configurable limit (
sys.getrecursionlimit(), 1000 by default) with aRecursionError.sys.setrecursionlimitcan raise it, but the documentation warns that a limit too high for the platform can crash the interpreter. - C#: a
StackOverflowExceptioncannot be caught; since .NET 2.0 the process terminates. Recursion depth must be bounded by design. - Java throws
StackOverflowError, which can technically be caught but leaves no safe way to continue. The thread stack size is set with-Xssor theThreadconstructor. - C++ has no required check at all: the standard does not describe stack exhaustion, and in practice it usually crashes the process. Default main-thread stacks are commonly 1 MB on Windows and 8 MB on Linux.
The usual fix is to convert deep recursion into a loop with an explicit stack on the heap, or to change the recursion so its depth is logarithmic, as the squaring version of power does.
Multiple inputs: one variable per size
When the input has several independent sizes, keep a variable for each. Collapsing them to one n hides real behaviour.
| Situation | Honest bound | Wrong simplification |
|---|---|---|
| nested loops over two lists | Θ(n · m) | O(n²): wrong when m is tiny or huge |
| build a set from one, probe with the other | Θ(n + m) expected | O(n): drops the cost of the probes |
| BFS or DFS on a graph with adjacency lists | O(V + E) | O(V²): only true for dense graphs |
| comparing two strings of lengths n and m by dynamic programming | Θ(n · m) | |
| inserting a word of length L into a trie | O(L), independent of the number of words | O(n) |
| answering a range query that returns k results from a balanced tree | O(log n + k) | O(log n): ignores the output |
You may merge variables only when you know how they relate. If m ≤ n always, then Θ(n + m) = Θ(n). For a connected graph E ≥ V − 1, so O(V + E) = O(E). Without such a guarantee, keep both.
Space follows the same rule. Building a set from the first list in the sequential example costs Θ(n) space, not Θ(n + m): the second list is only read.
Common mistakes
- Calling recursive code O(1) space because it allocates nothing. The stack counts.
- Adding up memory that is freed instead of measuring the peak.
- Counting the input or output as overhead, or forgetting to say whether you did.
- Writing O(n²) for two different inputs. Use n and m.
- Raising Python's recursion limit to fix a deep recursion instead of removing the depth.
- Ignoring element size when deciding whether data fits in memory.
Worked practice
1. Recursive binary search on n elements: time and auxiliary space? Iterative?
Recursive: Θ(log n) time and Θ(log n) stack frames. Iterative: Θ(log n) time and O(1) auxiliary space. Same algorithm, different memory.
2. Merging two sorted arrays of lengths n and m into a new array: time and space?
Time Θ(n + m): every element is written once. Space Θ(n + m) for the output; O(1) auxiliary space beyond the output. See merge two sorted arrays.
3. Naive Fibonacci makes about 1.6ⁿ calls. Why is its stack space only Θ(n)?
Space is the peak number of frames alive at once. A call to fib(k) finishes fib(k − 1) entirely
before starting fib(k − 2), so at most one root-to-leaf path is on the stack, and the longest path
has about n frames.
4. An algorithm loops over n words and, for each, over its L characters. Someone writes O(n²). What should it be?
Θ(n · L) if every word has length at most L, or Θ(total number of characters). n² would only be right if L grew like n, which nothing in the problem says.
Summary
- Report auxiliary space, the peak memory beyond the input, and say how you treat the output.
- Every active call holds a frame: recursion depth is space, and the stack is small.
- In place means O(1) extra space (O(log n) for a recursion stack in the looser usage).
- Speed often costs memory (hash sets, tables, memo); rolling arrays and different recursions buy it back.
- Keep one variable per independent size: Θ(n + m), Θ(n · m), O(V + E). Merge them only when you know how they relate.