← All lessons
How Big O notation works
Count the steps for one n
O(1)
O(log n)
O(n)
O(n log n)
O(n²)
shapes.js
function first(arr) { return arr[0]; // one step, no matter how big arr is} function halvings(n) { let steps = 0; for (let m = n; m > 1; m = Math.floor(m / 2)) steps++; return steps; // n halves each time} function sum(arr) { let total = 0; for (const x of arr) total += x; // each item once return total;} function rounds(arr) { // log n rounds for each item for (const x of arr) { for (let j = 1; j < arr.length; j *= 2) {} }} function allPairs(arr) { for (const a of arr) { for (const b of arr) {} // every item against every item }}Slide n up and watch the gap open
steps, log scale at about 10⁹ steps per second
O(1)
O(log n)
O(n)
O(n log n)
O(n²)
estimate.js
// about a billion simple steps per secondconst STEPS_PER_SECOND = 1e9; const steps = { "O(1)": 1, "O(log n)": Math.floor(Math.log2(n)), "O(n)": n, "O(n log n)": n * Math.ceil(Math.log2(n)), "O(n²)": n * n,};const seconds = steps[shape] / STEPS_PER_SECOND;Measure real code the ratio that stays flat is the class
Run at n, then at 2n
steps countedsteps ÷ nsteps ÷ n²
Big O drops constants and smaller terms: 2n and n + 5 are both O(n)
scan.js
// duplicates? compare every pair oncefor (let i = 0; i < arr.length; i++) for (let j = i + 1; j < arr.length; j++) if (arr[i] === arr[j]) return true; // min, then max: two loops in a rowfor (const x of arr) min = Math.min(min, x);for (const x of arr) max = Math.max(max, x); // duplicates? one pass with a Setconst seen = new Set();for (const x of arr) { if (seen.has(x)) return true; seen.add(x);}Topics
Next: How recursion works
Open lesson