Learn / Lesson 8 of 10
Big O, in pictures
Measure how much slower a solution gets as the input grows.
Words on this page, in plain English (19)Open if any word is new to you
- Variable
- A labelled box that holds a value. You give it a name, put something in it, and use the name later to get it back.
- Boolean (true or false)
- A value that can only be
trueorfalse. Like a light switch: on or off. - Array (list)
- A list of values kept in order, inside square brackets. Like a row of numbered lockers.
- Length
- How many items a list (or letters a string) has. The last position is always
length - 1. - If (a decision)
- Runs some code only when something is true. Like: if it's raining, take an umbrella.
- Loop
- Code that repeats. A
forloop repeats once per item or a set number of times; awhileloop repeats as long as something stays true. - Function
- A named, reusable recipe. You give it ingredients (inputs), it does its steps, and hands back a result.
- Return
- How a function hands back its answer. As soon as
returnruns, the function stops. - console.log
- Prints something so you can see it. The easiest way to find out what your code is really doing.
- Map
- A lookup table: it stores pairs of a key and a value, and finds any key instantly. Like a coat check: hand over a ticket, get your coat straight back.
- Hash, hashing
- A quick calculation that turns a key into a shelf number, so a Map can jump straight to it instead of searching.
- Pattern
- A trick that solves a whole family of problems. Learn the trick once, and you can solve problems you've never seen.
- Big O
- A way to say how much slower code gets as the input grows. It's about the trend, not exact seconds.
- O(1): constant time
- Takes the same time no matter how big the input is. Like opening a book at page 1.
- O(log n): logarithmic time
- The work grows very slowly, because each step throws away half. A million items need only about 20 steps.
- O(n): linear time
- The work grows in step with the input: twice the items, twice the work. One pass.
- O(n²): quadratic time
- Twice the items means four times the work. Usually a loop inside a loop. Fine for 100 items, painful for 100,000.
- Sorted
- In order, smallest to biggest (or A to Z). Many fast tricks only work on sorted lists.
- Test
- An example input with the answer it should give. Your code passes if it gives that answer.
Correct isn't enough
Two programs can give the same right answer, but one takes a second and the other takes a week. Coding problems have hidden tests with huge inputs, and a slow solution gets stopped. So we need a way to talk about how much slower a solution gets as the input grows. That's what Big O describes.
Count the steps
Big O doesn't measure seconds (they depend on the computer). It counts steps, roughly, and asks: if the input gets twice as big, what happens to the number of steps?
Try it: counting steps
function stepsForOneLoop(n) {
let steps = 0;
for (let i = 0; i < n; i++) steps++;
return steps;
}
function stepsForTwoLoops(n) {
let steps = 0;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) steps++;
}
return steps;
}
for (const n of [10, 100, 1000]) {
console.log(n, "items:", stepsForOneLoop(n), "vs", stepsForTwoLoops(n));
}Press Run to see the output. You can change the code first.
One loop: 10 times more items, 10 times more steps. A loop inside a loop: 10 times more items, 100 times more steps.
The common shapes
| Big O | Name | Doubling the input… | Example |
|---|---|---|---|
| O(1) | constant | changes nothing | list[5], map.get(key) |
| O(log n) | logarithmic | adds one step | binary search |
| O(n) | linear | doubles the work | one loop over the list |
| O(n log n) | "n log n" | a bit more than doubles | sorting |
| O(n²) | quadratic | quadruples the work | a loop inside a loop |
| O(2ⁿ) | exponential | squares the work | trying every subset |
To feel the difference, here's roughly how many steps each takes for a million items:
| Big O | Steps for n = 1,000,000 |
|---|---|
| O(1) | 1 |
| O(log n) | 20 |
| O(n) | 1,000,000 |
| O(n log n) | 20,000,000 |
| O(n²) | 1,000,000,000,000 |
A computer does very roughly 100 million simple steps per second in JavaScript. So O(n) on a million items takes a hundredth of a second, and O(n²) takes hours.
How to work it out
- Find the loops. A loop over the input is O(n). A loop inside it, also over the input, makes O(n²).
- Look inside built-in methods.
includes,indexOf,sliceand[...list]each go through the list: O(n). Inside a loop, they make O(n²). - Drop the small stuff. Two loops one after another is O(n + n) = O(2n), which is just O(n). Big O only cares about the shape of the growth, not fixed multiples.
- Keep the biggest part. O(n² + n) is O(n²): for big n, the n² part is all that matters.
Try it: a hidden loop
// Looks like one loop, but includes() searches the whole list each time.
function hasRepeatSlow(nums) {
for (let i = 0; i < nums.length; i++) {
if (nums.slice(i + 1).includes(nums[i])) return true;
}
return false;
}
// Change 10000 to 20000, then 40000: each doubling takes about 4 times as long.
const big = Array.from({ length: 10000 }, (_, i) => i);
const start = Date.now();
console.log(hasRepeatSlow(big));
console.log(Date.now() - start, "ms");Press Run to see the output. You can change the code first.
Memory counts too
The same idea applies to memory: how much extra storage does the solution need? A few variables is O(1) space. A Map with an entry per item is O(n) space. Often you can trade one for the other: use more memory (a Map) to save a lot of time. That trade is the heart of the Hashing pattern.
Reading the limits
Problems usually tell you how big the input can be. That's a hint about the speed you need:
| Input size | What usually fits |
|---|---|
| up to about 20 | even O(2ⁿ) |
| up to about 3,000 | O(n²) |
| up to about 1,000,000 | O(n) or O(n log n) |
| billions | O(log n), or a formula |
Your turn
What's the Big O of each function? Think first, then run it with bigger and bigger n to check: does doubling n double the steps, quadruple them, or barely change them?
Your turn
function a(n) { let s = 0; for (let i = 0; i < n; i++) s++; for (let i = 0; i < n; i++) s++; return s; }
function b(n) { let s = 0; for (let i = 1; i < n; i *= 2) s++; return s; }
function c(n) { let s = 0; for (let i = 0; i < n; i++) for (let j = 0; j < i; j++) s++; return s; }
for (const n of [1000, 2000, 4000]) console.log(n, a(n), b(n), c(n));Press Run to see the output. You can change the code first.
What you learned
- Big O describes how the work grows as the input grows.
- One loop is O(n); a loop inside a loop is O(n²); halving is O(log n).
- Hidden loops (
includes,slice) count. - Drop constants and smaller parts: O(2n + 5) is O(n).
- The input size limits hint at the speed you need.