To calculate space complexity, write down every unit of memory your algorithm allocates as a function of the input size, discard constant factors and lower-order terms, and express what remains in big-O notation. The key condition is that you're counting auxiliary space—memory the algorithm itself uses beyond the input—unless a problem explicitly asks for total space including the input. An algorithm that creates a new array of length n and otherwise uses a few variables is O(n); one that reverses an array in place with a couple of temp variables is O(1).

That short recipe hides most of the real work. You have to know which allocations belong in the count, how recursion consumes memory on the call stack, how languages hide memory behind data structures, and where “input space” ends and “working space” begins. Here's how to work through all of it, with runnable examples you can check by hand.

What Space Complexity Actually Measures

Space complexity describes how the memory an algorithm needs grows as the input size grows. It's a growth rate, not a byte count, so O(n) tells you the requirement scales linearly with input, not that it uses exactly n bytes.

Two conventions dominate:

Total space complexity counts everything: the input plus any auxiliary memory the algorithm allocates. Auxiliary space complexity counts only the extra memory beyond the input.

In algorithm courses and coding interviews, “space complexity” almost always means auxiliary space. The distinction matters because many algorithms keep the input intact and allocate little, while others copy the input. Reversing an array in place uses O(1) auxiliary space; building a reversed copy uses O(n). Both are legitimate answers to different questions.

One more preliminary: fix your variables before you count. For an array, convention is n = number of elements. For a matrix, n × m (or n² for a square grid). For a string, n = length. For a graph, V vertices and E edges. If you mix these mid-calculation, your answer will be wrong even if your reasoning is sound.

Count These Memory Categories

Walk your code and tally each allocation into one of these buckets:

1: Primitive variables and fixed-size locals. A handful of integers, booleans, or references. Constant, so they contribute O(1). 2: Arrays, lists, and buffers sized from the input. These contribute a term proportional to their length—O(n), O(n²), O(V + E), and so on. 3: Hash maps, sets, and lookup tables. Contribution depends on how many distinct entries the algorithm stores, which is often bounded by input size but sometimes bounded by an alphabet (such as 26 letters) and therefore constant. 4: Recursion stack frames. Each active call typically holds its parameters and locals; depth d usually gives O(d) auxiliary space. 5: Temporary objects from library calls. Slicing a list, concatenating strings in a loop, or calling a sort that builds a copy all allocate memory you should attribute to your algorithm. 6: Output containers. Build a result of size n? That's O(n) unless the problem says results don't count.

Then drop constants and lower-order terms and write the dominant term in big-O.

A Worked Procedure You Can Follow Every Time

This is the core of how to calculate space complexity. Apply it in order.

Prerequisite: know the input variables and whether the question asks for auxiliary or total space. Write that assumption at the top of your scratch work.

Step 1 — Mark every allocation. Scan the code statement by statement. Next to each new, array literal, map/set creation, slice, concatenation, or recursive call, note what it allocates in terms of the input variables.

Step 2 — Classify each as constant, proportional, or compounding. A single counter is constant. A list that gains one element per input item is O(n). A list of lists (or an n × n matrix) is O(n²). A structure filled once and then queried repeatedly stays proportional to what it ultimately holds, not to how many times it's read.

Step 3 — Add the terms. If you hold an array of size n plus a hash map of at most n keys plus a few variables, the total is n + n + constant.

Step 4 — Simplify. Drop coefficients (2n becomes n) and lower-order terms (n + log n becomes n). Keep the largest growth term.

Step 5 — Handle recursion separately. Sum frame memory across the deepest chain of active calls, not all calls ever made. Then combine with that call's other allocations using the rules in the recursion section below.

Step 6 — Verify with two input sizes. Mentally run n = 1 and n = 100. Does the peak-memory estimate plausibly grow the way your notation claims? This catches the classic error of labeling something O(1) because you only allocated “one” structure—when that structure's size depends on n.

Success check: state your answer out loud as “auxiliary space is O(...)” and confirm every term in the code maps to something you counted. A common failure is missing what a library call allocates, which step 1 is designed to catch.

Worked Example: A Copying Loop Versus an In-Place Reverse

Here is a complete calculation you can reproduce.

Count: the result list holds n elements, so O(n). temp and the loop index are constants. Total auxiliary space: O(n).

