Data Structures & Algorithms / Module 0: Thinking in cost

Topic 0.5

Hidden costs

One line of code isn't always one step: the functions that quietly read a whole list, and how to spot them.

8 min · beginner

Watch: count the checks in the bottom-right corner. One line of code that looks simple turns out to check the whole list every time.

01234567resultabcadbef
  • being checked
  • finished / the result
  • no longer used
Step 1 of 10

For every item, check whether it is already in the result list with includes.

One line of code, includes, quietly checks the whole result every time it runs. A Set checks in one step.
check with:

Like asking the whole room "is this taken?"

Picture writing down guests' names with no duplicates. Each time a guest arrives, you reread the whole list from the top to make sure the name isn't there yet. Guest 10 takes 9 reads, guest 100 takes 99. The method looks simple, but the work balloons. Now picture a guest book that tells you "already here" at a glance. That is a Set.

In the figure, compare the check count in the bottom-right corner for both ways. Same result, different amount of work.

Code, for programmersLooks O(n), is really O(n²)
function unique(list) {
  const result = [];
  for (const x of list) {
    if (!result.includes(x)) result.push(x);   // includes reads all of result
  }
  return result;
}
Code, for programmersReally O(n)
function unique(list) {
  return [...new Set(list)];                    // each check is one step
}

Functions to be suspicious of

CodeWhat happens inside
list.includes / indexOf / findchecks item by item from the front
list.shift / unshiftmoves every other element
list.splice in the middlemoves every element after it
[...list] or list.slice()copies the whole list
str += x inside a loopcan build a new string each time (depends on the language)
await db.query inside a loopone trip to the database per iteration (N+1)

Quiz

  1. Code: for (const x of a) { if (b.includes(x)) count++ }. a and b each hold n items. What is its Big-O?

  2. How do you make the previous code O(n)?

  3. Why can queue.shift() inside a loop be slow?

0 of 3 answered.