O(n) linear space
easy 14 minO(n) space means the extra memory an algorithm needs grows in proportion to its input: double n and the memory doubles.
Video lesson · Chapter 1 of 6
Two weights for one shipment
O(n) linear space
1:23Reel
Read caption
A roller disco wristband set stores up to one entry for each arrival before a repeated ID is detected. One new guest, one remembered ID.
How it works
Step through the idea, or press Play.
Read an element. The algorithm visits the input one element at a time
Understand it
Start here
What O(n) space means
An algorithm uses O(n) space when the extra memory it needs grows in proportion to the input size . Ten elements need about ten slots, a million need about a million. Double the input and the memory doubles. Most of the time that memory is a hash map, a new list, a memo table or the call stack.
One slot per element
Each element read may leave one entry behind, so elements leave up to entries.
Straight-line growth
Going from to doubles the memory. Constants and fixed-size extras do not change the class.
Usually worth it
Linear extra memory is affordable at almost any scale, and it often buys a much faster algorithm.
The definition
The picture
Memory grows in a straight line
- 1n = 44 slots
- 2n = 88 slots: 2x input, 2x memory
- 3n = 1616 slots: 4x input, 4x memory
Each time the input doubles, a linear-space structure doubles with it. That is the whole signature: $S(2n) = 2\,S(n)$.
Doubling test
Counting
Auxiliary space versus total space
Interviewers almost always mean auxiliary space: memory the algorithm allocates on top of the input it was given. The input itself already takes , so counting it would make every algorithm at least linear and hide the difference between a two-pointer scan and a hash map.
Two ways to count
How to work out auxiliary space
| Code | Auxiliary space | Why |
|---|---|---|
total += x in a loop | One integer, whatever is | |
seen = set() filled in a loop | Up to one entry per element | |
return arr[::-1] | Slicing builds a full copy | |
| Recursion levels deep | One stack frame per pending call | |
grid = [[0] * n for _ in range(n)] | rows of cells |
Example 1
Two Sum with a hash map
One pass with a map of seen values
def two_sum(nums, target): seen = {} # value -> index: O(n) extra space for i, num in enumerate(nums): need = target - num if need in seen: return seen[need], i seen[num] = i print(f"stored {num}->{i}, map size {len(seen)}") return Noneprint(two_sum([2, 7, 11, 15, 3, 8], 11)) # (4, 5) after 5 entriesWorst-case size of the map
The trade-off
Paying memory to buy speed
Two Sum, both ways
| Problem | Without extra space | With O(n) space |
|---|---|---|
| Two Sum | time, space | Hash map: time, space |
| Contains duplicate | time, space | Hash set: time, space |
| Fibonacci | Naive recursion: time, stack | Memo: time, space |
Example 2
Reverse into a copy
def reverse_copy(arr): result = [] # grows to n items: O(n) for i in range(len(arr) - 1, -1, -1): result.append(arr[i]) return resultdef reverse_in_place(arr): left, right = 0, len(arr) - 1 # two ints: O(1) while left < right: arr[left], arr[right] = arr[right], arr[left] left += 1 right -= 1nums = [5, 2, 8, 1, 9, 3]print(reverse_copy(nums), nums) # [3, 9, 1, 8, 2, 5] [5, 2, 8, 1, 9, 3]reverse_in_place(nums)print(nums) # [3, 9, 1, 8, 2, 5]Copy: O(n) space
- The original list is preserved (non-destructive).
- Safe when the caller still needs the input, or it is shared.
- Costs new slots: .
In place: O(1) space
- Only two indexes, whatever the length.
- Destroys the original order.
- Same time, so choose by whether mutation is allowed.
Example 3
Memoisation
Fibonacci with a memo table
What each call does
def fib(n, memo=None): if memo is None: memo = {0: 0, 1: 1} # grows to n + 1 entries if n not in memo: memo[n] = fib(n - 1, memo) + fib(n - 2, memo) return memo[n]memo = {0: 0, 1: 1}print(fib(6, memo), sorted(memo.items()))print(fib(90)) # 2880067194370816120Hidden space
Recursion depth is O(n) space too
A recursive call does not finish until the calls it makes return, so every pending call keeps a stack frame with its arguments and locals. If the recursion goes levels deep, frames are alive at once. No list appears in the code, yet the memory is linear.
Stack space
The stack at its peak for fib(6)
Pattern spotting
Common O(n) structures
Hash map or set
seen = {}orset()filled in a loop: up to keys for instant lookups.Result list
result = []collecting one output per input element.Memo table
memo = {}caching one answer per subproblem.Visited set
visited = set()in graph traversal: at most one entry per node.Stack or queue
DFS stacks and BFS queues can hold every node at once in the worst case.
Frequency counter
One entry per distinct value: , which is if all differ and for a fixed alphabet.
from collections import Counterdef contains_duplicate(nums): seen = set() # up to n values for x in nums: if x in seen: return True seen.add(x) return Falsedef dfs(graph, start): visited, stack, order = set(), [start], [] # each up to n nodes while stack: node = stack.pop() if node not in visited: visited.add(node) order.append(node) stack.extend(graph.get(node, [])) return orderprint(contains_duplicate([3, 1, 4, 1, 5])) # Trueprint(dfs({1: [2, 3], 2: [4], 3: [4], 4: []}, 1)) # [1, 3, 4, 2]print(Counter("banana")) # 3 distinct keys for 6 letters: O(k)Decide
When O(n) space is worth it
Spend O(n) space when
- It turns time into .
- It avoids recomputing the same subproblems (memoisation).
- The original data must be preserved.
- You need lookups by key.
Look for O(1) space when
- Memory is tight: embedded devices, huge streams.
- The input is sorted, so two pointers work.
- Changing the input in place is allowed.
- time from sorting is acceptable.
Quick decision flow
Scale
O(n) next to its neighbours
| Input size | ||||
|---|---|---|---|---|
| 1 | about 3 | 10 | 100 | |
| 1 | about 7 | 100 | 10,000 | |
| 1 | about 10 | 1,000 | 1,000,000 | |
| 1 | about 20 | 1,000,000 |
Recap
Key takeaways
Key points
- O(n) space: extra memory grows in proportion to the input, .
- Count auxiliary space, the memory you add, not the input you were given.
- Hash maps, sets, result lists, copies, memo tables, visited sets, queues and stacks are the usual sources.
- Recursion levels deep is space even with no list in sight.
- Two Sum: time with space, or time with space. Name the trade.
- A frequency counter is for distinct keys: for a fixed alphabet.