M03 · Big O

Space Complexity, the Call Stack and Multiple Inputs

Time is not the only resource. An algorithm that allocates a table per element, or recurses a million levels deep, can fail long before it runs out of time. This lesson measures extra memory the way the previous lessons measured operations, counts the call stack, and shows how to state bounds honestly when the input has more than one size.

~30 minBeginnerC# · Python · Java · C++
Curriculum: M03 Big O · 3 of 3 lessons available

You will be able to

  • Distinguish auxiliary space from total space and say whether the input and output are counted.
  • Count the call stack as memory: recursion depth times the size of a frame.
  • Explain what "in place" means, including the O(log n) stack of in-place recursive sorts.
  • Trade memory for time (hash sets, tables, memoization) and time for memory (rolling rows), and state both costs.
  • Write bounds with one variable per independent input size, such as Θ(n + m), Θ(n · m) and O(V + E).

Helpful before this lesson

  • M01 Algorithmic Thinking — Turn a vague task into precise inputs, outputs and constraints, then argue that a solution is correct.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Two ways to count memory

  • Total space: everything the algorithm holds, including its input.
  • Auxiliary (extra) space: what it allocates beyond the input: temporary arrays, hash sets, the call stack.

Algorithm analysis almost always reports auxiliary space, because the input exists either way. The output is usually reported separately: generating every subset needs Θ(n · 2ⁿ) memory if you keep them all, but that is the size of the answer, not overhead.

Memory is counted the same way as time: choose a unit (an element, a reference, a stack frame), count how many exist at the same time at the peak, and keep the growth class. Memory that is freed and reused does not add up: a loop that allocates and drops a temporary buffer of size n on every iteration does Θ(n²) work but needs only Θ(n) space at any moment (plus whatever the garbage collector has not reclaimed yet).

The call stack is memory

Each active function call keeps a frame on the call stack: its parameters, local variables and return address. A recursion that is d levels deep holds d frames at its deepest point, so its stack space is Θ(d) frames, even if it never allocates an object.

The lab above computes a power two ways and tracks Max stack depth:

  • Linear: 2^10 recurses on e − 1: 11 frames pile up before the first one returns. Depth Θ(e).
  • Squaring: 2^10 recurses on e / 2 (10, 5, 2, 1, 0): 5 frames. Depth Θ(log e).
  • Stack overflow asks the linear version for 2^20 on a simulated stack of 12 frames: it needs 21 and fails. The squaring version would need 6.

Same answer, same idea, very different memory. The exercises show the pattern on other code:

Exercise Time Stack space
Recursion that peels off one element Θ(n) Θ(n)
Recursion on half the input Θ(log n) Θ(log n)
Naive recursive Fibonacci Θ(φⁿ) Θ(n)
Two halves plus constant work Θ(n) Θ(height)

Naive Fibonacci is the instructive one: exponentially many calls, but only n of them are ever on the stack at once, because each branch returns before its sibling starts. Space is the peak, not the total. The recursion lesson covers frames and unwinding in detail.

In place

An algorithm is in place if it needs only O(1) auxiliary space beyond the input, or, in a common looser usage, O(log n) for a recursion stack. Examples:

Algorithm Auxiliary space
insertion, selection, bubble sort O(1)
heap sort O(1)
quicksort O(log n) stack if it recurses on the smaller part first; Θ(n) worst case if it does not
merge sort on arrays Θ(n) buffer
reversing an array with two pointers O(1)

Built-in sorts differ, and their documentation says so. Java's Arrays.sort for objects (a merge-based sort) documents temporary storage from a small constant for nearly sorted input up to n/2 object references for random input. C++ std::stable_sort is O(n log n) comparisons when it can allocate a buffer and O(n log² n) when it cannot: the same algorithm trading time for memory.

Trading memory for time, and back

Many speed-ups buy time with memory:

  • A hash set of seen values turns an all-pairs Θ(n²) duplicate check into Θ(n) expected time, for Θ(n) extra space (badge duplicates).
  • A prefix-sum array answers any range sum in O(1) after Θ(n) time and Θ(n) space (prefix sums lesson).
  • Memoization stores each subproblem's answer once: Fibonacci drops from exponential to Θ(n) time, at Θ(n) space.

The reverse also works. The n × n table exercise needs Θ(n²) cells, but each row depends only on the previous one, so two rows suffice: Θ(n) space, the same Θ(n²) time. Dynamic programming (M32) uses this constantly.

Constant factors are bigger in memory

O-notation hides the size of one element, and in memory that factor varies a lot between languages:

  • C# List<int> and C++ std::vector<int> store the 4-byte integers themselves, contiguously.
  • Java ArrayList<Integer> stores references to separately allocated Integer objects; each boxed value carries an object header, so the memory per element is several times that of an int[].
  • Python list stores references to int objects; every element is a full object on the heap. The array module or NumPy store raw numbers when that matters.

