Learn how algorithms use memory, see the difference between extra space and total space, and understand common space complexity levels from O(1) to O(n²).
A scan can read a million numbers while keeping only a running total. A second algorithm could read the same numbers and also keep a set of all the distinct values it encounters. The number of reads is similar, but their storage needs grow differently.
Space complexity measures peak memory use as input size grows. To explain a bound, say which memory you count: storage for the input, working storage such as temporary collections and unfinished calls, and storage for the output. We count a number, index, or reference as one fixed-size slot in the examples below.
These examples count occupied memory slots. A slot used for a returned result belongs to the output.
| Space Growth | Meaning | Common Example |
|---|---|---|
Constant O(1) | Uses the same amount of extra memory, no matter the input size. | Fixed variables, pointers that move inside the original array |
Logarithmic O(log n) | Extra memory grows by just one step each time the input size doubles. | Balanced recursive calls (like recursive Binary Search) |
Linear O(n) | Extra memory grows at the same rate as the input size. | A set holding up to n distinct keys |
Quadratic O(n²) | Extra memory grows with the square of the input size (n×n). | A grid with n rows and n columns |
O(1)An algorithm uses constant space, O(1), when it only creates a fixed number of variables, no matter how large the input gets.
The following sum keeps a running total as it visits each item. Even though the numbers inside the variables change as the loop runs, the number of variables we create stays the same.
function calculateSum(numbers) {
let total = 0; // Uses just one variable for the total
for (let i = 0; i < numbers.length; i++) {
total += numbers[i]; // Updates total directly without making new variables
}
return total; // O(1) Extra Space
}Another common O(1) pattern is modifying an array directly in place using two pointers:
function reverseInPlace(items) {
let left = 0;
let right = items.length - 1;
while (left < right) {
// Swap values directly in the original array
const temp = items[left];
items[left] = items[right];
items[right] = temp;
left++;
right--;
}
return items; // O(1) Extra Space: No new arrays or objects created
}The swap uses two moving indexes and a fixed amount of temporary storage. Neither implementation copies the array.
O(log n)An algorithm uses logarithmic space, O(log n), when its extra memory grows by just one small step every time the input size doubles.
One source of logarithmic working storage is the call stack. Imagine searching for 7 in the sorted array [1, 2, 3, 4, 5, 6, 7]. The midpoint values visited are 4 → 6 → 7. When the last call finds 7, it is active alongside the two earlier calls waiting for its return.
The gray branches show other possible search paths. This search only creates frames for the blue path. In the code below each frame stores a few indexes and passes along the same sorted array.
function binarySearchRecursive(items, target, left = 0, right = items.length - 1) {
if (left > right) return -1;
const mid = Math.floor((left + right) / 2);
if (items[mid] === target) return mid;
if (items[mid] < target) {
// Each recursive call adds a frame to the call stack
return binarySearchRecursive(items, target, mid + 1, right);
} else {
return binarySearchRecursive(items, target, left, mid - 1);
}
}Each call halves the number of remaining candidates. The number of simultaneously active calls is therefore O(log n) for large inputs, including the final call that finds the target or the empty interval.
Loops vs. Recursion Memory
Binary search written with a normal loop (iterative) uses O(1) extra space because it stays inside one function. The recursive version uses O(log n) extra space because the computer must keep each unfinished function call on the call stack.
O(n)A linear storage requirement grows in proportion to input size. A set can hold up to one entry per input item.
You usually get linear space when you:
function findUniqueNumbers(numbers) {
const seen = new Set(); // Can hold up to n items
for (const num of numbers) {
seen.add(num);
}
return Array.from(seen); // O(n) Extra Space
}If numbers has 1,000 items, seen may need to store up to 1,000 items. If all values are identical, the set holds just one number. With k distinct values, the set uses O(k) working space and the returned list also has k positions.
O(n²)An algorithm uses quadratic space, O(n²), when the memory it needs grows with the square of the input size (n×n).
A grid with r rows and c columns has r × c cells. This multiplication table has n rows and n columns. The function returns the table, so those cells belong to the output.
function createMultiplicationTable(n) {
const table = []; // Creates n rows, each with n items
for (let i = 0; i < n; i++) {
const row = [];
for (let j = 0; j < n; j++) {
row.push((i + 1) * (j + 1));
}
table.push(row);
}
return table; // Total items stored: n * n = O(n²) space
}If n=10, the table stores 100 numbers (10×10). If n=1,000, the table has to store 1,000,000 numbers in memory.
Suppose two functions reverse a list of n items. One swaps items inside the input. The other walks from the end and appends each item to a fresh output list.
| What is counted? | Reverse in place | Build a reversed copy |
|---|---|---|
| Original input | O(n) | O(n) |
| Working storage (auxiliary, excluding output) | O(1) for the swap | O(1) for the traversal |
| New output storage | None, return the input | O(n) for the copy |
| Extra storage including the output | O(1) | O(n) |
| Total storage including the input | O(n) | O(n) |
A problem may count the returned collection as extra memory or explicitly exclude required output. State the convention, especially when an algorithm returns a new collection.
Whenever your code calls a function, the computer puts a small block of memory called a stack frame onto the call stack. This stack frame holds:
Each stack frame stays in memory until that function call finishes and returns. If a recursive function calls itself n times before reaching the end condition (base case), all n function calls sit in memory at the exact same time.
// Iterative Factorial: O(1) Auxiliary Space
function factorialIterative(n) {
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result; // Only uses two variables: 'result' and 'i'
}
// Recursive Factorial: O(n) Auxiliary Space
function factorialRecursive(n) {
if (n <= 1) return 1;
return n * factorialRecursive(n - 1); // Keeps n function calls on the call stack at once
}The recursive version holds one frame for each unfinished multiplication. The iterative version reuses one frame. These bounds count frames and numeric slots. If you count bytes for exact, arbitrarily large factorial values, the result itself also grows.
Stack Overflow Risk
If a recursive function calls itself too many times, the call stack runs out of memory. When that happens, your program crashes with a Stack Overflow error.
Just like Time Complexity, we simplify Space Complexity using the same Big O rules:
O(2n² + 4n + 16) → O(n²)Comparing Space Growth from Best to Worst
These example storage sizes grow increasingly quickly for large inputs:
1 → log n → n → n²
O(1) extra space by changing data directly inside the existing array or list instead of creating a new one.