SystemTutor
About
Sign in
Loading course documentation…
SystemTutor

COURSES

  • Data Structures & Algorithms
  • CSS MasterclassNew course
  • System DesignNew course

PRACTICE

  • Algorithm practice
  • CSS practice

LEGAL

  • Privacy Policy
  • Terms of Service
  • About

© 2026 SystemTutor. All rights reserved.

Built with 🫶 by Shatlyk

Course Overview
Algorithm PerformanceBig O & Time ComplexitySpace ComplexityLogarithms and ComplexityProblem Solving ApproachAlgorithm Efficiency and Problem Solving
Big O Notation

Space Complexity

Learn how algorithms use memory, see the difference between extra space and total space, and understand common space complexity levels from O(1) to O(n²).

Analyzing Space Complexity

A scan can read a million numbers while keeping only a running total. A second algorithm could read the same numbers and also keep a set of all the distinct values it encounters. The number of reads is similar, but their storage needs grow differently.

Space complexity measures peak memory use as input size grows. To explain a bound, say which memory you count: storage for the input, working storage such as temporary collections and unfinished calls, and storage for the output. We count a number, index, or reference as one fixed-size slot in the examples below.

These examples count occupied memory slots. A slot used for a returned result belongs to the output.

Space GrowthMeaningCommon Example
Constant O(1)Uses the same amount of extra memory, no matter the input size.Fixed variables, pointers that move inside the original array
Logarithmic O(log n)Extra memory grows by just one step each time the input size doubles.Balanced recursive calls (like recursive Binary Search)
Linear O(n)Extra memory grows at the same rate as the input size.A set holding up to n distinct keys
Quadratic O(n²)Extra memory grows with the square of the input size (n×nn \times nn×n).A grid with n rows and n columns

Constant Auxiliary Space: O(1)

An algorithm uses constant space, O(1), when it only creates a fixed number of variables, no matter how large the input gets.

The following sum keeps a running total as it visits each item. Even though the numbers inside the variables change as the loop runs, the number of variables we create stays the same.

function calculateSum(numbers) {
  let total = 0; // Uses just one variable for the total

  for (let i = 0; i < numbers.length; i++) {
    total += numbers[i]; // Updates total directly without making new variables
  }

  return total; // O(1) Extra Space
}

Another common O(1) pattern is modifying an array directly in place using two pointers:

function reverseInPlace(items) {
  let left = 0;
  let right = items.length - 1;

  while (left < right) {
    // Swap values directly in the original array
    const temp = items[left];
    items[left] = items[right];
    items[right] = temp;

    left++;
    right--;
  }

  return items; // O(1) Extra Space: No new arrays or objects created
}

The swap uses two moving indexes and a fixed amount of temporary storage. Neither implementation copies the array.


Logarithmic Auxiliary Space: O(log n)

An algorithm uses logarithmic space, O(log n), when its extra memory grows by just one small step every time the input size doubles.

One source of logarithmic working storage is the call stack. Imagine searching for 7 in the sorted array [1, 2, 3, 4, 5, 6, 7]. The midpoint values visited are 4 → 6 → 7. When the last call finds 7, it is active alongside the two earlier calls waiting for its return.

The search visits midpoint values 4, 6, and 7. Only three frames are live, for candidate values 1–7, 5–7, and 7–7.

The gray branches show other possible search paths. This search only creates frames for the blue path. In the code below each frame stores a few indexes and passes along the same sorted array.

function binarySearchRecursive(items, target, left = 0, right = items.length - 1) {
  if (left > right) return -1;

  const mid = Math.floor((left + right) / 2);
  if (items[mid] === target) return mid;

  if (items[mid] < target) {
    // Each recursive call adds a frame to the call stack
    return binarySearchRecursive(items, target, mid + 1, right);
  } else {
    return binarySearchRecursive(items, target, left, mid - 1);
  }
}

Each call halves the number of remaining candidates. The number of simultaneously active calls is therefore O(log n) for large inputs, including the final call that finds the target or the empty interval.

Loops vs. Recursion Memory

Binary search written with a normal loop (iterative) uses O(1) extra space because it stays inside one function. The recursive version uses O(log n) extra space because the computer must keep each unfinished function call on the call stack.


Linear Auxiliary Space: O(n)

A linear storage requirement grows in proportion to input size. A set can hold up to one entry per input item.

You usually get linear space when you:

  1. Make a new array, list, or string that stores nnn items.
  2. Put nnn items into a Set or Map / dictionary.
  3. Keep nnn unfinished recursive calls active at the same time.
function findUniqueNumbers(numbers) {
  const seen = new Set(); // Can hold up to n items

  for (const num of numbers) {
    seen.add(num);
  }

  return Array.from(seen); // O(n) Extra Space
}

If numbers has 1,0001,0001,000 items, seen may need to store up to 1,0001,0001,000 items. If all values are identical, the set holds just one number. With k distinct values, the set uses O(k) working space and the returned list also has k positions.


