AlgoViz

O(n) linear space

easy 14 min

O(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

0:00 / 5:24

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.

Step 1 of 3

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 nn. 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 nn elements leave up to nn entries.

  • Straight-line growth

    Going from nn to 2n2n 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

S(n)=O(n)  ⟺  S(n)≤c⋅n   for some constant c and all large nS(n) = O(n) \iff S(n) \le c \cdot n \;\text{ for some constant } c \text{ and all large } n
S(n)S(n) is the extra memory used on an input of size nn. Storing 3 values per element (3n3n) or n+50n + 50 values is still O(n)O(n): Big O drops constant factors and smaller terms.

The picture

Memory grows in a straight line

Doubling the input
  1. 1n = 44 slots
  2. 2n = 88 slots: 2x input, 2x memory
  3. 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

S(2n)S(n)=c⋅2nc⋅n=2\frac{S(2n)}{S(n)} = \frac{c \cdot 2n}{c \cdot n} = 2
Compare: constant space gives a ratio of 1, quadratic space a ratio of 4. Measuring memory at nn and 2n2n tells you which class you are in.

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 O(n)O(n), 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

Stotal(n)=Sinput(n)⏟given to you+Saux(n)⏟what you addS_{\text{total}}(n) = \underbrace{S_{\text{input}}(n)}_{\text{given to you}} + \underbrace{S_{\text{aux}}(n)}_{\text{what you add}}
A function that sums a list has Saux=O(1)S_{\text{aux}} = O(1) even though Stotal=O(n)S_{\text{total}} = O(n). State which one you mean; when unsure, say auxiliary.

How to work out auxiliary space

Count the peak, not the total ever allocated: memory that is freed can be reused. Then keep the dominant term.
CodeAuxiliary spaceWhy
total += x in a loopO(1)O(1)One integer, whatever nn is
seen = set() filled in a loopO(n)O(n)Up to one entry per element
return arr[::-1]O(n)O(n)Slicing builds a full copy
Recursion nn levels deepO(n)O(n)One stack frame per pending call
grid = [[0] * n for _ in range(n)]O(n2)O(n^2)nn rows of nn cells

Example 1

Two Sum with a hash map

One pass with a map of seen values

Each number is looked at once. The map remembers every number already passed, so finding a partner is one O(1)O(1) lookup instead of a second scan.
Python
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 entries
Target 11 in [2, 7, 11, 15, 3, 8]: the map holds 5 entries before 8 finds its partner 3.
Edit and run it in your browser

Worst-case size of the map

∣seen∣≤n−1  ⇒  S(n)=O(n)|\text{seen}| \le n - 1 \;\Rightarrow\; S(n) = O(n)
If the pair is the last two elements, or there is no pair at all, every element but the last is stored. Here n=6n = 6 and the map peaked at 5 entries.

The trade-off

Paying memory to buy speed

Two Sum, both ways

O(n2) time,  O(1) space⏟check every pair⟶O(n) time,  O(n) space⏟hash map\underbrace{O(n^2) \text{ time},\; O(1) \text{ space}}_{\text{check every pair}} \quad\longrightarrow\quad \underbrace{O(n) \text{ time},\; O(n) \text{ space}}_{\text{hash map}}
Brute force tries all (n2)=n(n−1)2\binom{n}{2} = \frac{n(n-1)}{2} pairs with two loop counters. The hash map reads each element once but remembers them. For n=105n = 10^5 that is about 5 billion pair checks against 100,000 lookups.
ProblemWithout extra spaceWith O(n) space
Two SumO(n2)O(n^2) time, O(1)O(1) spaceHash map: O(n)O(n) time, O(n)O(n) space
Contains duplicateO(n2)O(n^2) time, O(1)O(1) spaceHash set: O(n)O(n) time, O(n)O(n) space
FibonacciNaive recursion: O(2n)O(2^n) time, O(n)O(n) stackMemo: O(n)O(n) time, O(n)O(n) space
Trading O(n)O(n) memory often turns quadratic or exponential time into linear time.

Example 2

Reverse into a copy

Python
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]
The copy keeps the original intact and costs n new slots. The in-place version swaps ends with two indexes.
Edit and run it in your browser

