Skip to content
Visual explainer 2h 30m to learn 4 steps

Amortised analysis & space complexity

Explain why some operations are cheap on average and measure the extra memory an algorithm uses.

By Invicly Tech, , in Data Structures & Algorithms. About 9 minutes to read.

Topic 3 of 54

In short

Amortised analysis averages the cost of an operation over a long sequence, so rare expensive steps are paid for by many cheap ones. Space complexity counts the extra memory an algorithm needs beyond its input, including the recursion stack. Both matter when choosing between otherwise similar solutions.

Think of it like this: Paying a little into a savings jar every day so the occasional big bill never hurts.

Explained simply

Some operations are usually cheap but sometimes expensive. Adding to a Python list is like this. Most of the time it takes one tiny step. Once in a while the list runs out of room and has to move everything into a bigger space. Amortised analysis asks: averaged over many operations, what does each one really cost?

Think of a monthly train pass. One day you pay a lot, but spread over 30 rides, each ride is cheap. Amortised cost spreads the rare big cost over all the cheap ones. For list append, the answer is O(1) per append, even counting the big moves.

Space complexity is the other side of the coin. It asks how much extra memory your code needs. A function that builds a new list of size n uses O(n) extra space. A function that only keeps a few counters uses O(1).

Recursion uses hidden memory. Every call waiting for an answer sits on the call stack, like a pile of sticky notes. A recursion that goes n levels deep needs n notes, so O(n) space, even if it never creates a list.

Press Play on a diagram to walk through it one step at a time.

CompareCost views for list.append
Single worst operation
  • Resize copies all n items
  • O(n) for that one call
  • Happens rarely
Amortised over n appends
  • Copies total about 2n
  • O(1) per append on average
  • Guaranteed, not probabilistic
FlowAppending 9 items to a doubling list
  1. 1
    Appends 1-2

    Capacity 1 -> 2, copy 1 item

  2. 2
    Append 3

    Capacity 2 -> 4, copy 2 items

  3. 3
    Append 5

    Capacity 4 -> 8, copy 4 items

  4. 4
    Append 9

    Capacity 8 -> 16, copy 8 items

  5. 5
    Total

    9 writes + 15 copies = 24 steps, under 3 per append

CompareWhere the extra memory goes
O(1) extra
  • A few counters
  • Swapping in place
  • Two-pointer loops
O(n) extra
  • A new result list
  • A set of seen items
  • Recursion n levels deep
Surprise O(n^2)
  • Slicing on every recursive call
  • Building a 2D table n by n
  • Storing every prefix as a string

In depth

The aggregate method, step by step

The aggregate method is the simplest way to find amortised cost. Add up the total cost of n operations, then divide by n.

For a list that doubles its capacity, append n items starting from capacity 1. Ordinary appends cost 1 each, so n total. Resizes copy 1, 2, 4, 8 and so on up to less than n items. That geometric series adds up to less than 2n. Total work is under 3n, so each append costs under 3 steps on average: O(1).

  • Total for n appends < n + 2n = 3n
  • 3n / n = 3, a constant
  • Growing by a fixed +10 instead gives O(n) per append

Why growing by a fixed amount fails

Suppose the list grows by 10 slots each time instead of doubling. Then a resize happens every 10 appends, and each resize copies everything so far: 10, 20, 30, up to n. That sum is about n^2 / 20, which is O(n^2) in total and O(n) per append.