All four are Θ(n) space. The real numbers can differ by a factor of four or more, which decides whether a dataset fits in memory or in cache. The contiguous storage lesson shows the effect on traversal speed.

Language notes: how deep can you recurse?

The stack is much smaller than the heap, so stack space is often the binding limit:

  • Python stops recursion at a configurable limit (sys.getrecursionlimit(), 1000 by default) with a RecursionError. sys.setrecursionlimit can raise it, but the documentation warns that a limit too high for the platform can crash the interpreter.
  • C#: a StackOverflowException cannot be caught; since .NET 2.0 the process terminates. Recursion depth must be bounded by design.
  • Java throws StackOverflowError, which can technically be caught but leaves no safe way to continue. The thread stack size is set with -Xss or the Thread constructor.
  • C++ has no required check at all: the standard does not describe stack exhaustion, and in practice it usually crashes the process. Default main-thread stacks are commonly 1 MB on Windows and 8 MB on Linux.

The usual fix is to convert deep recursion into a loop with an explicit stack on the heap, or to change the recursion so its depth is logarithmic, as the squaring version of power does.

Multiple inputs: one variable per size

When the input has several independent sizes, keep a variable for each. Collapsing them to one n hides real behaviour.

Situation Honest bound Wrong simplification
nested loops over two lists Θ(n · m) O(n²): wrong when m is tiny or huge
build a set from one, probe with the other Θ(n + m) expected O(n): drops the cost of the probes
BFS or DFS on a graph with adjacency lists O(V + E) O(V²): only true for dense graphs
comparing two strings of lengths n and m by dynamic programming Θ(n · m)
inserting a word of length L into a trie O(L), independent of the number of words O(n)
answering a range query that returns k results from a balanced tree O(log n + k) O(log n): ignores the output

You may merge variables only when you know how they relate. If m ≤ n always, then Θ(n + m) = Θ(n). For a connected graph E ≥ V − 1, so O(V + E) = O(E). Without such a guarantee, keep both.

Space follows the same rule. Building a set from the first list in the sequential example costs Θ(n) space, not Θ(n + m): the second list is only read.

Common mistakes

  • Calling recursive code O(1) space because it allocates nothing. The stack counts.
  • Adding up memory that is freed instead of measuring the peak.
  • Counting the input or output as overhead, or forgetting to say whether you did.
  • Writing O(n²) for two different inputs. Use n and m.
  • Raising Python's recursion limit to fix a deep recursion instead of removing the depth.
  • Ignoring element size when deciding whether data fits in memory.

Worked practice

1. Recursive binary search on n elements: time and auxiliary space? Iterative?

Recursive: Θ(log n) time and Θ(log n) stack frames. Iterative: Θ(log n) time and O(1) auxiliary space. Same algorithm, different memory.

2. Merging two sorted arrays of lengths n and m into a new array: time and space?

Time Θ(n + m): every element is written once. Space Θ(n + m) for the output; O(1) auxiliary space beyond the output. See merge two sorted arrays.

3. Naive Fibonacci makes about 1.6ⁿ calls. Why is its stack space only Θ(n)?

Space is the peak number of frames alive at once. A call to fib(k) finishes fib(k − 1) entirely before starting fib(k − 2), so at most one root-to-leaf path is on the stack, and the longest path has about n frames.

4. An algorithm loops over n words and, for each, over its L characters. Someone writes O(n²). What should it be?

Θ(n · L) if every word has length at most L, or Θ(total number of characters). n² would only be right if L grew like n, which nothing in the problem says.

Summary

  • Report auxiliary space, the peak memory beyond the input, and say how you treat the output.
  • Every active call holds a frame: recursion depth is space, and the stack is small.
  • In place means O(1) extra space (O(log n) for a recursion stack in the looser usage).
  • Speed often costs memory (hash sets, tables, memo); rolling arrays and different recursions buy it back.
  • Keep one variable per independent size: Θ(n + m), Θ(n · m), O(V + E). Merge them only when you know how they relate.

Full implementation

Both recursive powers in four languages, each checked against one shared fixture (zero exponent, zero and negative bases, results up to the 64-bit limit) and 2,000 random cases compared with an exact reference (BigInteger, Python ints or a checked loop); the C#, Java and C++ tests also confirm that a result past 64 bits throws instead of wrapping, and the Python and Java tests trigger a real RecursionError and StackOverflowError.

namespace Bekadan.Dsa.Examples.Recursion;
 