Copy: O(n) space

  • The original list is preserved (non-destructive).
  • Safe when the caller still needs the input, or it is shared.
  • Costs nn new slots: S(n)=nS(n) = n.

In place: O(1) space

  • Only two indexes, whatever the length.
  • Destroys the original order.
  • Same O(n)O(n) time, so choose by whether mutation is allowed.

Example 3

Memoisation

Fibonacci with a memo table

F(n)=F(n−1)+F(n−2),F(0)=0,  F(1)=1S(n)=(n+1)⏟memo+n⏟stack=O(n)F(n) = F(n-1) + F(n-2), \quad F(0) = 0,\; F(1) = 1 \qquad S(n) = \underbrace{(n + 1)}_{\text{memo}} + \underbrace{n}_{\text{stack}} = O(n)
The memo stores one answer per value 0..n0..n. Each value is computed once, so time drops from O(2n)O(2^n) to O(n)O(n).

What each call does

A miss computes and stores; every later request is a hit. The memo grows by one entry per distinct nn.
Python
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))                   # 2880067194370816120
fib(6) fills memo with 7 entries, 0 through 6. fib(90) is instant; without the memo it would take centuries.
Edit and run it in your browser

Hidden 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 nn levels deep, nn frames are alive at once. No list appears in the code, yet the memory is linear.

Stack space

Sstack(n)=max depth×frame size=n⋅O(1)=O(n)S_{\text{stack}}(n) = \text{max depth} \times \text{frame size} = n \cdot O(1) = O(n)
For fib with a memo the deepest chain is fib(n), fib(n-1), ..., fib(1): depth nn. Naive fib without a memo also reaches depth nn, so it is O(n)O(n) space even though it is O(2n)O(2^n) time.

The stack at its peak for fib(6)

Six frames for n=6n = 6. As each call returns, its frame is freed and one memo entry is written.

Pattern spotting

Common O(n) structures

  • Hash map or set

    seen = {} or set() filled in a loop: up to nn 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: O(k)O(k), which is O(n)O(n) if all differ and O(1)O(1) for a fixed alphabet.

Python
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)
Three more linear-space patterns: a set for duplicates, a visited set plus stack for DFS, and a counter.
Edit and run it in your browser

Decide

When O(n) space is worth it

Spend O(n) space when

  • It turns O(n2)O(n^2) time into O(n)O(n).
  • It avoids recomputing the same subproblems (memoisation).
  • The original data must be preserved.
  • You need O(1)O(1) 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.
  • O(nlog⁡n)O(n \log n) time from sorting is acceptable.

Quick decision flow

Each yes is a good reason to spend linear memory. If every answer is no, aim for constant space.

Scale

O(n) next to its neighbours

Input sizeO(1)O(1)O(log⁡n)O(\log n)O(n)O(n)O(n2)O(n^2)
n=10n = 101about 310100
n=100n = 1001about 710010,000
n=1,000n = 1{,}0001about 101,0001,000,000
n=1,000,000n = 1{,}000{,}0001about 201,000,000101210^{12}
Memory slots needed. A million 8-byte values is about 8 MB, easily affordable; 101210^{12} is terabytes.

Recap

Key takeaways

Key points

  • O(n) space: extra memory grows in proportion to the input, S(2n)=2 S(n)S(2n) = 2\,S(n).
  • 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 nn levels deep is O(n)O(n) space even with no list in sight.
  • Two Sum: O(n2)O(n^2) time with O(1)O(1) space, or O(n)O(n) time with O(n)O(n) space. Name the trade.
  • A frequency counter is O(k)O(k) for kk distinct keys: O(1)O(1) for a fixed alphabet.

Sources