Data Structures & Algorithms / Module 0: Thinking in cost

Topic 0.4

Space complexity

Algorithms don't only need time, they also need room, and often one can be traded for the other.

7 min · beginner

Watch: compare two ways of reversing a row: one builds a second row, the other just swaps within the same row.

01234561234567
  • moving now
  • being checked
  • finished / the result
  • no longer used
Step 1 of 9

Make a new list as long as the original, then fill it from the back.

Both ways give the same order. The copy needs as much room as the data; swapping needs just one temporary slot.
way:

Like reversing the books on a shelf

There are two ways to reverse the books on a shelf:

  • Use a second shelf. Take books from the right end one by one and line them up on an empty shelf. Easy, but you need a second shelf as long as the first.
  • Swap in place. Swap the leftmost book with the rightmost, then the second with the second from the right, and so on until you meet in the middle. You only need one free hand to hold a book for a moment.

Try both in the figure and watch the "extra memory" number in the bottom-right corner.

Space complexity

The second-shelf way needs as much room as there are books: O(n) extra memory. Swapping needs one temporary slot, however many books there are: O(1). Both take O(n) time, because every book still gets touched.

Code, for programmersTwo ways to reverse a list
// A copy: easy to read, uses O(n) extra memory
const reversed = [...list].reverse();

// In place: O(1) extra memory, but it changes the original list
function reverseInPlace(list) {
  for (let lo = 0, hi = list.length - 1; lo < hi; lo++, hi--) {
    [list[lo], list[hi]] = [list[hi], list[lo]];
  }
}

Trading time for memory

Many tricks that speed programs up work by using more memory. Keeping results you already worked out (a cache) makes the next lookup instant, but needs room to keep them. Building a Set from a list costs O(n) memory, but every check after that is instant. Which choice is right depends on which is scarcer: time or memory.

Quiz

  1. Reversing a list of 1,000 numbers by making a copy. How much extra memory?

  2. Reversing a list by swapping its ends. How much extra memory?

  3. Building a Set from a list so later checks are fast is an example of…

0 of 3 answered.