Skip to content

Algorithms & Scaling

The Course
•
20 min study

Big-O, defined with an example below, describes how work grows with input size, not exact milliseconds. Checking every candidate against every allowed value with repeated linear searches can do roughly n*m comparisons. Building a Set once provides efficient membership queries in typical implementations, with a cost for building and retaining the index.

Choose an algorithm only after preserving behavior. Sets use SameValueZero equality: object keys compare by identity, and NaN can match NaN. If your old logic used normalized string comparison, normalize before building the set. Otherwise a faster implementation can quietly change the contract.

For small lists, setup overhead may dominate; do not conclude that every includes call needs a Set. The relevant question is whether repeated membership queries justify an index. The example uses controlled primitive IDs and preserves candidate order.

Predict, run, and explain

Write the output and trace the important state changes before checking it. Then run the program. Each editor is independent. Async examples end with main() so this editor waits for their work.

Predict, then run JavaScript
const allowed = new Set(["a", "c"]);
const candidates = ["c", "b", "a"];

console.log(candidates.filter(id => allowed.has(id)).join(","));
console.log(allowed.size);
Check your prediction
Text
c,a
2

Count the steps instead of timing them

Big-O notation names how the amount of work grows as the input grows, ignoring constant factors. O(n) means "doubling the input roughly doubles the work". O(n²) means "doubling the input roughly quadruples it". It says nothing about milliseconds on your machine, which is why counting steps is a better way to see it than timing.

Both functions below keep the candidates that appear in an allowed list. The first does what allowedIds.includes(id) does internally, but counts each comparison. The second builds a Set first and counts insertions and lookups. Half of the candidates are allowed. Predict roughly how each count changes when the size goes from 100 to 1,000.

Count the work at two sizes JavaScript
function selectWithIncludes(candidates, allowedIds, counter) {
  return candidates.filter(id => {
    for (const allowed of allowedIds) {
      counter.steps += 1; // one comparison
      if (allowed === id) return true;
    }
    return false;
  });
}

function selectWithSet(candidates, allowedIds, counter) {
  const allowed = new Set();
  for (const id of allowedIds) {
    counter.steps += 1; // one insertion
    allowed.add(id);
  }
  return candidates.filter(id => {
    counter.steps += 1; // one lookup
    return allowed.has(id);
  });
}

for (const size of [100, 1000]) {
  const allowedIds = Array.from({ length: size }, (_, i) => `id${i * 2}`);
  const candidates = Array.from({ length: size }, (_, i) => `id${i}`);

  const slow = { steps: 0 };
  const fast = { steps: 0 };
  const a = selectWithIncludes(candidates, allowedIds, slow);
  const b = selectWithSet(candidates, allowedIds, fast);

  console.log(
    `n=${size}: same result ${a.join() === b.join()}, includes ${slow.steps} steps, Set ${fast.steps} steps`
  );
}
Check your prediction
Text
n=100: same result true, includes 6275 steps, Set 200 steps
n=1000: same result true, includes 625250 steps, Set 2000 steps

Multiplying the size by 10 multiplied the includes-style work by about 100 (from 6,275 to 625,250 comparisons), because each of n candidates may scan up to n allowed ids: roughly n × n. The Set version did one insertion per allowed id and one lookup per candidate, 2n steps, so it grew by exactly 10. In Big-O notation the first is O(n²) and the second O(n). (A Set lookup is not literally one machine step, but its cost does not grow with the number of entries in typical engines, which is what counting it as one step assumes.) At n = 100 both are fast in practice; the gap only matters because it keeps widening.

Separate membership indexing from deduplication

A membership index accelerates repeated questions about allowed ids. It need not remove duplicates from the candidate sequence. Changing which side is iterated can alter both order and repeated values even when every returned id is allowed.

Account for index construction and retained memory as well as lookup work. A one-off query on a tiny list may not justify building a Set. Use growth and repeated-query behavior to decide, rather than treating a particular collection as universally faster.

Separate membership indexing from deduplication: trace JavaScript
const allowed = new Set(["a", "b"]);
const candidates = ["b", "a", "b", "c"];

console.log(candidates.filter(id => allowed.has(id)).join(","));
console.log([...new Set(candidates)].filter(id => allowed.has(id)).join(","));
Check your prediction
Text
b,a,b
b,a

The second variant deduplicates candidates, changing the contract. It is not simply a faster implementation of the first if repeated candidates are meaningful.

Separate membership indexing from deduplication: contrast JavaScript
const first = { id: "a" };
const second = { id: "a" };
const objects = new Set([first]);
const ids = new Set([first.id]);

console.log(objects.has(second));
console.log(ids.has(second.id));
Check your prediction
Text
false
true

Object membership uses identity; id membership uses the domain key. An optimization that switches representation must preserve the comparison semantics the original behavior required.

Try the rule on new inputs

