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.
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.
- being checked
- finished / the result
- no longer used
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
| Code | What happens inside |
|---|---|
list.includes / indexOf / find | checks item by item from the front |
list.shift / unshift | moves every other element |
list.splice in the middle | moves every element after it |
[...list] or list.slice() | copies the whole list |
str += x inside a loop | can build a new string each time (depends on the language) |
await db.query inside a loop | one trip to the database per iteration (N+1) |
Quiz
Code: for (const x of a) { if (b.includes(x)) count++ }. a and b each hold n items. What is its Big-O?
How do you make the previous code O(n)?
Why can queue.shift() inside a loop be slow?
0 of 3 answered.