Skip to content

Module 18 · Algorithms and Problem Solving — topic 6 of 18

Space complexity

How much extra memory an algorithm needs as input grows: constant versus linear extra space, in-place algorithms, recursion and the call stack, lazy evaluation, and trading memory for speed with caching.

Beginner 8 min read·Lesson 266 of 306 in Python Programming

Learning objectives

  • Estimate an algorithm's extra memory
  • Write in-place algorithms
  • Recognise memory costs of recursion and caching

Definition

Space complexity describes how the extra memory an algorithm uses — beyond its input — grows with the input size n. An algorithm using a fixed amount of extra memory is O(1) space; one that builds a structure as large as its input is O(n).

Introduction

Reversing a list by building a new one doubles the memory used; reversing it in place needs only two index variables. On huge data, that difference decides whether a program runs at all.

Why it matters

Memory is limited, especially on servers handling many requests or on small devices. Understanding space cost helps you choose between speed and memory deliberately.

Detailed explanation

Auxiliary space is the extra memory beyond the input. It is what space complexity usually measures.

In-place algorithms modify the input directly and use only a few variables: O(1) extra space. Swapping elements to reverse a list is an example.

Algorithms that build new lists, sets or dictionaries proportional to the input use O(n) extra space.

Recursion uses the call stack: each active call stores its local variables. A recursion n levels deep uses O(n) stack space, and Python stops very deep recursion with RecursionError (the default limit is about 1,000 levels).

Generators and iterators process one item at a time, keeping memory constant even for huge inputs.

Caching (memoisation) trades memory for time: storing results avoids recomputation but uses space for the cache.

When memory is tight, prefer streaming, in-place updates and iteration over recursion.

Like time complexity, space complexity ignores constant factors and focuses on growth.

Syntax

Python
def reverse_in_place(xs): # O(1) extra space
i, j = 0, len(xs) - 1
while i < j:
xs[i], xs[j] = xs[j], xs[i]
i += 1
j -= 1
reversed_copy = xs[::-1] # O(n) extra space
  • Measure extra memory.
  • In-place uses O(1).
  • Recursion depth costs stack space.

Code examples

In place versus a copy

Python
def reversed_copy(xs):
return xs[::-1]
def reverse_in_place(xs):
i, j = 0, len(xs) - 1
while i < j:
xs[i], xs[j] = xs[j], xs[i]
i += 1
j -= 1
a = [1, 2, 3, 4, 5]
b = reversed_copy(a)
reverse_in_place(a)
print(a, b, a == b)
Output
[5, 4, 3, 2, 1] [5, 4, 3, 2, 1] True

Recursion uses stack space

Python
def depth_sum(n):
return 0 if n == 0 else n + depth_sum(n - 1)
def loop_sum(n):
total = 0
for i in range(n + 1):
total += i
return total
print(depth_sum(500))
try:
depth_sum(100_000)
except RecursionError:
print("RecursionError: too deep")
print(loop_sum(100_000))
Output
125250
RecursionError: too deep
5000050000

More examples

Streaming and caching trade-offs

Python
import tracemalloc
from functools import lru_cache
def peak(fn):
tracemalloc.start()
fn()
_, p = tracemalloc.get_traced_memory()
tracemalloc.stop()
return p
list_peak = peak(lambda: sum([i * i for i in range(200_000)]))
gen_peak = peak(lambda: sum(i * i for i in range(200_000)))
print(list_peak > 10 * gen_peak)
@lru_cache(maxsize=None)
def paths(r, c):
return 1 if r == 0 or c == 0 else paths(r - 1, c) + paths(r, c - 1)
print(paths(10, 10), paths.cache_info().currsize)
Output
True
184756 120

Step-by-step explanation

  • Summing a list comprehension builds all 200,000 squares first; the generator keeps only one at a time.
  • paths counts grid routes; without the cache it would recompute the same subproblems millions of times.
  • The cache stores 120 results — extra memory that makes the computation almost instant.

Expected output

Running “Streaming and caching trade-offs” prints exactly:

TextOutput
True
184756 120

Practical applications

  • Streaming large log files instead of loading them.
  • Caching expensive database queries.

Best practices

  • Prefer iteration for deep or long processes.
  • Stream large data with generators.
  • Cache deliberately, with limits where needed.

Common mistakes

Deep recursion on big inputs

Avoid

def total(xs):
return 0 if not xs else xs[0] + total(xs[1:])

Prefer

def total(xs):
return sum(xs)

The recursive version uses O(n) stack and O(n²) memory for slices, and fails on long lists.

Important notes

  • sys.setrecursionlimit raises the limit, but very deep recursion can still crash the interpreter; iteration is safer.

Key takeaways

  • Space complexity measures extra memory growth.
  • In-place algorithms use O(1) space; copies use O(n).
  • Recursion and caches consume memory.

Try it yourself

  1. 1
    Write an in-place function that moves all zeros in a list to the end.
  2. 2
    Rewrite a recursive factorial iteratively and explain the space difference.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

16 questions cover the “Algorithms and Problem Solving” module. Answers and explanations are revealed after you submit.

  • AdvancedWhat is printed?
  • AdvancedWhat is the average time complexity of x in my_set?
  • AdvancedA loop over a list checks item in other_list for each item. With both lists of length n, the complexity is…
Practise this module