Module 2 · Measuring Speed and Memory · Lesson 5 of 40
Space complexity: how much memory?
Measure the extra memory an algorithm needs, including the hidden memory used by recursive calls.
In this lesson · about 15 minutes
- Tell the difference between input space and extra (auxiliary) space
- Find the space used by lists, 2D lists and dictionaries you create
- Explain why recursion uses memory for each waiting call
Time is not the only cost. Memory matters too. Space complexity asks: how much extra memory does the algorithm need as n grows?
Input space vs extra space
The input itself takes memory, but you were given it. Usually we care about the extra memory your code creates, called auxiliary space.
| Your code creates… | Extra space |
|---|---|
A few number variables (total, i) | O(1) |
| A new list with one item per input item | O(n) |
| A grid of n rows and n columns | O(n²) |
| A dictionary counting each item | O(n) in the worst case |
| A list of 26 counters, one per letter | O(1), because 26 never grows |
Nested loops don't mean nested space
Two loops inside each other take O(n²) time, but if they only use a counter, the space is still O(1). Time and space are measured separately.
Recursion uses memory too
When a function calls itself, each waiting call is kept in memory on the call stack until it finishes. If the calls go n levels deep, that is O(n) space, even if you made no lists. Count how many calls are waiting at the same time (the depth), not the total number of calls.
The trade-off
Often you can use more memory to save time. Storing items in a set (more memory) makes "is it there?" checks instant (less time). Good programmers choose this trade on purpose.
Try it: two ways to reverse
The first way builds a new list (O(n) extra space). The second swaps items in place (O(1) extra space). Both give the same answer.
Exercise
Reverse in place
Write reverse_in_place(nums) that reverses the list without making a new list: swap the first and last items, then the second and second-last, and so on. Return the same list.
Check your understanding0 of 3 correct
Quiz score: 0 of 3
Exercises solved: 0 of 1
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.