Space complexity means the amount of space the algorithm needs to run.
Example 1: Sorting-Algorithms
All sorting algorithms need at least O(n)
space to save the list (of length n
) they have to sort
- Bubblesort (and most other sorting algorithms too) can work in-place, this means that it needs no more space as it needs to save the list. (just searching two elements in the wrong order and swaping them)
- Stupid-Sort lists all permutations of the input list (and saves them) and then searching the sorted one. Since there are
n!
permutations this algorithm needsO(n * n!)
space.
Example 2: Number representation
A number n
can be saved in different ways:
- binary (or any other base
≥2
): this needsO(log n)
space, due ton = 2log n
- unary: here you write
n
as a sum of ones (n = 1 + 1 + 1 + ... + ... + 1
) and you have to save every one. So this needsO(n)
space, due ton = n ⋅ 1
.