Space Complexity & Call Stack Mechanics
Processor speed isn't the only bottleneck. Learn how to track physical memory footprints, auxiliary space rules, and recursive stack frames across your code bases.
1. Defining Space Complexity
While time complexity measures how long code takes, space complexity calculates the total amount of volatile memory (RAM) your algorithm requires relative to the input size ($n$). This includes both input storage and auxiliary space (extra memory allocated by the algorithm itself).
2. Auxiliary Space vs. Total Space
When interviewers ask for space complexity, they usually want the auxiliary space. If a function accepts an array of size $n$ and creates a duplicate list of size $n$, the auxiliary space is $O(n)$, while the total space is $O(n + n)$, which simplifies back to $O(n)$.
3. Understanding Recursive Stack Memory
Every time a function calls itself recursively, the system pushes a new stack frame onto the call stack to hold local variables and return addresses. If a recursive function runs $n$ times deep before hitting a base case, its space complexity is automatically $O(n)$ regardless of variables declared inside!
Quick Check: Test Your Intuition
If a recursive function makes $n$ sequential self-calls before reaching its termination base case, what is its minimum auxiliary space complexity?