Algorithms

Time and space complexity: how much an algorithm spends

Cover of the article Time and space complexity: how much an algorithm spends
Focused reading

Understand the context.
Put it into practice.

Leia este artigo em português

In this article
  1. What are the two costs of an algorithm?
  2. How do you measure the memory an algorithm uses?
  3. Does recursion use memory too?
  4. Can you trade memory for time?
  5. Now you ask: what matters more, time or memory?
  6. What are the most common mistakes?
  7. Now it’s your turn!

Time complexity measures how many steps an algorithm takes as the input grows. Space complexity measures how much memory it needs to do that. Both use the same ruler: Big O notation.

In the article about Big O notation, we counted steps. Today we’ll look at the other resource every program consumes: memory. And you’ll see that, very often, you can trade one for the other.

What are the two costs of an algorithm?

Think of the times table. The teacher asks what 7 × 8 is, and you don’t know it by heart. You can add 7 eight times: no paper needed, but it takes time. Or you can write the times table on a sheet once and, next time, just look. The sheet takes up space, but the answer comes right away.

Three-panel comic: the teacher asks what 7 times 8 is and the student adds 7 at a time in his head; then he writes the 7 times table on a sheet of paper; at the next question, he just looks at the sheet and answers 56 right away
Adding every time costs time; writing down the times table costs paper. These are the two costs of an algorithm.

Algorithms work the same way. Every program spends two resources:

  • Time: how many steps it takes to finish. That is what Big O notation measures when it counts the turns of a loop.
  • Space: how much extra memory it needs while it works: variables, lists and even the call stack.

Notice the word extra. The input, that list the algorithm receives to work on, doesn’t count. What you measure is what the algorithm creates beyond it, and that space even has a name: auxiliary space.

And there are two ways to find these costs, which work for both time and space: measure the program while it runs, which is the empirical method, or count on paper, which is the analytical method. Today we’ll do both.

How do you measure the memory an algorithm uses?

Let’s add up the numbers from 1 to n in two ways. The first keeps all the numbers in a list and then adds them. The second adds as it goes and keeps only the total. Both give the same answer, and both are O(n) in time, because they go through every number. The difference is in memory.

Each language measures it in its own way. In Python, the tracemalloc module records the highest memory usage during the call. In PHP, the memory_get_peak_usage function returns that peak, and memory_reset_peak_usage resets the peak between one measurement and the next. In C, you are the one who asks for memory, with malloc, so the count is exact. Here is the code (click the tabs):

import tracemalloc


def sum_with_list(n):
    numbers = list(range(1, n + 1))  # keeps all n numbers before adding them up
    return sum(numbers)


def sum_accumulating(n):
    total = 0
    for i in range(1, n + 1):
        total += i  # keeps only the running total
    return total


def peak_memory(function, n):
    tracemalloc.start()
    function(n)
    _, peak = tracemalloc.get_traced_memory()  # the highest usage during the call
    tracemalloc.stop()
    return peak


print(f"{'n':>9} {'with list':>10} {'accumulating':>12}")
for n in (1_000, 10_000, 100_000, 1_000_000):
    print(f"{n:>9} {peak_memory(sum_with_list, n):>10} {peak_memory(sum_accumulating, n):>12}")
<?php

function sumWithList(int $n): int
{
    $numbers = range(1, $n); // keeps all n numbers before adding them up
    return array_sum($numbers);
}

function sumAccumulating(int $n): int
{
    $total = 0;
    for ($i = 1; $i <= $n; $i++) {
        $total += $i; // keeps only the running total
    }
    return $total;
}

function peakMemory(callable $function, int $n): int
{
    memory_reset_peak_usage();
    $before = memory_get_usage();
    $function($n);
    return memory_get_peak_usage() - $before; // the highest usage during the call
}

printf("%9s %10s %12s\n", 'n', 'with list', 'accumulating');
foreach ([1_000, 10_000, 100_000, 1_000_000] as $n) {
    printf("%9d %10d %12d\n", $n, peakMemory('sumWithList', $n), peakMemory('sumAccumulating', $n));
}
#include <stdio.h>
#include <stdlib.h>

