Space complexity
Space complexity describes how much extra memory an algorithm needs as its input grows. In Java that memory includes the call stack, not only the objects you allocate.
Detailed Explanation
Time complexity gets all the attention, but memory is the resource that fails loudly. Running out of heap throws OutOfMemoryError and running out of stack throws StackOverflowError. Both kill the request, and often the process.
Space complexity is measured the same way as time complexity, with Big-O, and it almost always means auxiliary space: the memory you allocate on top of the input. Summing an int[] of a million elements is O(1) auxiliary space, because you keep one running total no matter how large the array is. Copying that array into a List first is O(n).
There are two places the memory goes. The heap holds your arrays, collections and objects. Each thread's stack holds one frame per active method call, and each frame holds that call's locals. That second one is easy to forget. A recursive method that descends n levels uses O(n) stack space even if it allocates nothing at all.
Java's representation choices change the constant factor sharply, and the numbers are worth memorising. An int is 4 bytes. An Integer is a heap object: 16 bytes on a typical 64-bit JVM with compressed object pointers, plus the 4-byte reference pointing at it. So int[1_000_000] costs about 4 MB, while List<Integer> with the same million values costs roughly 20 MB. A HashMap<Integer, Integer> entry is worse again, because each entry is its own Node object holding a hash, a key reference, a value reference and a next pointer, landing near 50 bytes per entry before the boxed keys and values.
That is why the advice "use int[] for your DP table, not HashMap<Integer, Integer>" is about memory as much as speed. The complexity class is identical. The constant is five times apart.
Sorting is a good illustration of auxiliary space in the library. Collections.sort and Arrays.sort(Object[]) use TimSort, which is stable and needs up to O(n) temporary space for merging. Arrays.sort(int[]) uses dual-pivot quicksort, which sorts in place and uses O(log n) space for its recursion. The phrase "in-place" almost never means literally zero extra memory.
You reach for space analysis when the input will not fit comfortably in memory, when you are asked in an interview to "do better than O(n) space", and when a batch job dies overnight on the one day the input doubled. The common wins are streaming instead of collecting, reusing a single buffer, rolling a two-dimensional DP table down to two rows, and replacing boxed collections with primitive arrays.
The trade-off runs in both directions. Memoisation buys time with space. Recomputing a value buys space with time. Neither answer is right in isolation; the right one depends on which resource you are short of.
Code Examples
public class FibonacciSpace {
// O(n) time, O(n) space: the whole table is kept alive.
static long fibTable(int n) {
long[] table = new long[n + 1]; // n+1 slots because indices 0..n are used
table[0] = 0;
table[1] = 1;
for (int i = 2; i <= n; i++) {
table[i] = table[i - 1] + table[i - 2];
}
return table[n];
}
// O(n) time, O(1) space: only the last two values are ever needed.
static long fibRolling(int n) {
if (n < 2) return n;
long previous = 0;
long current = 1;
for (int i = 2; i <= n; i++) {
long next = previous + current;
previous = current;
current = next;
}
return current;
}
public static void main(String[] args) {
System.out.println(fibTable(90)); // prints: 2880067194370816120
System.out.println(fibRolling(90)); // prints: 2880067194370816120
// long is required here: fib(47) already overflows int.
}
}public class StackIsSpaceToo {
// Allocates nothing on the heap, yet uses O(depth) stack space.
static int depth(int level) {
return level == 0 ? 0 : 1 + depth(level - 1);
}
public static void main(String[] args) {
System.out.println(depth(10_000)); // prints: 10000
try {
depth(10_000_000); // far past the default stack size
} catch (StackOverflowError e) {
System.out.println("stack exhausted"); // prints: stack exhausted
}
}
}Common Gotchas
Recursion depth is space, and the JVM enforces it
the default thread stack is around 512 KB to 1 MB, which is roughly ten to twenty thousand simple frames. Recursing over a list of 100,000 nodes throws `StackOverflowError`. Raise it with `-Xss4m` or, better, rewrite the recursion with an explicit `ArrayDeque`.
Boxed collections cost several times what the numbers cost
`Map<Integer, Integer>` stores two heap objects and a node per entry. For dense integer keys use `int[]`, and for sparse ones consider a primitive-specialised map library. The complexity is unchanged; the byte count is not.
"In place" still uses memory
`Arrays.sort` on primitives needs `O(log n)` stack for recursion, and `Collections.sort` needs an `O(n)` merge buffer. Claiming `O(1)` space for a sort-based solution is wrong.