⌂ ≡

Space Complexity

Space complexity means how much extra memory an algorithm needs while it runs. The key word is extra. The input itself is already given. We usually care about the additional storage used during the process.

Space = extra memory used
Small input or big input?
Usually written with n

Simple Idea

If a program only uses a few extra variables like i, j, or temp, then its extra memory stays almost the same even when the input grows. That is why we call it O(1) extra space.

When Space Grows

If a program creates another array or list that grows with the input size, then its space grows with n. That is usually called O(n) space.

Simple Examples

Example 1: O(1)

Find the biggest number in a list by checking each item and storing only one variable called max. You are not creating a second list.

Example 2: O(n)

Copy all items from one list into a new list. If the input has 100 items, the new list also needs space for 100 items.

Example 3: Sorting Here

Bubble Sort, Selection Sort, and Insertion Sort on this site sort the same list in place, so they use O(1) extra space.

Easy Memory Trick

Ask this question:

"As the input gets bigger,
do I need a lot more extra memory?"

If no, it may be O(1).
If yes, and memory grows with the input,
it may be O(n).