long long sum_with_array(int n, size_t *bytes) {
    int *numbers = malloc(n * sizeof(int)); // keeps all n numbers before adding them up
    long long total = 0;

    if (numbers == NULL) {
        *bytes = 0;
        return -1; // out of memory
    }
    for (int i = 0; i < n; i++) {
        numbers[i] = i + 1;
    }
    for (int i = 0; i < n; i++) {
        total += numbers[i];
    }
    *bytes = n * sizeof(int); // what was requested from malloc
    free(numbers);
    return total;
}

long long sum_accumulating(int n, size_t *bytes) {
    long long total = 0;

    for (int i = 1; i <= n; i++) {
        total += i; // keeps only the running total
    }
    *bytes = 0; // nothing requested from malloc: only local variables
    return total;
}

int main(void) {
    int sizes[] = {1000, 10000, 100000, 1000000};

    printf("%9s %10s %12s\n", "n", "with array", "accumulating");
    for (int i = 0; i < 4; i++) {
        size_t with_array, accumulating;
        sum_with_array(sizes[i], &with_array);
        sum_accumulating(sizes[i], &accumulating);
        printf("%9d %10zu %12zu\n", sizes[i], with_array, accumulating);
    }
    return 0;
}

And the outputs, in bytes:

        n  with list accumulating
     1000      32016          152
    10000     392016          152
   100000    3992016          152
  1000000   39992016          152
        n  with list accumulating
     1000      20536           40
    10000     266296           40
   100000    2101328           40
  1000000   16781392           40
        n with array accumulating
     1000       4000            0
    10000      40000            0
   100000     400000            0
  1000000    4000000            0

The numbers change from one language to another, because each one stores a number in its own way: in Python it’s about 40 bytes per number, in PHP 16 to 20, and in C exactly 4. But the shape of the growth is the same in all three. The list column grows with n: ten times the n, ten times the memory. The accumulator column doesn’t move. Focus on the concept, not the language!

In Big O notation, the sum with a list is O(n) space, and the accumulating sum is O(1) space, that is, constant memory. Same time, very different memory. Got it?

Does recursion use memory too?

It does, and a lot of people forget it. Remember the call stack? Every call that hasn’t finished yet stays stored in it, with its variables, waiting for the answer from the next call. A recursive sum from 1 to n leaves n calls stacked at the same time. It is O(n) space, even without creating any list. See it in Python:

import sys


def recursive_sum(n):
    if n == 0:
        return 0
    return n + recursive_sum(n - 1)  # each call waits for the next one on the stack


def loop_sum(n):
    total = 0
    for i in range(1, n + 1):
        total += i
    return total


print("limit of stacked calls:", sys.getrecursionlimit())
print("loop with 100000:", loop_sum(100_000))
print("recursion with 900:", recursive_sum(900))
print("recursion with 100000:", recursive_sum(100_000))

Output (I cut the repeated lines of the error in the middle):

limit of stacked calls: 1000
loop with 100000: 5000050000
recursion with 900: 405450
Traceback (most recent call last):
[...]
RecursionError: maximum recursion depth exceeded

Python has a limit on stacked calls, which here is 1,000. The documentation explains why: the limit keeps an infinite recursion from overflowing the C stack and crashing Python itself. With 900 calls, the recursion works. With 100,000, it hits the limit, while the loop adds the same numbers with no trouble at all.

In PHP, that limit doesn’t show up, but memory pays the bill. I measured the memory peak of both versions:

<?php

function recursiveSum(int $n): int
{
    if ($n === 0) {
        return 0;
    }
    return $n + recursiveSum($n - 1); // each call waits for the next one on the stack
}

function loopSum(int $n): int
{
    $total = 0;
    for ($i = 1; $i <= $n; $i++) {
        $total += $i;
    }
    return $total;
}

function peakMemory(callable $function, int $n): int
{
    memory_reset_peak_usage();
    $before = memory_get_usage();
    $function($n);
    return memory_get_peak_usage() - $before;
}

