Foundations
Space Complexity
Understand memory usage in algorithms, auxiliary space trade-offs, and call stack memory.
Last Updated: July 31, 2026
•
15 min read
1. Introduction
What is Space Complexity?
Space Complexity measures how much memory (RAM) an algorithm needs to run to completion as the input size (N) grows.Auxiliary Space vs Total Space
In coding interviews, Space Complexity usually refers to Auxiliary Space.
Where is it Used?
O(1) auxiliary space.2. Mental Model
Imagine a Chef Preparing a Salad.
Both approaches produce the same chopped salad! But Approach 1 leaves your kitchen counter clean, whereas Approach 2 clutter your kitchen counter with extra dishes. Space complexity counts those extra dishes.
3. Concept: Sources of Extra Memory
When your code runs, memory is consumed in two primary places:
1. Variables & Primitive Data Types (O(1) Space)
Storing a few counters or index pointers requires constant extra space:This is O(1) Auxiliary Space because memory does not depend on input size N.
2. Dynamically Allocated Data Structures (O(N) Space)
Creating a copy array or a HashSet to store N elements:This requires O(N) Auxiliary Space.
3. Recursive Call Stack (O(N) or O(log N) Space)
Every time a function calls itself recursively, a new stack frame is pushed onto the call stack storing parameter variables and return addresses.A recursion depth of N calls takes O(N) Call Stack Space.
4. Visuals
Common Space Complexity Ratings
| Auxiliary Space | Description | Code Example | Memory Impact |
|---|---|---|---|
O(1) | Constant Space | In-place array swap, counter variables | 🟢 Minimal (Bytes) |
O(log N) | Logarithmic Space | Call stack depth of Binary Search or balanced Tree | 🟢 Low |
O(N) | Linear Space | Creating a copy array, HashMap, or linear recursion | 🟡 Moderate |
O(N²) | Quadratic Space | Creating an N × N 2D grid matrix | 🔴 High |
5. Real-World Examples
O(1) memory prevent app force-closures when scrolling long feeds.O(1) extra RAM, whereas filters that clone high-resolution 4K bitmap images use O(Width × Height) memory.6. Interview Perspective
How Interviewers Ask This Topic
Interviewers will often push for space optimization: "You solved this inO(N) space using a HashMap. Can you solve it in O(1) space in-place?"
Common Mistakes
Warning: 1. Forgetting Recursion Call Stack: Claiming a recursive function uses
O(1) space because no arrays were created, ignoring the O(N) stack frames!> 2. Confusing Input Space with Auxiliary Space: Counting the input array size as part of the algorithm's memory footprint when the interviewer only asked for extra space.
> 3. String Concatenation Memory: Forgetting that strings are immutable in Java/Python. Appending chars in a loop creates O(N²) garbage objects!
Important Interviewer Tips
O(N) and auxiliary space is O(1)").7. Summary
O(1) space.O(N) space.