In a code review (a teammate checking your code), the teammate says, "This function is O(n²), change it." You look at the code: there are two loops, but one after the other, not one inside the other. Is your teammate right? This lesson gives you the way to answer that.
Estimating how quickly code slows down as its data grows is called complexity analysis. The result is written in Big-O, with n as the amount of data. This closing lesson gives you a quick table of what each data structure costs, then shows how to read your own function and estimate its Big-O.
Quick table: what each operation costs
This code reads the last item of an array by its index, then searches for -1, a number that isn't there, in the same 1,000 numbers: once in the array, once in a Set.
const n = 1000;
const arr = Array.from({ length: n }, (_, i) => i); // 0 to 999
const set = new Set(arr);
console.log(arr[n - 1]); // 999, O(1): straight to its index
console.log(arr.includes(-1)); // false, O(n): 1,000 items checked one by one
console.log(set.has(-1)); // false, O(1) on average
Same data, but very different costs to search it. Here's what each operation costs in each structure:
| Structure | Access (index) | Search | Insert | Delete |
|---|---|---|---|---|
| Array | O(1) | O(n) | O(n) | O(n) |
| Stack | O(n) | O(n) | O(1) | O(1) |
| Queue | O(n) | O(n) | O(1) | O(1) |
| Linked list | O(n) | O(n) | O(1) | O(1) |
| Hash map | none | O(1)* | O(1)* | O(1)* |
| BST | none | O(log n)* | O(log n)* | O(log n)* |
| Heap | none | O(n) | O(log n) | O(log n) |
- The * means on average. The worst case is O(n): a hash map where many keys collide (land in the same bucket), or a BST that isn't balanced.
- Inserting and deleting in an array is O(n), because the other items have to shift. At the end of the array (
push,pop) it's only O(1). - O(1) inserts and deletes in a linked list apply at a node you already hold, such as the head.
How big the difference is for n = 1,000: O(1) is one step, O(log n) about 10, O(n) 1,000, O(n log n) about 10,000, and O(n²) a million.
One loop: O(n)
For your own function, ask: as n grows, how many times does the line inside the loop run? Take the function total, which adds up the items of an array:
function total(arr) {
let sum = 0;
for (const x of arr) {
sum += x;
}
return sum;
}
console.log(total([5, 10, 15])); // 30
The loop runs once for each item: n items, n passes. Twice the items, twice the passes: O(n). The lines outside the loop (let sum = 0, return) run only once, so they don't count.
A loop inside a loop: O(n²)
The function countPairs counts the pairs of items in an array with a loop inside a loop:
function countPairs(arr) {
let pairs = 0;
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
pairs++;
}
}
return pairs;
}
console.log(countPairs([1, 2, 3, 4])); // 6
For each i, the inner loop runs from i + 1 to the end of the array. With 4 items: 3 + 2 + 1 = 6 passes. With 1,000 items: 499,500, roughly n × n / 2. Big-O drops multipliers like "/ 2", so the result is O(n²): twice the items, roughly four times the time. An inner loop starting at i + 1, as here, or at 0 is O(n²) either way.
Halved every pass: O(log n)
Before you read the comments in this code, guess: what does doublingSteps(1000) return, about 10, 500 or 1,000?
function doublingSteps(n) {
let steps = 0;
for (let i = 1; i < n; i *= 2) {
steps++;
}
return steps;
}
console.log(doublingSteps(8)); // 3
console.log(doublingSteps(1000)); // 10
i doubles every pass: 1, 2, 4, 8, ... For n = 8, i is 1, 2, 4, then the loop stops when i becomes 8: 3 passes. For n = 1,000 it's only 10 passes, and for a million only 20. Doubling i until it reaches n takes as many passes as halving n until 1 is left, which is log n. So when the loop counter doubles every pass, or the data that is left is halved every pass as in binary search, the Big-O is O(log n).
Putting it together: add, multiply, drop constants
- One after another: keep the biggest. One loop finishes, then another runs: n + n = 2n, still O(n). An O(n) loop followed by a nested loop (a loop inside a loop) that is O(n²): the result is O(n²).
- Nested: multiply. A loop that runs n times inside a loop that runs n times: n × n = O(n²).
- Built-in methods count too.
includes,indexOfandshiftwork on the array's items one at a time, so they're O(n). Oneincludesinside a loop is the same as a loop inside a loop: O(n²). - Drop fixed numbers. These fixed numbers are called constants. 3n becomes O(n), and n² / 2 becomes O(n²). A loop that always runs 10 times, whatever n is, is O(1).
⚠️ Miscounts that make your Big-O wrong
- Reading a starred O(1) as a promise. It's an average. A hash map and a BST can still be O(n) in the worst case.
- Counting two loops in a row as O(n²). Only a loop that sits inside another loop is O(n²).
- Treating Big-O as an exact time. Big-O is about large amounts of data. For a few dozen items, simple O(n²) code can be faster than complicated O(n log n) code.
TL;DR: Big-O says how fast the number of steps of the code grows as n (the amount of data) gets bigger. One loop over n items: O(n). A loop inside a loop: O(n²), even when the inner loop only starts after the outer loop's position (i + 1). A loop counter doubled, or data halved, every pass: O(log n), about 10 steps for 1,000 items. Loops in a row add up and you keep the biggest, nested loops (one inside another) multiply, fixed numbers are dropped, and methods like includes inside a loop count too. Array: access by index O(1), search O(n). Hash map and Set: search O(1) on average. Balanced BST: O(log n). Heap: insert and delete O(log n).
⚡ One loop: O(n)
Meaning: To estimate the Big-O of a function, ask this: as n (the amount of data) grows, how many times does the line inside the loop run? One loop over n items runs n times: twice the items, twice the passes. That's O(n). The lines outside the loop run only once, so they don't count.
⚡ A loop inside a loop: O(n²)
Write:
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
pairs++;
}
}
Meaning: This code counts the pairs of items in the array arr: for each i, the inner loop runs from i + 1 to the end. With 1,000 items, pairs++ runs 499,500 times, roughly n × n / 2. The "/ 2" is dropped, so it's O(n²). Two loops in a row that each run n times, not one inside the other, are still O(n).
⚡ Doubled every pass: O(log n)
Guess first: doublingSteps(n) counts the passes of a loop. The loop starts with i = 1, then doubles i every pass while i is still less than n. What does doublingSteps(1000) return, about 10, 500 or 1,000?
It returns 10. i is 1, 2, 4, ..., 512, then the loop stops when i becomes 1,024. Even a million takes only 20 passes.
Write:
for (let i = 1; i < n; i *= 2) {
steps++;
}
Meaning: When the loop counter doubles every pass, like i here, or the data that is left is halved every pass, like in binary search, the Big-O is O(log n). Watch out for methods like includes inside a loop too: includes checks the array's items one by one, so that's a loop inside a loop, O(n²).