printf("%9s %10s %6s\n", 'n', 'recursion', 'loop');
foreach ([10_000, 100_000, 1_000_000] as $n) {
    printf("%9d %10d %6d\n", $n, peakMemory('recursiveSum', $n), peakMemory('loopSum', $n));
}

Output, in bytes:

        n  recursion   loop
    10000    1572864     32
   100000   15990784     32
  1000000  159907840     32

The recursion uses about 160 bytes per stacked call: with 1 million calls, almost 160 MB. The loop stays at the same 32 bytes. And here comes the catch: PHP’s default memory limit is 128 MB. Running with that limit, the million row never even shows up:

        n  recursion   loop
    10000    1572864     32
   100000   15990784     32
PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 2097152 bytes)

Can you trade memory for time?

You can, and that is exactly what you did with the times table. The classic example is the Fibonacci sequence, in which each number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13 and so on. The direct recursive version is beautiful, but it computes the same thing several times. fib(5) calls fib(3) twice, fib(2) three times and fib(1) five times:

Two call trees of fib(5). On the left, without notes, 15 calls, with the repeated ones in beige: fib(3) appears twice, fib(2) three times and fib(1) five times. On the right, with notes, 9 calls: the repetitions become lookups, drawn with a dashed border
The call tree of fib(5): without notes, 15 calls; with notes, 9.

The way out is to write down each result the first time and, from then on, just look it up. This technique is called memoization (yes, with no r). Here are three versions, counting the calls (click the tabs):

calls = 0


def fib(n):
    global calls
    calls += 1
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)  # computes again what it already computed


def fib_with_notes(n, notes):
    global calls
    calls += 1
    if n in notes:
        return notes[n]  # already computed: just look it up
    notes[n] = n if n < 2 else fib_with_notes(n - 1, notes) + fib_with_notes(n - 2, notes)
    return notes[n]


def fib_with_loop(n):
    previous, current = 0, 1
    for _ in range(n):
        previous, current = current, previous + current  # keeps only the last two
    return previous


print(f"{'n':>3} {'result':>9} {'no notes':>9} {'with notes':>10}")
for n in (10, 20, 30):
    calls = 0
    result = fib(n)
    no_notes = calls
    calls = 0
    fib_with_notes(n, {})
    print(f"{n:>3} {result:>9} {no_notes:>9} {calls:>10}")
print("with a loop, fib(90) =", fib_with_loop(90))
<?php

$calls = 0;

function fib(int $n): int
{
    global $calls;
    $calls++;
    if ($n < 2) {
        return $n;
    }
    return fib($n - 1) + fib($n - 2); // computes again what it already computed
}

function fibWithNotes(int $n, array &$notes): int
{
    global $calls;
    $calls++;
    if (isset($notes[$n])) {
        return $notes[$n]; // already computed: just look it up
    }
    $notes[$n] = $n < 2 ? $n : fibWithNotes($n - 1, $notes) + fibWithNotes($n - 2, $notes);
    return $notes[$n];
}

function fibWithLoop(int $n): int
{
    [$previous, $current] = [0, 1];
    for ($i = 0; $i < $n; $i++) {
        [$previous, $current] = [$current, $previous + $current]; // keeps only the last two
    }
    return $previous;
}

printf("%3s %9s %9s %10s\n", 'n', 'result', 'no notes', 'with notes');
foreach ([10, 20, 30] as $n) {
    $calls = 0;
    $result = fib($n);
    $noNotes = $calls;
    $calls = 0;
    $notes = [];
    fibWithNotes($n, $notes);
    printf("%3d %9d %9d %10d\n", $n, $result, $noNotes, $calls);
}
echo 'with a loop, fib(90) = ', fibWithLoop(90), PHP_EOL;
#include <stdio.h>

long long calls = 0;

long long fib(int n) {
    calls++;
    if (n < 2) {
        return n;
    }
    return fib(n - 1) + fib(n - 2); // computes again what it already computed
}