Test candidate order, duplicate candidates, empty allowed sets and normalized ids. Describe repeated linear searches in terms of candidate count and allowed count before measuring a particular machine.

Trace the contract before building

Growth analysis asks how work changes as input grows. Repeating a full scan for every item can become quadratic even when one tiny example feels immediate. Counting comparisons or source pulls makes that structure visible without relying on timing noise.

Include preparation and maintenance when evaluating an index or cache. Building another structure consumes memory and creates consistency obligations on update. Start with a correct simple implementation, identify the repeated operation, then justify a different data structure against the actual workload. Keep independent result and ownership tests when changing the algorithm.

Your turn

Exercise

A pair sum in one pass

hasPairNested(numbers, target, counter) is supplied: it answers "do two different positions add up to target?" by checking every pair, and counts each check. Write hasPairSet with the same answers in one pass, counting one step per number examined. The test runs both at two sizes, with a target that has no pair (1) and one whose only pair is the last two numbers. It also checks that a number cannot pair with itself. Print:

Text
n=200 target 1: false | nested 19900 | Set 200
n=200 target 1191: true | nested 19900 | Set 200
n=2000 target 1: false | nested 1999000 | Set 2000
n=2000 target 11991: true | nested 1999000 | Set 2000
false true
Your workspace JavaScript
function hasPairNested(numbers, target, counter) {
  for (let i = 0; i < numbers.length; i++) {
    for (let j = i + 1; j < numbers.length; j++) {
      counter.steps += 1;
      if (numbers[i] + numbers[j] === target) return true;
    }
  }
  return false;
}

function hasPairSet(numbers, target, counter) {
  // One pass: for each n, check whether target - n was seen earlier,
  // then remember n. Add 1 to counter.steps per number examined.
  return false;
}

for (const size of [200, 2000]) {
  const numbers = Array.from({ length: size }, (_, i) => i * 3); // multiples of 3
  for (const target of [1, 3 * (size - 1) + 3 * (size - 2)]) {
    const slow = { steps: 0 };
    const fast = { steps: 0 };
    const a = hasPairNested(numbers, target, slow);
    const b = hasPairSet(numbers, target, fast);
    console.log(`n=${size} target ${target}: ${a === b ? a : "MISMATCH"} | nested ${slow.steps} | Set ${fast.steps}`);
  }
}

console.log(hasPairSet([5], 10, { steps: 0 }), hasPairSet([5, 5], 10, { steps: 0 }));
Hint 1: the idea

For each number n, the partner it needs is target - n. If you remember every number you have already passed in a Set, then "has my partner appeared before me?" is one lookup instead of a scan.

Hint 2: a first step

Loop over numbers once with a seen Set. Inside, first check seen.has(target - n) and return true if so, and only then seen.add(n). Run it and compare the Set step counts at the two sizes before looking at the last line.

Show one solution
JavaScript
function hasPairNested(numbers, target, counter) {
  for (let i = 0; i < numbers.length; i++) {
    for (let j = i + 1; j < numbers.length; j++) {
      counter.steps += 1;
      if (numbers[i] + numbers[j] === target) return true;
    }
  }
  return false;
}

function hasPairSet(numbers, target, counter) {
  const seen = new Set();
  for (const n of numbers) {
    counter.steps += 1;
    if (seen.has(target - n)) return true;
    seen.add(n);
  }
  return false;
}

for (const size of [200, 2000]) {
  const numbers = Array.from({ length: size }, (_, i) => i * 3); // multiples of 3
  for (const target of [1, 3 * (size - 1) + 3 * (size - 2)]) {
    const slow = { steps: 0 };
    const fast = { steps: 0 };
    const a = hasPairNested(numbers, target, slow);
    const b = hasPairSet(numbers, target, fast);
    console.log(`n=${size} target ${target}: ${a === b ? a : "MISMATCH"} | nested ${slow.steps} | Set ${fast.steps}`);
  }
}

console.log(hasPairSet([5], 10, { steps: 0 }), hasPairSet([5, 5], 10, { steps: 0 }));
Text
n=200 target 1: false | nested 19900 | Set 200
n=200 target 1191: true | nested 19900 | Set 200
n=2000 target 1: false | nested 1999000 | Set 2000
n=2000 target 11991: true | nested 1999000 | Set 2000
false true

Checking seen before adding n is what stops a number pairing with itself: [5] with target 10 is false, while [5, 5] is true because the second 5 finds the first. Both versions agree on every case, which is checked before any step count is read. The nested version's counts grow about 100-fold when n grows 10-fold (19,900 to 1,999,000), because it examines every pair: O(n²). The Set version examines each number once, so its counts grow 10-fold: O(n). The worst case for both is a target whose only pair comes last, so every number is examined.

Change it and test it

Test empty inputs, duplicate allowed IDs and duplicate candidates. Compare the result with a simple includes-based reference implementation across several small cases. Explain the index’s extra memory cost and why result order still follows candidates.

Was this article helpful?

Your response is saved on this device.