Reading history

Space Complexity: Auxiliary Space and Recursion in C

8 min read 0 views

Learn how much memory algorithms need: input vs auxiliary space, O(1) to O(n^2) examples in C, and how recursion quietly uses stack space.

Every program pays two bills: one in time and one in memory. Space complexity is the memory bill, described by how fast the extra storage climbs when you hand the algorithm a bigger input. Speed is not enough on its own: a solution that is fast but needs a gigabyte of extra memory may not run on a phone, a microcontroller or a busy server at all.

In this lesson you will learn

  • The difference between total space and auxiliary (extra) space
  • How to recognise O(1), O(log n), O(n) and O(n²) space
  • Why recursion uses memory even when you never call malloc
  • How to trade memory for speed, and when not to
  • The space cost of common algorithms

Total Space vs Auxiliary Space

An algorithm’s memory has two parts:

  • Input space: memory for the data you were given, such as an array of n numbers.
  • Auxiliary space: any extra memory the algorithm uses while it works: variables, temporary arrays and the call stack.

Total space = input space + auxiliary space. When people compare algorithms, they usually mean auxiliary space, because every algorithm that reads the input needs the input space anyway. Always say which one you mean.

AlgorithmAuxiliary spaceTotal space
Insertion sortO(1)O(n)
Merge sort (arrays)O(n)O(n)
Binary search (loop)O(1)O(n)

Insertion sort and merge sort have the same total space, but very different extra space. That difference is what matters when memory is tight.

O(1) Space vs the Hidden Cost of Recursion

Here are two ways to add up 1,000 numbers. The loop uses a fixed handful of variables. The recursive version looks just as small, but each call waits on the call stack until the one after it returns.

#include <stdio.h>

/* O(1) extra space: a fixed number of variables, whatever n is. */
static long sum_iterative(const int a[], int n) {
    long total = 0;
    for (int i = 0; i < n; i++) total += a[i];
    return total;
}

/* O(n) extra space: every call waits on the stack for the next one. */
static long sum_recursive(const int a[], int n, int depth, int *max_depth) {
    if (depth > *max_depth) *max_depth = depth;
    if (n == 0) return 0;
    return a[n - 1] + sum_recursive(a, n - 1, depth + 1, max_depth);
}

int main(void) {
    int data[1000];
    for (int i = 0; i < 1000; i++) data[i] = i + 1;

    int deepest = 0;
    printf("iterative sum: %ld\n", sum_iterative(data, 1000));
    printf("recursive sum: %ld\n", sum_recursive(data, 1000, 1, &deepest));
    printf("recursive calls alive at once: %d\n", deepest);
    return 0;
}

Output

iterative sum: 500500
recursive sum: 500500
recursive calls alive at once: 1001

Both give the same answer. But while the recursive version runs, 1,001 calls are alive at once, each with its own stack frame holding parameters and a return address. That is O(n) auxiliary space. The loop uses O(1).

The stack is small, typically a few megabytes. Recursing a million levels deep can crash with a stack overflow, even though the program never called malloc. Learn more in Function Call Stack in C.

O(n) vs O(1): Copy or Work in Place?

Many tasks can be done either by building a new array or by changing the original. Reversing an array is a simple example.

#include <stdio.h>
#include <stdlib.h>

/* Reversing an array two ways. */
static int *reversed_copy(const int a[], int n) {      /* O(n) extra space */
    int *out = malloc(n * sizeof *out);
    if (!out) return NULL;
    for (int i = 0; i < n; i++) out[i] = a[n - 1 - i];
    return out;
}

static void reverse_in_place(int a[], int n) {          /* O(1) extra space */
    for (int i = 0, j = n - 1; i < j; i++, j--) {
        int tmp = a[i]; a[i] = a[j]; a[j] = tmp;
    }
}

int main(void) {
    int a[] = {10, 20, 30, 40, 50};
    int n = 5;

    int *copy = reversed_copy(a, n);
    if (!copy) return 1;
    printf("copy:     ");
    for (int i = 0; i < n; i++) printf("%d ", copy[i]);
    printf("\n");
    free(copy);

    reverse_in_place(a, n);
    printf("in place: ");
    for (int i = 0; i < n; i++) printf("%d ", a[i]);
    printf("\n");
    return 0;
}

Output

copy:     50 40 30 20 10 
in place: 50 40 30 20 10
  • reversed_copy allocates a second array of n items: O(n) auxiliary space. The original stays unchanged, which is sometimes exactly what you need.
  • reverse_in_place swaps items using one temporary variable: O(1) auxiliary space. It changes the original array.

An algorithm that uses O(1) extra space is called in-place.

O(log n) Space: Recursion That Halves the Problem

Recursion does not always cost O(n). If each call cuts the problem in half, the stack only grows to about log₂n frames. The program below runs a recursive binary search over more than a million items and records the deepest point.