Count: two integer indices and one swap variable. No structure grows with n. Auxiliary space: O(1). The input array is modified, not copied.

Same task, different memory profiles. If someone asks for total space including input, both are O(n)—because the input itself is n elements—which is exactly why stating your convention matters.

Recursion: Counting Stack Frames Correctly

Each pending call occupies a stack frame until it returns. For a linear recursion like computing a factorial or walking a linked list, the deepest chain is n frames, each O(1), so auxiliary space is O(n)—even though the function allocates no arrays. This is the single most common surprise in space-complexity questions.

For binary recursion like naive Fibonacci, the stack depth is n but the number of calls is exponential; space follows the depth, not the call count, so it's O(n) auxiliary. The runtime is exponential, but space is not, because frames unwind as calls return.

Binary search is the instructive mixed case. Recursive binary search recurses log n deep with O(1) per frame: O(log n) auxiliary space. The iterative version uses O(1). Same result, different memory.

When a recursive function also allocates per frame—say, slicing the array at each call, which is common in quicksort written in Python-style pseudocode—the allocations compound. A merge sort that copies n/2 elements at each of log n levels of recursion holds peak memory of roughly n + n/2 + n/4 + … ≈ 2n for one active path, which simplifies to O(n) auxiliary space. The geometric series doesn't change the big-O, but it explains why the constant looks like 2 rather than 1.

Watch Language-Level Allocation You Didn't Write

Your count is only as good as your model of the language.

String concatenation in a loop. In languages where strings are immutable, building an n-character result by appending one character at a time may allocate intermediate strings. The peak live memory is usually still O(n), but the churn is O(n²) in time. Stick to live-memory peaks for space complexity, not the total amount ever allocated. Slices and copies. arr[1:], list.copy(), and similar calls allocate. In quicksort implementations that slice, that's O(n) peak auxiliary space rather than the O(log n) of an index-based version. Hash map overhead. A map with n keys is O(n) in asymptotic terms; the constant factor might be several words per entry. Asymptotics don't care, but capacity planning does. Sorting. Python's sorted() builds a new list, adding O(n). In-place sorts like heapsort add O(1) auxiliary (ignoring recursion); merge sort typically needs O(n) extra buffer space.

The safe move: if you can't confidently say whether a call copies, assume it might and say so. Naming the assumption is better than silently guessing.

Total Versus Auxiliary Space in Practice

Use total space when the question is about overall memory footprint—say, deciding whether a program fits in an embedded device's RAM. Use auxiliary space when comparing algorithms on the same input, because the input cost cancels out.

The mismatch trips people up: an “in-place” algorithm is O(1) auxiliary but O(n) total on an n-element array. Neither label is wrong; they answer different questions. Write down your convention first, then answer, and you'll never be caught out by the ambiguity.

Check Your Answer Against Edge Cases

Before finalizing, test these:

Empty and single-element input. Does the notation still make sense? O(n) covers it trivially; O(log n) behaves oddly at n = 1 but is standard convention. Worst-case versus typical. A hash set of n elements is O(n) regardless, but an algorithm that only sometimes builds a full auxiliary structure should be analyzed at its worst case unless the question says otherwise. The “one big structure” trap. Allocating a single array of size n is O(n), not O(1). Students lose points on this constantly. The “many constant structures” trap. Allocating a million fixedsize counters is still O(1) asymptotically—but it's a bad answer for a practical question, so mention the constant if the prompt is engineering-oriented.

Common Mistakes and How to Catch Them

The most frequent error is forgetting the recursion stack, which flips many answers from O(1) to O(n). The second is counting the input when the question asked for auxiliary space. The third is trusting a library call not to allocate. The fourth is confusing runtime with space: a nested loop doesn't automatically mean O(n²) space—only nested allocation does.

A quick sanity routine: after you write your answer, ask “where does the peak live memory occur?” If you can point to the line of code and express its size in n, you've probably got it. If not, you've missed an allocation.

When to Stop and Recheck With a Professional

This is general educational material about algorithm analysis, not something that requires professional advice. If you're analyzing memory for a production system with real constraints—embedded firmware, a hard memory cap, or a latency-sensitive service—the asymptotic answer is only the starting point. Measure actual peak memory with your language's profiling tools in your real environment, and involve the engineers responsible for that system before committing to a design based on a big-O estimate.