long long fib_with_notes(int n, long long notes[]) {
    calls++;
    if (notes[n] != -1) {
        return notes[n]; // already computed: just look it up
    }
    notes[n] = n < 2 ? n : fib_with_notes(n - 1, notes) + fib_with_notes(n - 2, notes);
    return notes[n];
}

long long fib_with_loop(int n) {
    long long previous = 0, current = 1;

    for (int i = 0; i < n; i++) {
        long long next = previous + current; // keeps only the last two
        previous = current;
        current = next;
    }
    return previous;
}

int main(void) {
    int sizes[] = {10, 20, 30};

    printf("%3s %9s %9s %10s\n", "n", "result", "no notes", "with notes");
    for (int i = 0; i < 3; i++) {
        int n = sizes[i];
        long long notes[31];

        for (int j = 0; j <= 30; j++) {
            notes[j] = -1; // -1: not computed yet
        }
        calls = 0;
        long long result = fib(n);
        long long no_notes = calls;
        calls = 0;
        fib_with_notes(n, notes);
        printf("%3d %9lld %9lld %10lld\n", n, result, no_notes, calls);
    }
    printf("with a loop, fib(90) = %lld\n", fib_with_loop(90));
    return 0;
}

The output is the same in all three languages:

  n    result  no notes with notes
 10        55       177         19
 20      6765     21891         39
 30    832040   2692537         59
with a loop, fib(90) = 2880067194370816120

Look at the third column. Without notes, fib(30) makes 2,692,537 calls: they grow exponentially. With notes, there are 59, that is, 2n − 1. The time dropped from exponential to O(n). And the price? The saved values, n + 1 numbers stored: O(n) space. The stack also reaches n levels.

Watch fib(5) with notes, step by step
Animation of fib(5) with memoization: the calls fib(5), fib(4), fib(3), fib(2) and fib(1) pile up on the stack, the results are saved in a row from fib(0) to fib(5), and the repeated calls just look up the saved value, until the result 5 with 9 calls
The call stack and the saved values: each value is computed once and then only looked up.

And the loop version? It keeps only the last two numbers and computes fib(90) without saving anything: O(n) time and O(1) space. The Princeton recursion materials follow exactly this path: from the exponential waste of the plain recursion to memoization and then to the bottom-up version.

VersionTimeExtra space
Recursive, no notesExponentialO(n): the call stack
Recursive, with notesO(n)O(n): the stack and the saved values
With a loopO(n)O(1): only the last two numbers
The three Fibonacci versions: same answer, different costs.

In Python, you don’t even need to write the note-taker by hand: functools.cache does it for you, and the documentation itself says it is sometimes called memoize. But pay attention to a detail that is right there: it has no size limit, and everything it saves stays in memory.

Now you ask: what matters more, time or memory?

The Princeton analysis of algorithms slides start with two questions: why is my program so slow? Why does it run out of memory? The honest answer is that it depends on which of the two you’re short of haha. A few rules help:

  • If the time is the same, keep the version that uses less memory. The two sums at the beginning are O(n) in time. There’s no reason to keep a million numbers just to add them up.
  • If the repeated work is large, taking notes pays off. In Fibonacci, keeping 31 values cut 2.6 million calls down to 59.
  • Be wary of deep recursion. Every stacked call costs memory. For a large n, a loop is usually safer, as you saw in Python and PHP.
  • Memory runs out too. A program that runs out of memory doesn’t just get slow: it stops, like PHP with the 128 MB limit.

What are the most common mistakes?

  • Counting the input as the algorithm’s cost. What you measure is the auxiliary space, what it creates beyond the input.
  • Forgetting the call stack. A recursion that creates no list is still O(n) space when it stacks n calls.
  • Measuring only once. A single number says nothing. Measure with n, 10n and 100n and look at the shape of the growth, like in the tables in this article.

Now it’s your turn!

On paper, give the time complexity and the extra space complexity of each of these functions:

  • A function that adds up the elements of a list with a loop.
  • A function that returns a new list with each element doubled.
  • The recursive factorial from the recursion article.
  • Binary search written with a loop.
  • Binary search written with recursion.