/// <summary>
/// Integer power b^e computed recursively, two ways. Both use 64-bit integers and
/// <c>checked</c> multiplication, so a result that does not fit throws
/// <see cref="OverflowException"/> instead of silently wrapping around.
/// </summary>
public static class RecursivePower
{
    /// <summary>Linear recursion: one call per unit of e, so e + 1 frames deep. Θ(e) time and stack.</summary>
    public static long Linear(long b, int e)
    {
        ArgumentOutOfRangeException.ThrowIfNegative(e);
        if (e == 0)
            return 1;
        long rest = Linear(b, e - 1);
        return checked(b * rest);
    }
 
    /// <summary>Recursion by squaring: the exponent halves on every call. Θ(log e) time and stack.</summary>
    public static long Squaring(long b, int e)
    {
        ArgumentOutOfRangeException.ThrowIfNegative(e);
        if (e == 0)
            return 1;
        long half = Squaring(b, e / 2);
        if (e % 2 == 0)
            return checked(half * half);
        return checked(half * half * b);
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Recursion/RecursivePower.cs

"""Integer power b**e computed recursively, two ways.
 
Python integers have arbitrary precision, so these never overflow; the other three
languages use 64-bit integers and check every multiplication. What Python does limit
is recursion depth: linear recursion needs e + 1 frames, and the interpreter raises
RecursionError past sys.getrecursionlimit() (1000 by default).
"""
 
 
def power_linear(b: int, e: int) -> int:
    """Linear recursion: one call per unit of e. Θ(e) time and stack."""
    if e < 0:
        raise ValueError("e must be non-negative")
    if e == 0:
        return 1
    rest = power_linear(b, e - 1)
    return b * rest
 
 
def power_squaring(b: int, e: int) -> int:
    """Recursion by squaring: the exponent halves on every call. Θ(log e) calls and stack."""
    if e < 0:
        raise ValueError("e must be non-negative")
    if e == 0:
        return 1
    half = power_squaring(b, e // 2)
    if e % 2 == 0:
        return half * half
    return half * half * b

Tested on CPython 3.14.0 · examples/python/dsa_examples/recursive_power.py

package dev.bekadan.dsa.recursion;
 
/**
 * Integer power b^e computed recursively, two ways. Both use 64-bit {@code long} and
 * {@link Math#multiplyExact(long, long)}, so a result that does not fit throws
 * {@link ArithmeticException} instead of silently wrapping around.
 */
public final class RecursivePower {
    private RecursivePower() {
    }
 
    /** Linear recursion: one call per unit of e, so e + 1 frames deep. Θ(e) time and stack. */
    public static long linear(long b, int e) {
        if (e < 0) {
            throw new IllegalArgumentException("e must be non-negative");
        }
        if (e == 0) {
            return 1;
        }
        long rest = linear(b, e - 1);
        return Math.multiplyExact(b, rest);
    }
 
    /** Recursion by squaring: the exponent halves on every call. Θ(log e) time and stack. */
    public static long squaring(long b, int e) {
        if (e < 0) {
            throw new IllegalArgumentException("e must be non-negative");
        }
        if (e == 0) {
            return 1;
        }
        long half = squaring(b, e / 2);
        if (e % 2 == 0) {
            return Math.multiplyExact(half, half);
        }
        return Math.multiplyExact(Math.multiplyExact(half, half), b);
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/recursion/RecursivePower.java

#pragma once
 
#include <cstdint>
#include <limits>
#include <stdexcept>
 
namespace bekadan::dsa {
 
// Signed overflow is undefined behaviour in C++, so check before multiplying
// (the bounds test from SEI CERT rule INT32-C).
inline std::int64_t checked_multiply(std::int64_t a, std::int64_t b) {
    constexpr auto max = std::numeric_limits<std::int64_t>::max();
    constexpr auto min = std::numeric_limits<std::int64_t>::min();
    const bool overflows = a > 0 ? (b > 0 ? a > max / b : b < min / a)
                                 : (b > 0 ? a < min / b : a != 0 && b < max / a);
    if (overflows) throw std::overflow_error("power does not fit in 64 bits");
    return a * b;
}
 
// Linear recursion: one call per unit of e, so e + 1 frames deep. Θ(e) time and stack.
inline std::int64_t power_linear(std::int64_t b, int e) {
    if (e < 0) throw std::invalid_argument("e must be non-negative");
    if (e == 0) return 1;
    const std::int64_t rest = power_linear(b, e - 1);
    return checked_multiply(b, rest);
}
 
// Recursion by squaring: the exponent halves on every call. Θ(log e) time and stack.
inline std::int64_t power_squaring(std::int64_t b, int e) {
    if (e < 0) throw std::invalid_argument("e must be non-negative");
    if (e == 0) return 1;
    const std::int64_t half = power_squaring(b, e / 2);
    if (e % 2 == 0) return checked_multiply(half, half);
    return checked_multiply(checked_multiply(half, half), b);
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/recursive_power.hpp

References