Space complexity
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Space complexity measures how much working memory an algorithm needs as the input size n grows. Just as running too many steps causes Time Limit Exceeded, allocating too much memory causes OutOfMemoryError or Memory Limit Exceeded.
Extra memory versus input memory
Space complexity is the extra memory an algorithm needs as a function of the input size, not counting the input itself.
When your method receives an int[] nums of length n, that array already occupies memory before your method starts. In coding interviews and algorithm analysis, we focus on auxiliary space (usually just called extra space)—the additional memory your method allocates while running.
Example 1 · O(n) extra space vs O(1) in-place array reversal
import java.util.Arrays;
public class SpaceComparisonReverseDemo { // Allocates a brand-new array of length n -> O(n) time, O(n) extra space public static int[] reverseWithExtraArray(int[] nums) { int[] copy = new int[nums.length]; for (int i = 0; i < nums.length; i++) { copy[i] = nums[nums.length - 1 - i]; } return copy; }
// Swaps elements inside nums using 3 int variables -> O(n) time, O(1) extra space public static void reverseInPlace(int[] nums) { int left = 0; int right = nums.length - 1; while (left < right) { int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; left++; right--; } }
public static void main(String[] args) { int[] a = {10, 20, 30, 40}; int[] copied = reverseWithExtraArray(a); System.out.println("Extra array : " + Arrays.toString(copied)); reverseInPlace(a); System.out.println("In-place : " + Arrays.toString(a)); }}Extra array : [40, 30, 20, 10] In-place : [40, 30, 20, 10]
What this code does
reverseWithExtraArrayallocatesnew int[nums.length], so its memory grows linearly withn(O(n)).reverseInPlaceonly usesleft,right, andtempregardless of how largenumsis (O(1)extra space).
- Input memory: The space already used by the parameters passed into your method.
- Extra (auxiliary) space: New arrays, collections, objects, or stack frames created by your method.
- Usually, unless a prompt says otherwise, required output arrays are stated separately ('
O(1)extra space beyond the returned array').
If your method only declares a few primitive variables (int i, int sum, long max), it uses the exact same tiny amount of extra memory whether n is 10 or 10,000,000. That is O(1) extra space.
for (...) { int temp = ...; }) still uses O(1) space because the same single stack slot is reused on every iteration.Arrays, maps, and copies
Extra space grows with n whenever your code allocates a data structure whose size depends on n. For example, new int[n], Arrays.copyOf(nums, nums.length), or s.toCharArray() allocates n slots on the heap, costing O(n) extra space.
Example 2 · Why a fixed 26-letter frequency array is O(1) space
public class FixedAlphabetSpaceDemo { // Even if s has 1,000,000 characters, counts[] always has length 26! // Time: O(n) | Extra Space: O(1) public static int maxLetterFrequency(String s) { int[] counts = new int[26]; int max = 0; for (int i = 0; i < s.length(); i++) { int idx = s.charAt(i) - 'a'; counts[idx]++; if (counts[idx] > max) { max = counts[idx]; } } return max; }
public static void main(String[] args) { System.out.println("Max freq in 'mississippi': " + maxLetterFrequency("mississippi")); }}Max freq in 'mississippi': 4
What this code does
- Notice that
s.charAt(i)reads characters directly fromsinO(1)space, whereas callings.toCharArray()would have allocated anO(n)char[]copy! - Because
new int[26]is a fixed constant size independent ofs.length(), the extra space isO(1).
new int[n]ornew ArrayList<>(n)->O(n)space.new int[n][n](ann x n2D grid) ->O(n²)space.new int[26]ornew int[128](fixed alphabet table) ->O(1)space.- Hidden copies:
s.toCharArray(),s.split(" "), andArrays.copyOf(...)all allocateO(n)memory.
Collections also cost space proportional to how many distinct items they store: a HashSet or HashMap holding up to n elements uses O(n) space. By contrast, a fixed-size frequency array for lowercase English letters—new int[26]—always has length 26 no matter how long the string is, so it uses O(1) extra space!
The call stack in recursion
Recursion uses memory even without new, because every call adds a stack frame, a saved set of that call's variables. The code below compares a deep recursion with a shallow one.
A stack frame stays in memory until that call returns. So the space cost of recursion equals the maximum depth of active calls on the stack at the same time. If countdown(n) calls countdown(n - 1) all the way down to 0, there are n + 1 frames stacked up at the bottom, costing O(n) stack space.
Example 3 · Recursive stack depth: O(n) vs O(log n) call stack space
public class RecursionStackDepthDemo { // Linear recursion: depth grows by 1 down to 0 -> O(n) stack frames public static int linearDepth(int n, int currentDepth) { if (n <= 1) { return currentDepth; } return linearDepth(n - 1, currentDepth + 1); }
// Halving recursion: n is divided by 2 each call -> O(log n) stack frames public static int halvingDepth(int n, int currentDepth) { if (n <= 1) { return currentDepth; } return halvingDepth(n / 2, currentDepth + 1); }
public static void main(String[] args) { System.out.println("Linear max depth (n=1024) : " + linearDepth(1024, 1)); System.out.println("Halving max depth (n=1024): " + halvingDepth(1024, 1)); }}Linear max depth (n=1024) : 1024 Halving max depth (n=1024): 11
What this code does
linearDepth(1024, 1)keeps1,024stack frames alive at the same time before reaching the base case (O(n)space).halvingDepth(1024, 1)reaches the base case in just11frames (O(log n)space).
Even if a method never uses new, it can still use O(n) memory if it calls itself recursively! Every time a method calls another method (or itself), the JVM pushes a stack frame onto the call stack to hold that call's parameters, local variables, and return address.
- Recursive countdown
f(n) -> f(n - 1): max depth isn->O(n)stack space. - Recursive halving
f(n) -> f(n / 2)(like recursive binary search): max depth islog₂(n)->O(log n)stack space. - Too many frames (typically around
5,000to10,000in Java 17) throwsStackOverflowError.
Predict the output
Count the stack frames
Read each method and pick the answer.
Round 1 of 2
In-place algorithms
An in-place algorithm updates or rearranges the elements inside the original input array using only O(1) extra variables, instead of allocating a second array.
For example, reversing an array by creating int[] rev = new int[n] takes O(n) extra space. Reversing it in place by swapping nums[left] and nums[right] with a single int temp variable takes O(1) extra space.
- Extra-space version (
O(n)space): leaves the original array untouched, uses more memory. - In-place version (
O(1)extra space): mutates the input array directly, saves memory.
Next step
Check your understanding
10 quick questions