Summary & Trade-offs — Algorithms

Every approach has a price: time or memory, and swapping one for the other is called a trade-off. Estimate the time first from n (the amount of data), with a…

Across this category you've met plenty of faster ways: binary search, O(n log n) sorts, two pointers, memoization. But the fast way usually has a price.

This closing lesson of the Algorithms category is about choosing. Every approach has a price, usually time (how long it runs) or memory (how much it has to keep). A trade-off means swapping one for the other, for example using more memory so the code runs far faster.

How big is your n?

Big-O describes how the number of steps of an approach grows as the amount of data (n) gets bigger. O(n): twice the data, roughly twice the time. O(n²), such as two nested loops (a loop inside a loop): twice the data, roughly four times the time. As a rough rule, a computer runs about 100 million simple operations a second. One simple operation is one small step, like comparing two numbers. This code uses that rule for 5,000 items:

const n = 5000;
const perSecond = 100000000; // a rough rule: simple operations per second

console.log(n * n); // 25000000 operations for O(n²)
console.log((n * n) / perSecond); // 0.25 seconds
console.log((n * Math.log2(n)) / perSecond); // about 0.0006 seconds for O(n log n)

With the same calculation, this table shows which Big-O still fits in about 1 second for each size of n:

n around What still fits Example
10 O(n!) trying every ordering (backtracking)
5,000 O(n²) two nested loops
100,000 O(n log n) sort first, then binary search or two pointer
1,000,000 O(n) or O(n log n) one walk through the array, for example with a hash map (Map or an object) or a sliding window
1,000,000,000 O(log n) binary search, or a formula

Trade memory for time

For example: find out whether an array has a repeated number (a duplicate), a number that appears more than once. Here are two ways, a slow one and a fast one:

function hasDuplicateSlow(arr) {
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] === arr[j]) return true;
    }
  }
  return false;
}

function hasDuplicateFast(arr) {
  const seen = new Set();
  for (const x of arr) {
    if (seen.has(x)) return true;
    seen.add(x);
  }
  return false;
}

console.log(hasDuplicateSlow([3, 1, 4, 1])); // true
console.log(hasDuplicateFast([3, 1, 4, 1])); // true

A hash map uses the same trick, for example to find two numbers that add up to a target. Keep the numbers you've seen, and for each new number, check whether its partner is already stored. For n = 100,000, O(n²) means about 10 billion operations (over a minute), while O(n) is only 100,000. Memoization from the Memoization & Dynamic Programming lesson uses the same idea: keep results so they aren't calculated again.

When slow is the right choice

For 50 numbers, two nested loops take just 2,500 operations, done in a moment. Your data is only 50 numbers and the code runs once a day? There's no need to replace it with something cleverer. The simple version is easier to read, and it is less likely to have a bug (a mistake in the code).

A slower approach is also right when memory is tight. For example, to find a repeated number: sort the array with heap sort, then compare neighbouring numbers, because after sorting, repeated numbers are always side by side. This takes O(n log n) time, but doesn't need to keep a copy of every number the way a Set does.

The order is always the same:

  1. First write the simplest approach that's correct.
  2. Estimate its number of operations from n.
  3. Only look for something faster when the estimated time is too long.

A map of this category's techniques

This table matches the kind of task to a technique from this category:

When the task is about Try
searching sorted data binary search
pairs in a sorted array two pointer
a group of side-by-side numbers sliding window
"have I seen this before?" or counting a hash map or a Set
the same small calculation repeated again and again memoization and DP
a best-right-now choice that's proven right greedy
every arrangement, with a small n backtracking
shortest paths with weights Dijkstra
an order with dependencies topological sort

⚠️ Before you call your code fast enough

TL;DR: Every approach has a price: time or memory, and swapping one for the other is called a trade-off. Estimate the time first from n (the amount of data), with a rough rule of 100 million operations a second. 5,000 items are still fine for O(n²), and 1,000,000 needs O(n) or O(n log n). A Set or a hash map (Map or an object) trades O(n) memory for time: finding duplicates (repeated numbers) or two numbers with a given sum becomes O(n) instead of O(n²). When the data is small or memory is tight, the simple, slower approach is the right choice.

⚡ How big is your n?

Write:

const n = 5000;
const perSecond = 100000000; // a rough rule: simple operations per second

console.log(n * n); // 25000000 operations for O(n²)
console.log((n * n) / perSecond); // 0.25 seconds

Meaning: n is the amount of data. As a rough rule, a computer runs about 100 million simple operations a second (perSecond). 5,000 items with O(n²) means 5,000 × 5,000 = 25 million operations, about a quarter of a second: still fine.

⚡ Trade memory for time

Write:

function hasDuplicateFast(arr) {
  const seen = new Set();
  for (const x of arr) {
    if (seen.has(x)) return true;
    seen.add(x);
  }
  return false;
}
Guess first: finding a repeated number with two nested loops (a loop inside a loop, O(n²)) takes about 10 billion operations for n = 100,000. With a Set or a hash map, how many are left?

Only about 100,000, so O(n). The price is O(n) memory, since the Set may have to hold every number.

Meaning: hasDuplicateFast checks whether an array has a repeated number. seen is a Set (a collection with no repeats) that remembers the numbers already seen. has checks whether a number is already there, and takes about one step on average. Memoization from the Memoization & Dynamic Programming lesson uses the same idea: keep results so they aren't calculated again.

⚡ When slow is the right choice

Meaning: 50 numbers with two nested loops take just 2,500 operations, done in a moment. First write the simplest approach that's correct, then estimate its number of operations from n. Only look for something faster when the estimated time is too long.

What you will learn