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.
Watch: compare two ways of reversing a row: one builds a second row, the other just swaps within the same row.
- moving now
- being checked
- finished / the result
- no longer used
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
Reversing a list of 1,000 numbers by making a copy. How much extra memory?
Reversing a list by swapping its ends. How much extra memory?
Building a Set from a list so later checks are fast is an example of…
0 of 3 answered.
Built on
Used in
No follow-up topics yet.