Quadratic storage: O(n²)

An algorithm uses quadratic space, O(n²), when the memory it needs grows with the square of the input size (n×nn \times nn×n).

A grid with r rows and c columns has r × c cells. This multiplication table has n rows and n columns. The function returns the table, so those cells belong to the output.

function createMultiplicationTable(n) {
  const table = []; // Creates n rows, each with n items

  for (let i = 0; i < n; i++) {
    const row = [];
    for (let j = 0; j < n; j++) {
      row.push((i + 1) * (j + 1));
    }
    table.push(row);
  }

  return table; // Total items stored: n * n = O(n²) space
}

If n=10n = 10n=10, the table stores 100100100 numbers (10×1010 \times 1010×10). If n=1,000n = 1,000n=1,000, the table has to store 1,000,0001,000,0001,000,000 numbers in memory.


Extra Space vs. Total Space

Reversing into another array allocates n output slots, while swapping in place reuses the input.

Suppose two functions reverse a list of n items. One swaps items inside the input. The other walks from the end and appends each item to a fresh output list.

What is counted?Reverse in placeBuild a reversed copy
Original inputO(n)O(n)
Working storage (auxiliary, excluding output)O(1) for the swapO(1) for the traversal
New output storageNone, return the inputO(n) for the copy
Extra storage including the outputO(1)O(n)
Total storage including the inputO(n)O(n)

A problem may count the returned collection as extra memory or explicitly exclude required output. State the convention, especially when an algorithm returns a new collection.


Memory in the Recursive Call Stack

Four calls from factorial(4) down to factorial(1) are active together before the base case returns.

Whenever your code calls a function, the computer puts a small block of memory called a stack frame onto the call stack. This stack frame holds:

  • The function's inputs (arguments) and local variables.
  • The return point (where the program should jump back to when the function finishes).

Each stack frame stays in memory until that function call finishes and returns. If a recursive function calls itself nnn times before reaching the end condition (base case), all nnn function calls sit in memory at the exact same time.

// Iterative Factorial: O(1) Auxiliary Space
function factorialIterative(n) {
  let result = 1;
  for (let i = 2; i <= n; i++) {
    result *= i;
  }
  return result; // Only uses two variables: 'result' and 'i'
}

// Recursive Factorial: O(n) Auxiliary Space
function factorialRecursive(n) {
  if (n <= 1) return 1;
  return n * factorialRecursive(n - 1); // Keeps n function calls on the call stack at once
}

The recursive version holds one frame for each unfinished multiplication. The iterative version reuses one frame. These bounds count frames and numeric slots. If you count bytes for exact, arbitrarily large factorial values, the result itself also grows.

Stack Overflow Risk

If a recursive function calls itself too many times, the call stack runs out of memory. When that happens, your program crashes with a Stack Overflow error.


Simplifying Space Complexity

Just like Time Complexity, we simplify Space Complexity using the same Big O rules:

  1. Drop constant numbers and multipliers: If you create two separate arrays of size nnn, that is O(2n)O(2n)O(2n) memory, which simplifies to O(n)O(n)O(n).
  2. Drop smaller terms: If your code creates a 2D grid of size n2n^2n2 and a list of size nnn, the space is O(n2+n)O(n^2 + n)O(n2+n), which simplifies to O(n2)O(n^2)O(n2) because n2n^2n2 grows much faster.
  3. Look at peak memory: Space complexity only counts the most memory used at any one time. Memory that is created, used, and then thrown away (garbage collected) does not keep piling up.
O(2n² + 4n + 16) → O(n²)

Comparing Space Growth from Best to Worst

These example storage sizes grow increasingly quickly for large inputs:

1 → log n → n → n²


Key Takeaways

  • Auxiliary space counts temporary working storage. Report required output storage separately, then say whether your extra-space bound includes it.
  • In-Place Algorithms: Code that achieves O(1) extra space by changing data directly inside the existing array or list instead of creating a new one.
  • Call Stack Memory: Every recursive function call takes up memory on the call stack. A recursive function uses space equal to how deep the calls go.
  • Peak Memory: Space complexity measures the maximum amount of memory used at any single moment, not the total sum of memory used over time.
  • Time vs. Space Trade-offs: Making code faster often costs extra memory (like using a hash table to save results), and saving memory sometimes makes code take longer to run.

How is this lesson?

Previous lessonBig O & Time ComplexityNext lessonLogarithms and Complexity
Edit on GitHubReport on GitHub
On this page
%

On this page

Analyzing Space ComplexityConstant Auxiliary Space: O(1)Logarithmic Auxiliary Space: O(log n)Linear Auxiliary Space: O(n)Quadratic storage: O(n²)Extra Space vs. Total SpaceMemory in the Recursive Call StackSimplifying Space ComplexityKey Takeaways