Lesson 116 of 296
Space complexity, best and worst case, amortised cost
What you will learn
- Measuring memory with space complexity
- Best, average and worst case
- Amortised cost, using array push as the example
- The time–memory trade-off
On this page
Space complexity
Space complexity measures how much extra memory an algorithm needs as n grows. We usually count only the extra memory, not the input itself (called auxiliary space).
function sumSpace(nums: number[]): number {
let total = 0;
for (const n of nums) total += n;
return total;
}Only one extra variable: O(1) space.
function doubled(nums: number[]): number[] {
return nums.map((n) => n * 2);
}Creates a new array of n items: O(n) space.
Recursion uses space
Each recursive call waits on the call stack (Lesson 68) until the calls below it finish. A recursion n levels deep uses O(n) space, even with no arrays.
function sumRecursive(nums: number[], i = 0): number {
if (i === nums.length) return 0;
return nums[i]! + sumRecursive(nums, i + 1);
}O(n) time and O(n) space for the stack. Very deep recursion (around 10,000 levels or more in JavaScript) can cause a stack overflow.
(The ! after nums[i] tells TypeScript the item exists. With noUncheckedIndexedAccess (Lesson 105), array reads include undefined. In this part we use ! only where the index is guaranteed to be valid by the loop.)
Best, average and worst case
The same algorithm can take different times on different inputs of the same size.
Searching for a value in an unsorted array:
| Case | When | Steps |
|---|---|---|
| Best | The value is first | 1 |
| Average | Somewhere in the middle | about n/2, which is O(n) |
| Worst | The value is last or missing | n |
Big-O usually describes the worst case, because that is the guarantee. When average and worst differ a lot, mention both. For example, quicksort is O(n log n) on average but O(n²) in the worst case; hash map lookups are O(1) on average but O(n) in the worst case (if many keys collide).
Amortised cost
Amortised means "averaged over many operations".
arr.push(x) is described as O(1). But arrays are stored in a block of memory of a fixed size. When it is full, the engine creates a bigger block (often about double the size) and copies every item: that one push is O(n).
Because the size doubles, these expensive copies happen rarely. If you push n items, the total copying work is about n + n/2 + n/4 + ... which is less than 2n. Spread over n pushes, that is about 2 steps each: O(1) amortised.
So: "push is O(1) amortised" means "an occasional push is slow, but on average over many pushes each one costs constant time."
The time–memory trade-off
Often you can make an algorithm faster by using more memory. The most common example: storing what you have seen in a Set or Map.
function hasDuplicateFast(nums: number[]): boolean {
const seen = new Set<number>();
for (const n of nums) {
if (seen.has(n)) return true;
seen.add(n);
}
return false;
}| Approach | Time | Space |
|---|---|---|
| Nested loops (Lesson 115) | O(n²) | O(1) |
| Set | O(n) | O(n) |
| Sort first, then compare neighbours | O(n log n) | O(1) to O(n) depending on the sort |
In interviews, state the trade-off out loud. Memory is usually cheaper than time, but say it.
How to say it in an interview
"Space complexity counts the extra memory an algorithm needs, including the recursion stack. I state the worst-case time but mention when the average case differs, such as quicksort or hash maps. Amortised cost averages occasional expensive operations over many cheap ones, which is why array push is O(1) amortised despite occasional resizing. Often I trade memory for speed, for example using a Set to turn an O(n squared) check into O(n)."
Key words
| Word | Meaning |
|---|---|
| Space complexity | How extra memory grows with input size |
| Auxiliary space | Memory used besides the input |
| Worst case | The input that takes the most steps |
| Amortised | Averaged over a sequence of operations |
| Trade-off | Gaining one thing (speed) by giving another (memory) |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.