Try it on your own first, without asking anyone for the ready-made answer, not even AI! Then check:

See the answers
  1. O(n) time and O(1) space: only the total is kept.
  2. O(n) time and O(n) space: the new list has n elements.
  3. O(n) time and O(n) space: there are n stacked calls.
  4. O(log n) time and O(1) space: only the start, end and middle indexes.
  5. O(log n) time and O(log n) space: each call stacks the next one, and there are log n calls.

See you in the next article!

Stay confident!!!

Sources:

  • Cornell University, CS 2110. Lecture 6: Recursion, with space complexity as the most memory needed at any point during a method’s execution, beyond the memory for its parameters, and the depth of the call stack used to compute it.
  • Johns Hopkins University, CS 226 Data Structures. Space Complexity, with auxiliary space as the extra or temporary space an algorithm uses, apart from the input space.
  • Real Python. Space complexity, with the input space and the auxiliary space, memoization that saves time at the cost of memory and deep recursion that uses stack space.
  • Princeton University, Robert Sedgewick and Kevin Wayne. COS 226: Analysis of Algorithms, with the experimental and the mathematical analysis of running time and the analysis of memory consumption.
  • Princeton University, Introduction to Programming in Java. 2.3 Recursion, with the exponential waste of the recursive Fibonacci and the top-down and bottom-up dynamic programming that avoid it.
  • Princeton University, Robert Sedgewick and Kevin Wayne. Dynamic Programming, with top-down dynamic programming, also known as memoization because it remembers the results of function calls.
  • University of Washington, CSE 421. Dynamic Programming, I: Fibonacci, with the many duplicate calls that make the recursive Fibonacci take exponential time and memoization, which saves the answers of the recursive calls.
  • Python documentation. tracemalloc, with get_traced_memory, which returns the current size and the peak of the traced memory.
  • Python documentation. sys, with getrecursionlimit and the limit that keeps an infinite recursion from overflowing the C stack and crashing Python.
  • Python documentation. functools, with cache, sometimes called memoize, which has no size limit.
  • PHP Manual. memory_get_peak_usage, which returns the peak of memory allocated to the script.
  • PHP Manual. memory_reset_peak_usage, which resets the peak memory usage, available since PHP 8.2.
  • PHP Manual. Description of core php.ini directives, with memory_limit and its default value of 128M.
  • The examples were run on Python 3.13, PHP 8.3 and GCC 13. The C program also went through Valgrind, with no memory leaks.

Share this article

About the author

Walmir Silva

Hi! I'm Walmir, a software engineer with an MBA in Software Engineering, the mind behind GrowthCode and the author of the book "Além do Código" (in Portuguese).

If you think programming is just about writing code, get ready to broaden your horizons. Here, we go beyond the code and explore the fascinating intersections between technology, business, the arts and philosophy.

Are you looking for career growth? Do you want to stand out in a competitive market? Are you after a life richer in knowledge and fulfillment? Then you've come to the right place. At GrowthCode, we offer deep insights, proven strategies and a touch of philosophical wisdom to fuel your personal and professional growth.

See all articles →

Continue the conversation

Share your perspective

Your email address will not be published. Required fields are marked *

We keep the IP address and browser of commenters for 6 months, to block spam and because Brazil’s Marco Civil da Internet requires access records to be kept for that period. See how we handle your data (in Portuguese).

Find your next answer

What do you want to learn?

Cookie preferences

Optional cookies start off. You can change your choice at any time on this screen.

NecessaryAlways on

They store your cookie choice and its record code, and keep the site working. They are not used for advertising.

They count visits and show how the site is used: Google Analytics and Microsoft Clarity, loaded by Google Tag Manager.

They show Google AdSense ads without personalization. The cookies in this category limit how often ads repeat and measure their results.

Uses your browsing to choose ads and build ad audiences: Google ads chosen by your interests and Google signals in Analytics. When off, ads are shown without personalization. Requires Advertising.

You can also block cookies in your browser settings. Details in the Privacy policy (in Portuguese).