Space Complexity
Space complexity measures how much extra memory an algorithm needs as input grows. It is often traded against time — faster algorithms frequently require more RAM.
What is space complexity?
Space complexity measures how much extra memory an algorithm needs as the input grows. Swapping two variables uses O(1) space, copying an array uses O(n), and a recursive function uses O(depth) space for its call stack. Often you can trade space for time, for example by storing results in a hash map to avoid recomputing them.
const reverseInPlace = (a) => { // O(1) extra space
for (let i = 0, j = a.length - 1; i < j; i++, j--) [a[i], a[j]] = [a[j], a[i]];
return a;
};
const reversedCopy = (a) => [...a].reverse(); // O(n) extra spaceInteractive growth visualiser
Use the slider to see how different space complexities grow with n. O(1) algorithms are ideal — they use the same memory regardless of input size.
n =
16Auxiliary vs total space
Total space = input size + auxiliary space. Auxiliary space = extra memory beyond the input itself. Interviews usually ask about auxiliary space — we already know the input exists.
In-place reverse: only 2 extra variables (O(1) auxiliary space). The input array is not counted.
Common space complexities
Constant time
Logarithmic time
Linear time
Linearithmic time
Quadratic time
In-place vs copying
1// In-place reverse — O(1) auxiliary space2function reverse(arr):3 left = 0, right = len(arr) - 14 while left < right:5 swap(arr[left], arr[right])6 left++, right--78// O(n) space version — creates a copy9function reverseCopy(arr):10 result = new Array(len(arr))11 for i from 0 to len(arr) - 1:12 result[i] = arr[len(arr) - 1 - i]13 return result
Recursion call stack
1// Recursion depth = call stack frames2function factorial(n):3 if n <= 1: return 14 return n * factorial(n - 1) // O(n) stack frames56// Tail-recursive — compiler can optimise to O(1) space7function factTail(n, acc = 1):8 if n <= 1: return acc9 return factTail(n - 1, n * acc)
🎯 Quick Check
What is the auxiliary space complexity of merge sort on an array of n elements?
Space Complexity: summary
Key points
- Usually only auxiliary (extra) space is counted, not the input itself.
- Recursion depth counts: a recursive sum of n numbers uses O(n) stack space.
- Memoisation trades O(n) memory for a big drop in running time.
Frequently asked questions
›Does recursion use more memory than a loop?
Yes. Each recursive call adds a stack frame, so a recursion n levels deep uses O(n) space, while an equivalent loop uses O(1).