#include <stdio.h>

/* Recursive binary search: how deep does the call stack get? */
static int depth_max = 0;

static int find(const int a[], int lo, int hi, int target, int depth) {
    if (depth > depth_max) depth_max = depth;
    if (lo > hi) return -1;
    int mid = lo + (hi - lo) / 2;
    if (a[mid] == target) return mid;
    if (a[mid] < target) return find(a, mid + 1, hi, target, depth + 1);
    return find(a, lo, mid - 1, target, depth + 1);
}

int main(void) {
    static int a[1 << 20];                 /* 1,048,576 sorted numbers */
    int n = 1 << 20;
    for (int i = 0; i < n; i++) a[i] = 2 * i;

    find(a, 0, n - 1, -1, 1);              /* missing target: worst case */
    printf("n = %d, deepest recursion = %d calls\n", n, depth_max);
    return 0;
}

Output

n = 1048576, deepest recursion = 21 calls

Only 21 calls are on the stack at the deepest point, because 220 = 1,048,576. That is O(log n) auxiliary space. The loop version of binary search uses O(1), which is why it is usually preferred.

O(n²) Space: Tables and Grids

Storing something for every pair of items costs n² memory. Examples include a distance table between n cities, an adjacency matrix for a graph with n nodes, and many dynamic programming tables.

/* n x n table of road distances between n cities */
int (*dist)[n] = malloc(sizeof(int[n][n]));   /* n * n * 4 bytes */

Quadratic space grows quickly. For n = 10,000 cities, an int table needs 10,000 × 10,000 × 4 bytes = 400 MB. Many dynamic programming problems can be reduced from O(n²) to O(n) space by keeping only the previous row of the table.

Space Complexity Classes at a Glance

Auxiliary spaceWhere it comes fromExample
O(1)A fixed number of variablesLoop sum, in-place reverse, bubble sort
O(log n)Recursion that halves the problemRecursive binary search, quick sort’s stack on average
O(n)A copy of the input, or recursion n levels deepMerge sort, recursive sum, hash set of seen items
O(n²)Something stored for every pairAdjacency matrix, 2D DP table

Trading Memory for Speed

Extra memory often buys speed. Checking an array for duplicates shows the trade-off:

  • Compare every pair: O(n²) time, O(1) extra space.
  • Sort first, then check neighbours: O(n log n) time, O(1) to O(n) extra space depending on the sort.
  • Remember what you have seen in a hash set: O(n) time, O(n) extra space.

On a desktop, the hash set is usually the right choice. On a microcontroller with 2 KB of RAM, the slower in-place method may be the only one that fits.

Common Mistakes

  1. Forgetting the call stack. Recursion uses memory for every active call; count it.
  2. Mixing up total and auxiliary space. State which one you mean, especially in interviews.
  3. Counting only malloc. Large local arrays like int a[100000] inside a function also take stack space, and can overflow it.
  4. Ignoring the size of each item. O(n) of char and O(n) of 1 KB structs are the same class but very different in real megabytes.
  5. Not freeing memory. A leak inside a loop turns O(1) space into ever-growing memory use. Always free what you malloc.

Practice Exercises

Exercise 1. What is the auxiliary space of this function?

int count_even(const int a[], int n) {
    int count = 0;
    for (int i = 0; i < n; i++)
        if (a[i] % 2 == 0) count++;
    return count;
}
Show answer

O(1). It uses only count and i, whatever n is.

Exercise 2. A recursive function calls itself with n - 1 until n reaches 0, and allocates nothing. What is its auxiliary space?

Show answer

O(n), because n + 1 calls can be on the stack at the same time.

Exercise 3. How much memory does a 5,000 × 5,000 table of double values need (8 bytes each)?

Show answer

5,000 × 5,000 × 8 = 200,000,000 bytes, about 200 MB.

Frequently Asked Questions

Does space complexity include the input?

Total space complexity does; auxiliary space does not. Most comparisons of algorithms use auxiliary space, so say which one you mean.

Is O(1) space always better?

Not always. An O(1)-space method may be much slower. Choose based on how much memory you have and how fast the program must be.

Why does recursion use space?

Each call needs a stack frame for its parameters, local variables and return address, and that frame stays alive until the call returns.

What is an in-place algorithm?

One that uses only O(1) extra memory, working directly on the input. Insertion sort and in-place array reversal are examples.

Summary

  • Space complexity measures memory growth; auxiliary space counts only the extra memory.
  • Recursion costs stack space: n levels deep is O(n), halving each time is O(log n).
  • Copying the input is O(n); working in place is O(1).
  • Storing something per pair of items is O(n²) and grows very fast.
  • Extra memory can buy speed; pick the trade-off that suits your device.
Lessons are also marked complete when you click Next.