Count the extra memory an algorithm needs, including the call stack.
Use it when you must say how much memory code needs, whether it fits a limit, or whether a recursion is safe. Signal words: how much memory, in place, extra space, recursion depth.
Start decide what you count: auxiliary or total, cells or bytes, and the input size n.
Step follow the running total of live cells and frames as the code allocates, frees, calls and returns.
Stop report the peak of that total, and say what it depends on.
It does not give bytes by itself. Bytes need the size of one cell, which depends on the language and the machine.
Cost: one pass over the events, with a few numbers kept.
In this lesson you learn to count the memory a program needs. You separate the extra memory from the input, you count the call stack as memory, and you find the peak instead of the sum.
You work on a monitoring system. A nightly job reads 1,000,000 readings of a day and must produce them sorted and reversed. The job runs on a small machine, so its memory is limited.
Three versions are on the table. One reverses the list in place. One builds a reversed copy. One sums the list with a function that calls itself once for each reading.
Your team lead says: Tell me which versions fit, before the machine runs out of memory at three in the morning.
So the task is this: count the memory each version needs, and say what limits it.
You sort papers on a desk. If you rearrange them where they lie, you need no more room. If you copy every paper and sort the copies, you need a second desk.
When you also stack a tray for each task you are waiting on, the pile of trays needs room too. Memory is the desks plus the pile.
Like sorting papers on a desk: rearranging them needs no extra room, a copy needs a second desk, and each waiting task needs a tray.
Before you write code, count one recursion by hand. A function on 100 items calls itself on half the items, and stops at 1 item. Count the frames alive at the deepest call.
Solve it by hand: Frames alive in a halving recursion. The hand-solve sheet loads in your browser.
Each count is the most extra cells alive at one moment. An instrumented copy of each job counted them.
| Job | Extra cells at the peak |
|---|---|
| Reverse in place, one temporary cell | 1 |
| Reverse into a new list | 1,000 |
| Build a prefix table | 1,001 |
The input holds 1,000 cells in every job. The extra cells are what differ.
Start with a correct version. Sum the list with a function that sums the rest of the list and adds the first item.
def total(items, i):
if i == len(items): # past the end: nothing left to add
return 0
return items[i] + total(items, i + 1) # wait for the rest of the listIt is correct. Each call waits for the next one, so every call keeps its frame alive until the end.
Now check the real size.
The job reads 1,000,000 readings, and a frame takes about 100 bytes.
Here is the count:
Predict the cost
Q A function calls itself once for each of 1,000,000 readings, and a frame takes about 100 bytes. About how much stack memory does it need?
Answer: C
1,000,001 frames of 100 bytes each is 100,000,100 bytes.
You decided this with a count, before the job ran.
Can the same result use less memory? Compare what each version allocates. The input is 1,000,000 integers, which is the same in every version.
| Version | Extra memory measured |
|---|---|
| Reverse in place | 0 bytes |
| Reverse into a new list | 8,000,000 bytes |
| Sort in place | about 4,000,000 bytes |
| Sort into a new list | about 12,000,000 bytes |
These came from tracemalloc on one laptop with CPython 3.11.6, for a list of 1,000,000 random integers. They depend on the version and the machine. A list holds 8 bytes for each item here, so 1,000,000 items is 8,000,000 bytes.
The in-place sort still needed a buffer of about half the list. In place means the result replaces the input. It does not promise that no extra memory is used.
Race: Frames alive at the deepest call. The operation counter loads in your browser.
The race counts the frames alive at the deepest call, by running each recursion. At n = 10,000, a call on half the items needs 14 frames, a call on both halves needs 15, and a call on one fewer item needs 10,001.
Frames alive at the deepest call: a call on half the items needs about log n, and one call on one fewer item needs n plus one.
A job allocates and frees memory in this order: 4 cells, free 4, 6 cells, free 3, 1 cell. The player asks you to predict the live cells after each event.
Dry run: Predict each step: the peak of live cells. The step-by-step player loads in your browser.
Reading without the player? Cover the last column and predict it row by row.
| Event | Cells live | Peak so far |
|---|---|---|
| allocate 4 | 4 | 4 |
| free 4 | 0 | 4 |
| allocate 6 | 6 | 6 |
| free 3 | 3 | 6 |
| allocate 1 | 4 | 6 |
The peak is 6 cells. The allocations sum to 11, and 4 cells are live at the end.
Another run: the events 3, 3, -2, 5, -4, -4, 2 give running totals 3, 6, 4, 9, 5, 1, 3. The peak is 9 cells, the allocations add up to 13, and 3 cells are live at the end.
Total space is the input plus the extra memory. For a list of 1,000 items reversed in place, the total is about 1,001 cells and the auxiliary space is 1 cell. For a reversed copy, the auxiliary space is 1,000 cells and the total is 2,000.
Say which one you mean. Most Big-O claims about space count the auxiliary space, because the input is already given.
Exercise · Put it in order: Reverse with one spare cell. Arrange the lines into a function that reverses the list in place by swapping from both ends, so it needs no second list.
def reverse_in_place(items):
lo = 0
hi = len(items) - 1
while lo < hi:
items[lo], items[hi] = items[hi], items[lo]
lo += 1
hi -= 1
return items
hi = len(items)Time and space can disagree. Recursive Fibonacci with n = 20 makes 21,891 calls but keeps at most 20 frames alive, and with n = 25 it makes 242,785 calls and keeps 25. A merge sort that merges through one shared buffer needs a buffer of n cells, plus 11 frames for 1,000 items and 21 frames for 1,000,000 items. On one laptop (CPython 3.11.6), summing the squares of 1,000,000 integers peaked at 40,448,360 bytes through a list and at 472 bytes through a generator.
Exercise · Predict the output: How deep does the stack go?. This recursion splits 13 items into two halves and handles them one after the other. What does it print: the most frames alive at once?
def frames(n):
if n <= 1:
return 1
half = n // 2
return 1 + max(frames(half), frames(n - half))
print(frames(13))Here is the rule that keeps a space claim honest. Both templates use it.
Space is the peak of live memory at any moment: count the extra cells beyond the input, and count every call frame still waiting.
Memory goes up when code allocates and down when it frees. The space is the highest the running total reaches, not what was ever allocated.
Use it when you must say how much memory code needs, whether it fits a limit, or whether a recursion is safe. Signal words: how much memory, in place, extra space, recursion depth.
Start: decide what you count: auxiliary or total, cells or bytes, and the input size n.
Step: follow the running total of live cells and frames as the code allocates, frees, calls and returns.
Stop: report the peak of that total, and say what it depends on.
It does not give bytes by itself. Bytes need the size of one cell, which depends on the language and the machine.
Cost: one pass over the events, with a few numbers kept.
The function returns the frames alive at the deepest call of three kinds of recursion. Kind 0 calls itself on one fewer item. Kind 1 calls itself on half the items. Kind 2 calls itself on both halves, one after the other.
def stack_frames(kind, n):
# [1] The first call is one frame.
frames = 1
# [2] One fewer item each call: n more frames are alive at the bottom.
if kind == 0:
return n + 1
# [3] Halving: count how often the size halves before it reaches 1.
size = n
while size > 1:
# [4] Both halves run one after the other, so only the larger half is alive: it rounds up.
size = size // 2 if kind == 1 else (size + 1) // 2
frames += 1
# [5] Return the frames alive at the deepest call.
return framespublic int stackFrames(int kind, int n) {
// [1] The first call is one frame.
int frames = 1;
// [2] One fewer item each call: n more frames are alive at the bottom.
if (kind == 0) {
return n + 1;
}
// [3] Halving: count how often the size halves before it reaches 1.
int size = n;
while (size > 1) {
// [4] Both halves run one after the other, so only the larger half is alive: it rounds up.
size = kind == 1 ? size / 2 : (size + 1) / 2;
frames++;
}
// [5] Return the frames alive at the deepest call.
return frames;
}int stackFrames(int kind, int n) {
// [1] The first call is one frame.
int frames = 1;
// [2] One fewer item each call: n more frames are alive at the bottom.
if (kind == 0) {
return n + 1;
}
// [3] Halving: count how often the size halves before it reaches 1.
int size = n;
while (size > 1) {
// [4] Both halves run one after the other, so only the larger half is alive: it rounds up.
size = kind == 1 ? size / 2 : (size + 1) / 2;
frames++;
}
// [5] Return the frames alive at the deepest call.
return frames;
}function stackFrames(kind, n) {
// [1] The first call is one frame.
let frames = 1;
// [2] One fewer item each call: n more frames are alive at the bottom.
if (kind === 0) {
return n + 1;
}
// [3] Halving: count how often the size halves before it reaches 1.
let size = n;
while (size > 1) {
// [4] Both halves run one after the other, so only the larger half is alive: it rounds up.
size = kind === 1 ? Math.floor(size / 2) : Math.floor((size + 1) / 2);
frames++;
}
// [5] Return the frames alive at the deepest call.
return frames;
}Rebuild the template: put its lines back in order. Loads in your browser.
Each event allocates cells when it is positive and frees them when it is negative. The function returns the highest running total.
def peak_live_cells(events):
# [1] No cells are live at the start, and the peak so far is 0.
live = 0
peak = 0
for e in events:
# [2] A positive event allocates cells and a negative event frees them.
live += e
# [3] The peak is the largest number of live cells at any moment.
if live > peak:
peak = live
# [4] Return the peak.
return peakpublic long peakLiveCells(int[] events) {
// [1] No cells are live at the start, and the peak so far is 0.
long live = 0;
long peak = 0;
for (int e : events) {
// [2] A positive event allocates cells and a negative event frees them.
live += e;
// [3] The peak is the largest number of live cells at any moment.
if (live > peak) {
peak = live;
}
}
// [4] Return the peak.
return peak;
}long long peakLiveCells(vector<int>& events) {
// [1] No cells are live at the start, and the peak so far is 0.
long long live = 0;
long long peak = 0;
for (int e : events) {
// [2] A positive event allocates cells and a negative event frees them.
live += e;
// [3] The peak is the largest number of live cells at any moment.
if (live > peak) {
peak = live;
}
}
// [4] Return the peak.
return peak;
}function peakLiveCells(events) {
// [1] No cells are live at the start, and the peak so far is 0.
let live = 0;
let peak = 0;
for (const e of events) {
// [2] A positive event allocates cells and a negative event frees them.
live += e;
// [3] The peak is the largest number of live cells at any moment.
if (live > peak) {
peak = live;
}
}
// [4] Return the peak.
return peak;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Find the bug: The peak that forgets the pile. This function should return the most cells live at any moment. For two allocations of 3 cells in a row it answers 3. Which line is wrong?
def peak_live_cells(events):
live = 0
peak = 0
for e in events:
live += e
peak = max(peak, e)
return peakPeak of live cells: add each event to a running total, and keep the highest value it ever reaches.
You can decide any memory question in four steps.
A job builds a prefix table of 1,000,000 cells for each of 5 days. If it frees each table before the next, the peak is 1,000,001 cells. If it keeps all five, the peak is 5,000,005.
Template 2 gives both numbers from the events. Freeing early cuts the peak by a factor of 5.
Real data brings edge cases.
For kind = 1, n = 0 the template returns 1: the call itself is one frame, even with nothing to do. A recursion always keeps at least one frame.
For events = [7, -7] the peak is 7, and the live cells at the end are 0. The peak looks at every moment, not only at the end.
For kind = 2, n = 1 the template returns 1. A call on one item stops at once. Both halves of a size 3 call give 3 frames: kind = 2, n = 3.
For events = [2000000000, 2000000000] the peak is 4,000,000,000, above the 32-bit limit of 2,147,483,647. The running total must be 64 bits, as in the templates.
This version says sorting a list in place uses no extra memory.
Counterexample: on one laptop (CPython 3.11.6), sorting a list of 1,000,000 random integers in place allocated about 3,999,752 extra bytes, half the pointer array. Count what the code allocates.
This version says a recursive sum uses no memory beyond its input, because it declares no list.
Counterexample: the recursive sum of 1,000 items needs 1,001 frames, and on one laptop Python's default limit stopped it at 1,000 calls. Each waiting call is memory.
Two wrong claims: in place means no extra memory, and recursion is free. Both fail when you count what the code allocates.
This version adds up every allocation and calls the sum the space.
Counterexample: the events 4, -4, 4, -4 allocate 8 cells in total, but never more than 4 are live. The peak is 4, and the sum is 8.
This version says reversing in place and reversing a copy both use O(n) space, because the input has n cells.
Counterexample: counting the input, the in-place reversal of 1,000 items has a total of 1,001 cells and a copy has 2,000, so the totals look alike. The auxiliary space is 1 against 1,000. Say which space you count.
Counting cells assumes every cell is the same size. In Python, a list of 1,000,000 integers holds 8,000,056 bytes of pointers, and each integer from 257 to 2^30 - 1 is a separate object of 28 bytes.
For a memory limit in bytes, multiply by the real size of the item, and measure it. The class still tells you how the memory grows.
Your team lead brings three product changes. Each one asks how memory moves.
The job reads 2,000,000 readings. At 8 bytes an item, the reversed copy doubles from 8,000,000 to 16,000,000 bytes. A halving recursion adds one frame, 21 for 2,000,000 against 20 for 1,000,000.
The job keeps the prefix tables of five days instead of freeing each one. The peak grows from 1,000,001 to 5,000,005 cells, so the memory is five times larger.
The limit falls to 100,000 bytes, and a frame takes 100 bytes. A linear recursion fits only 1,000 frames, so it handles 999 items. A halving recursion needs about 20 frames for 1,000,000 items.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how you decide how much memory code needs, and what you count. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have counted it.
I follow the live memory. I count the extra cells beyond the input, and I count each call that is waiting, because it keeps a frame.
The space is the peak of that total, not the sum of what was allocated. Reversing in place needs one extra cell, and a copy needs n.
I say whether I mean auxiliary or total space, and I measure bytes only on the real machine.
To say how much memory code needs, I follow the live memory. I count the extra cells beyond the input, which is the auxiliary space, and I count every call that is waiting, because each keeps a frame.
The space is the peak of that total, not the sum of what was allocated. Reversing a list in place needs one extra cell. Reversing into a new list needs n cells. A prefix table needs n plus one.
A recursion on one fewer item needs n plus one frames, a thousand and one for a thousand items. A recursion that halves needs about log n frames, ten for a thousand.
In place does not always mean constant. A sort measured on one machine used about half the list as a buffer. So I count what the code allocates and measure bytes on the real machine.
Checkpoint · Space
Q1/10 What is auxiliary space?
Answer: B
Auxiliary space is the extra memory. Total space adds the input.
Q2/10 Reversing 1,000 items in place needs how many extra cells in the lesson's count?
Answer: D
The swap uses one temporary cell. A copy needs 1,000 and a prefix table 1,001.
Q3/10 A function calls itself once on one fewer item, starting from 1,000 items. How many frames are alive at the deepest call?
Answer: B
One frame for each of the calls on 1,000, 999 and so on down to 0.
Q4/10 A function calls itself once on half the items, starting from 1,000 items, and stops at 1 item. How many frames are alive at the deepest call?
Answer: C
The size halves 9 times from 1,000 to 1, so there are 10 frames.
Q5/10 The events 4, -4, 6, -3, 1 allocate and free cells. What is the peak of live cells?
Answer: C
The running total is 4, 0, 6, 3, 4. The highest is 6.
Q6/10 Why is the sum of all allocations a poor measure of space?
Answer: B
The events 4, -4, 4, -4 allocate 8 cells but never more than 4 are live.
Q7/10 On one laptop, sorting 1,000,000 random integers in place with CPython used about how much extra memory?
Answer: C
The lesson measured 3,999,752 bytes. Other versions and machines differ.
Q8/10 A recursive sum of 1,000,000 readings keeps one frame of about 100 bytes for each call. About how much stack does it need?
Answer: C
1,000,001 frames of 100 bytes is 100,000,100 bytes.
Q9/10 Python raised a RecursionError for a recursive sum of 1,000 items. What does this show?
Answer: C
The default limit is 1,000 calls. A list of 998 items worked on that machine.
Q10/10 Someone says an algorithm that works in place always uses O(1) extra space. What is wrong?
Answer: A
Count what the code allocates, not what its name promises.
Ten questions on this lesson. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Memory for a prefix table | Observe | Easy | Peak extra bytes when tables are kept or freed |
| 2 | Recursion depth and stack memory | Platform | Medium | Frames alive for three recursion shapes against a stack limit |
| 3 | Streaming without storing everything | Stream | Medium | A one-pass answer that keeps only a few numbers |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.