Every program needs memory to run. It uses memory to store variables, create data structures like arrays and hash maps, and keep track of active function calls.
Space complexity describes how the amount of memory a program uses grows as the input size increases.
In this lesson, we'll explore the most common space complexity patterns you'll encounter in DSA problems and coding interviews, and learn how to analyze the space complexity of a piece of code step by step.
Before we look at code, let's clarify exactly what we're measuring.
The input itself takes up memory. An array of n integers requires space for n integers, regardless of how the algorithm processes it. Since the input is already given to us, we typically don't count its memory when analyzing a solution.
Instead, we measure auxiliary space, which is the extra memory an algorithm uses beyond the input itself. Throughout this lesson, when we talk about space complexity, we're referring to auxiliary space.
There's one more important detail to understand. Memory can be reused. When a function returns or a temporary array is no longer needed, the memory it occupied can be reclaimed and reused.
So when analyzing space complexity, we look at the maximum amount of memory needed at any single point during execution, rather than adding up all the memory allocated over the course of execution.
Let us start with the simplest pattern: constant space. Here's a function that reverses an array in place.
Let's break down how much extra memory this function uses. It creates a left pointer, a right pointer, and a temporary variable for swapping elements. That's just three integers.
Whether the array contains 10 elements or 10 million, the function uses the same three variables. We're simply rearranging elements within the original array without creating a new one.
Loading simulation...
Since the extra memory remains constant regardless of the input size, the space complexity is O(1).
Other algorithms that use a fixed number of variables, such as finding the maximum element or calculating a running sum, also have constant space complexity.
Here's another example where an algorithm creates an array but still uses constant space. This function checks whether two strings containing only lowercase English letters are anagrams of each other.
Loading simulation...
Since the function creates a new array called count, you might initially assume it uses O(n) space.
But the array contains exactly 26 slots, one for each letter of the English alphabet. Whether the strings contain 10 characters or a million characters, the array still contains 26 slots.
Its size depends on the size of the alphabet, not the length of the strings. Since the alphabet size is fixed, the space complexity is O(1).
Now let's look at a pattern where the extra memory grows linearly with the input size. Here's a function that checks whether an array contains any duplicate values.
As we iterate through the array, we add each value to a hash set. If we encounter a value that's already in the set, we've found a duplicate.
In the worst case, every element is unique, so we end up storing all n elements in the set. Since the size of the set grows linearly with the input size, the space complexity is O(n).
Loading simulation...
The same pattern appears when we create a copy of an array, build a frequency map, or store all the elements in a stack or queue.
Next, let's look at a pattern that uses a two-dimensional array.
Suppose a robot starts at the top-left corner of an m by n grid and can only move right or down. Our goal is to count the number of unique paths the robot can take to reach the bottom-right corner.
Each cell in the table stores the number of ways to reach that position. We calculate this by adding the path counts from the cell directly above and the cell directly to the left.
Since the table contains m rows and n columns, we need space to store m × n integers. This gives us a space complexity of O(m × n).
Loading simulation...
If the grid is square, with n rows and n columns, the space complexity becomes O(n²).
Graphs are another common case where space complexity depends on two values: the number of vertices, V, and the number of edges, E.
Many graph problems give us a list of edges, which we use to build an adjacency list. The adjacency list maintains a list of neighbors for each vertex.
In an undirected graph, each edge is stored twice, once in the neighbor list of each endpoint. So all the lists together contain 2 × E entries. Accounting for V lists and 2 × E entries gives us a space complexity of O(V + E).
An adjacency matrix, on the other hand, uses a V by V grid, requiring O(V²) space, regardless of how many edges the graph contains.
Traversing a graph also requires extra memory. Consider breadth-first search.
It maintains a visited set to track discovered vertices and a queue to hold vertices waiting to be explored.
Loading simulation...
Each vertex is added to the visited set only once, so the set holds at most V vertices. Similarly, the queue can hold at most V vertices at any given time.
So breadth-first search uses O(V) auxiliary space, in addition to the O(V + E) space required by the adjacency list.
So far, we've focused on memory used by variables and data structures that we explicitly create. But recursion also uses memory that isn't directly visible in the code: the call stack.
Here's a recursive function that calculates the sum of all elements in an array.
Notice that it doesn't create any additional arrays or collections. However, every function call creates a stack frame that stores its parameters, local variables, and information about where execution should resume once the call returns.
When sum(0) calls sum(1), it must wait for sum(1) to return its result. Until then, its stack frame remains in memory. The same thing happens with sum(1), sum(2), and every subsequent call.
By the time we reach the base case, there are n + 1 stack frames in memory at the same time. This gives us a space complexity of O(n), even though we haven't created any additional data structures.
An iterative version of the same function would use only O(1) space.
This also matters in practice. Python typically has a default recursion limit of 1,000, while in Java, too many nested function calls can exhaust the available stack space and trigger a StackOverflowError.
The space complexity of a recursive function depends on the maximum depth of recursion, not the total number of function calls.
Here's a function that calculates the height of a binary tree.
The function visits every node, so it makes O(n) calls in total. But these calls don't all occupy the call stack at the same time.
Once we finish exploring the left subtree, its stack frames are removed before we begin exploring the right subtree. At any given moment, the call stack only contains the frames along a single path from the root to the current node.
So the space complexity is O(h), where h is the height of the tree.
In a balanced binary tree, the height is O(log n), giving us a space complexity of O(log n). Recursive binary search also uses O(log n) space because each recursive call reduces the search range by half.
Loading simulation...
However, in a completely skewed binary tree, the height grows linearly with the number of nodes, so the space complexity becomes O(n).
Let's make this clearer using the recursive Fibonacci function.
This function takes O(2ⁿ) time because the number of recursive calls grows exponentially. You might expect its space complexity to be exponential as well.
However, the call stack only holds one path through the recursion tree at any given time. The deepest path starts at fib(n), goes to fib(n - 1), and continues all the way down to fib(1).
This gives us roughly n stack frames in memory at the same time, resulting in a space complexity of O(n).
Many algorithms use a combination of data structures and recursion. When analyzing their space complexity, we need to account for all the extra memory used at the same time.
Merge sort is a good example. The recursion goes about log n levels deep, so the call stack uses O(log n) space.
However, the merge operation also requires temporary storage, and the largest merge involves all n elements.
Adding O(n) and O(log n), and keeping only the dominant term, gives us an overall space complexity of O(n).
Sometimes the output itself requires a significant amount of memory, so it's useful to analyze it separately. Here's a function that generates all possible subsets of an array.
For each element, we have two choices: either include it in the current subset or leave it out.
Since we make one decision at each level of recursion, the call stack holds at most n + 1 frames. The list representing the current subset also holds at most n elements. Together, these give us O(n) auxiliary space.
But what about the memory needed to store the output? There are 2ⁿ possible subsets, each containing up to n elements. Storing all these subsets requires O(n × 2ⁿ) space.
Loading simulation...
Since the output is required by the problem, we typically don't count it as part of the auxiliary space.
When analyzing a solution like this, it's best to report both separately: O(n) auxiliary space and O(n × 2ⁿ) output space.
So how do you determine the space complexity of a piece of code?