The lesson: growing by a percentage (double, or Python's roughly 1.125 times plus a bit) keeps appends cheap. Growing by a fixed number does not.

FlowGrowing by a fixed 10 slots
  1. Step 1
    Resize every 10 appends
  2. Step 2
    Each resize copies all

    10, 20, 30, up to n items

  3. Step 3
    Total copies

    About n^2 / 20

  4. Step 4
    Per append

    O(n), not O(1)

Amortised is not the same as average case

Average case assumes something about the input, like "the target is at a random spot". Bad luck can still give you the worst case.

Amortised cost makes no such assumption. It is a promise about any sequence of operations: no matter what you append, n appends cost O(n) in total. One single append can still be slow, which matters in real-time systems such as games, where one long pause is noticeable.

CompareAverage case vs amortised
Average case
  • Assumes something about the input
  • Bad luck still gives the worst case
  • Example: linear search checks about n/2
Amortised
  • No assumption about the input
  • Promise over any sequence of operations
  • One operation can still be slow
  • Example: n appends cost O(n) total

Counting space honestly

Input space is the memory holding your input. Auxiliary space is everything extra you allocate. When people say an algorithm is "O(1) space" they mean auxiliary space.

Count these: new lists, dicts and sets; copies made by slicing like xs[1:]; strings built along the way; and the recursion stack depth. A recursive function that slices its list on every call can quietly use O(n^2) memory, because each level keeps its own copy.

  • Slicing creates a copy: O(k) space for k items
  • Recursion depth d means O(d) stack space
  • Python's default recursion limit is about 1000

Learn it in 4 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Use the aggregate method for amortised cost~40m
  2. 2
    Count auxiliary space versus input space~40m
  3. 3
    Include recursion stack depth in space~40m
  4. 4
    Measure real runtimes with timeit~40m

Key points

  • Amortised O(1) is a guarantee over any sequence, unlike average case over random inputs.
  • Auxiliary space excludes the input; total space includes it.
  • A recursion of depth d uses O(d) stack space even with no data structures.
  • Measure with timeit and tracemalloc to confirm your analysis on real data.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
import timeit

setup = 'xs = list(range(10_000))'
print(timeit.timeit('xs.append(1); xs.pop()', setup, number=100_000))
print(timeit.timeit('xs.insert(0, 1); xs.pop(0)', setup, number=100_000))
# append/pop at the end: amortised O(1)
# insert/pop at index 0: O(n) shifting each time

Measuring the resize cost yourself

We simulate a doubling array and count copies. With 1,000 appends, copies add up to 1 + 2 + 4 + ... + 512 = 1,023. Total work is 1,000 writes plus 1,023 copies, about 2 per append. Doubling the number of appends roughly doubles the total, which is exactly linear growth.

python
def append_cost(n):
    cap, size, copies = 1, 0, 0
    for _ in range(n):
        if size == cap:
            copies += size   # move everything
            cap *= 2
        size += 1
    return n + copies

print(append_cost(1000))   # 2023
print(append_cost(2000))   # 4047

Same answer, different space

Both functions sum a list. The recursive one makes n nested calls, and each call slices the list, copying it. For n = 5 that is copies of length 4, 3, 2, 1, so about n^2 / 2 items in total, plus 5 stack frames. The loop version uses one counter: O(1) extra space. Try the recursive one on 5,000 items and Python raises RecursionError.

python
def sum_rec(xs):          # O(n) stack, O(n^2) copied items
    if not xs:
        return 0
    return xs[0] + sum_rec(xs[1:])

def sum_loop(xs):         # O(1) extra space
    total = 0
    for x in xs:
        total += x
    return total

print(sum_rec([1, 2, 3, 4, 5]), sum_loop([1, 2, 3, 4, 5]))  # 15 15

Quick reference

  • Amortised cost = total cost of n operations / n
  • Doubling capacity: n appends cost under 3n steps, so O(1) each
  • Growing by a fixed +k: O(n) per append, avoid it
  • Amortised is a guarantee for any sequence; average case assumes random input
  • Auxiliary space = extra memory beyond the input
  • Recursion depth d costs O(d) stack space
  • xs[1:] copies; pass an index instead to save memory
  • Measure: timeit for time, tracemalloc for memory

Common mistakes

  • Calling a recursive solution O(1) space while it uses O(n) stack frames.
  • Confusing amortised with average case; amortised needs no assumptions about inputs.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A dynamic array doubles when full. What is the amortised cost of append?

Question 2

2What is the auxiliary space of reversing a list in place with two pointers?

Question 3

3How does amortised cost differ from average-case cost?

Question 4

4A recursive function calls itself on n - 1 until 0, keeping no lists. What is its space?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write reverse_in_place(xs) that reverses a list without creating a new list. Example: [1, 2, 3, 4] becomes [4, 3, 2, 1]. State the time and auxiliary space.

  2. Exercise 2medium

    Write copies_for(n, grow) that simulates n appends to an array starting at capacity 1, where grow(cap) returns the new capacity, and returns the total number of copied items. Compare grow = lambda c: c * 2 with grow = lambda c: c + 10 for n = 10,000.

  3. Exercise 3hard

    Design a stack with push, pop and get_min, all O(1) amortised time. Example: push 5, push 2, push 7, get_min is 2; pop, pop, get_min is 5. What is its space?

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is list.append really O(1)?
It is O(1) amortised. A single append that triggers a resize costs O(n), but these are rare enough that the average over many appends is constant.
Does the input count toward space complexity?
Usually not. Most people quote auxiliary space, the extra memory beyond the input. Say which one you mean if it matters.
Why does my recursive code crash with RecursionError?
Python limits the stack to about 1000 nested calls by default. Rewrite deep recursion as a loop with an explicit stack, or raise the limit with sys.setrecursionlimit carefully.

Go deeper

ShareXLinkedInWhatsApp