Computer ScienceAlgorithmsMedium

Space Complexity

Also known as:Memory complexityAuxiliary space

Space complexity is a measure of the amount of memory an algorithm requires as a function of the size of its input, expressed in Big O notation. It includes both the memory needed to store the input (input space) and any additional auxiliary memory allocated during execution (auxiliary space). Optimising space complexity is critical in memory-constrained environments such as embedded systems or mobile devices.

Key Formula

S(n) = O(g(n))

LaTeX: S(n) = O(g(n))

SymbolMeaningUnit
S(n)Memory usage of the algorithmbytes / words
nSize of the inputelements
g(n)Function bounding the memory growthdimensionless

Worked Example

Problem

A recursive algorithm to compute the nth Fibonacci number calls itself n times, with each call using a constant amount of stack space. What is the space complexity?

Solution

Step 1: Each recursive call pushes a stack frame onto the call stack. Step 2: The maximum depth of recursion is n. Step 3: Each frame uses O(1) space. Step 4: Total space = n × O(1) = O(n).

Answer

O(n) — linear space complexity due to the call stack.

Space Complexity of Common Algorithms

AlgorithmSpace ComplexityReason
Array lookupO(1)No extra memory needed
Iterative loopO(1)Fixed number of variables
Merge sortO(n)Requires auxiliary array
Recursive DFSO(h)h = height of call stack
Hash tableO(n)Stores n key-value pairs
Bubble sortO(1)In-place swapping only

Interactive Tools

Big-O Cheat Sheet

Reference for time and space complexities

Open Tool

Khan Academy – Algorithms

Algorithm analysis tutorials

Open Tool

Brilliant.org

Interactive complexity problems

Open Tool
Graph comparing growth functions used in complexity analysis

Wikimedia Commons, CC BY-SA

Related Terms

Space complexity is a concept from computational complexity theory, developed alongside time complexity in the 1960s. Formally defined within the framework established by Juris Hartmanis and Richard Stearns, and later extended by researchers such as Walter Savitch.

space-complexitymemoryalgorithmsbig-ocomputer-science