5 / 7 · Basic
How fast? Big O notation
At a billion steps per second, an n² method on a million values takes about 17 minutes; an n log n method takes 0.02 seconds.
Jump to the 12 practice questionsYou will learn
- Read the growth rate from the shape of code
- Tell best, average and worst cases apart
Before this: Sorting 2: merge sort and quicksort
1Explain
Growth matters more than the exact count
So far we have counted steps exactly: 45 comparisons, 4 swaps, 20 checks. Exact counts are useful for small examples, but they depend on details such as whether bubble sort stops early or how a pivot is chosen. When the input becomes large, one thing dominates everything else: how the count grows as n grows. An algorithm whose steps grow like n² will eventually lose to one whose steps grow like n log n, however carefully the first one is tuned.
2Explain
What O(n²) means
Big O notation is the shorthand for that growth. Writing that an algorithm is O(n²), read "big O of n squared", means that for large n its step count is at most some constant times n². Two rules make it easy to use. Drop constant factors: 3n and n/2 are both O(n). Keep only the fastest-growing term: n²/2 − n/2, the comparisons of selection sort, is O(n²), because for large n the n² part is almost all of it. MIT's 6.006 course uses the same idea when it compares data structures and sorts by their asymptotic running time.
3Problem
Simplify 3n² + 5n + 2
After dropping constant factors and lower-order terms, which usual simplified Big O expression describes 3n² + 5n + 2?
Hint
Keep the fastest-growing term and drop its constant.
Solution
Answer: O(n²)
Drop the constant factor 3 and keep only the fastest-growing term, n².
4Explore
Counting steps as n grows
Pick n. The program counts the steps of a single loop, of two nested loops and of repeated halving.
Double n: the single loop doubles, the nested loops go up four times, and the halving count goes up by one.
const n = 10;
let one = 0, pairs = 0, halvings = 0;
for (let i = 0; i < n; i++) one++; // O(n)
for (let i = 0; i < n; i++)
for (let j = 0; j < n; j++) pairs++; // O(n²)
for (let k = n; k > 1; k = Math.floor(k / 2)) halvings++; // O(log n)
console.log(one);
console.log(pairs);
console.log(halvings);10
100
35Problem
Two nested loops
Two loops nested inside each other, each running over n values. Big O?
Hint
n rounds, each with n rounds inside.
Solution
Answer: O(n²)
For each of the n outer rounds the inner loop does n rounds: n × n.
6Problem
Binary search in Big O
Binary search is
Hint
Each check halves what is left.
Solution
Answer: O(log n)
Each check halves the range that is left.
7Problem
Halving 64
How many times does while (n > 1) n = Math.floor(n / 2) run when n starts at 64?
Hint
64 → 32 → 16 → 8 → 4 → 2 → 1.
Solution
Answer: 6
64 → 32 → 16 → 8 → 4 → 2 → 1: six rounds, log₂ 64 = 6.
8Explain
What the numbers mean in seconds
For this example, imagine a computer that completes one billion (10⁹) simple steps each second. Real computers take different amounts of time for different steps. Here is what each growth rate means for a million values. O(log n) is about 20 steps, far under a microsecond. O(n) is a million steps, one millisecond. O(n log n) is about 20 million steps, 0.02 seconds.
| Growth | Steps for n = 1,000,000 | Time at 10⁹ steps per second |
|---|---|---|
| O(1) | 1 | about a nanosecond |
| O(log n) | about 20 | about 20 nanoseconds |
| O(n) | 1,000,000 | 1 millisecond |
| O(n log n) | about 20,000,000 | about 0.02 seconds |
| O(n²) | 1,000,000,000,000 | about 17 minutes |
| O(2ⁿ) | more than 300,000 digits long | never finishes |
9Problem
O(n²), ten times the input
An O(n²) method takes 2 seconds for 1,000 values. About how many seconds for 10,000 values?
Hint
10 times the input gives 10² times the work.
Solution
Answer: 200
10 times the input gives 10² = 100 times the work: 2 × 100 = 200 seconds.
10Problem
O(n), ten times the input
An O(n) method takes 2 seconds for 1,000 values. About how many seconds for 10,000 values?
Hint
Linear: the time grows by the same factor as the input.
Solution
Answer: 20
In a linear method each value is handled a fixed number of times, so 10 times the input means 10 times the time.
11Explain
Reading Big O from code
You can often read the growth rate straight from the shape of the code. A single loop over the list is O(n). Two loops, one inside the other, both over the list, are O(n²): for each of the n outer rounds the inner loop does up to n rounds. A loop that halves a number each time, such as while (n > 1) n = Math.floor(n / 2), is O(log n): starting from 1,000 it runs 9 times, from a million 19 times. Steps that happen one after another add up, and the bigger term wins: an O(n) loop followed by an O(n²) loop is O(n²) overall.
// O(n): one pass
let total = 0;
for (const x of list) total += x;
// O(n²): every pair
for (let i = 0; i < list.length; i++)
for (let j = i + 1; j < list.length; j++)
if (list[i] === list[j]) console.log("duplicate", list[i]);
// O(log n): halving
let k = list.length, rounds = 0;
while (k > 1) { k = Math.floor(k / 2); rounds++; }
12Problem
One loop, then a nested one
A program runs an O(n) loop and then an O(n²) loop. Overall it is
Hint
Add the two: n + n². Which term wins?
Solution
Answer: O(n²)
Steps in sequence add up, and n + n² is dominated by n².
13Explain
Best, average and worst case
One algorithm can behave very differently on different inputs. Insertion sort is O(n) on a list that is already sorted and O(n²) on a reversed one. Quicksort is O(n log n) on average and O(n²) with consistently bad pivots. When people quote a single Big O figure without saying which case, they usually mean the worst case, because it is a guarantee: the algorithm will never do worse. Big O also leaves things out. It ignores constant factors, so for small inputs an O(n²) method with very simple steps can beat an O(n log n) one.
14Problem
Insertion sort, already sorted
Insertion sort on a list that is already sorted is
Hint
Each new value is compared once and stays.
Solution
Answer: O(n)
Each new value is compared once with its left neighbour and stays: n − 1 comparisons.
15Problem
Small inputs
Why can an O(n²) method beat an O(n log n) method on small inputs?
Hint
Big O hides the constant factors.
Solution
Answer: Big O ignores constant factors, and the simpler method may do less per step
Big O describes growth for large n; for small n the hidden constants decide.
16Problem
From slow to fast growth
Order these growth rates from slowest-growing to fastest-growing.
- O(2ⁿ)
- O(1)
- O(n log n)
- O(n)
- O(n²)
- O(log n)
Hint
Try n = 1,000 in each.
Solution
Answer:
- O(1)
- O(log n)
- O(n)
- O(n log n)
- O(n²)
- O(2ⁿ)
For large n each one ends up far below the next.
17Practice
Count the pairs
Count the rounds of the inner loop. The program should print 45 and 190: doubling n makes the count about four times larger.
45
190function countPairs(n) {
let count = 0;
// Two nested loops: i from 0 to n - 1, j from i + 1 to n - 1.
// Add 1 to count inside the inner loop.
return count;
}
console.log(countPairs(10));
console.log(countPairs(20));
Hint
j starts at i + 1, so each pair is counted once.
A solution
function countPairs(n) {
let count = 0;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
count++;
}
}
return count;
}
console.log(countPairs(10));
console.log(countPairs(20));18Practice
Count the halvings
Count how many times a number can be halved before it reaches 1. It should print 9 and 19: a thousand times bigger, only 10 more rounds.
9
19function halvings(n) {
let rounds = 0;
// While n > 1, halve it (round down) and count.
return rounds;
}
console.log(halvings(1000));
console.log(halvings(1000000));
Hint
Round down with Math.floor after each halving.
A solution
function halvings(n) {
let rounds = 0;
while (n > 1) {
n = Math.floor(n / 2);
rounds++;
}
return rounds;
}
console.log(halvings(1000));
console.log(halvings(1000000));19Explain
Common mistakes
const list = [3, 8, 3, 5];
let dup = 0;
for (let i = 0; i < list.length; i++)
for (let j = 0; j < list.length; j++)
if (list[i] === list[j]) dup++;
console.log(dup);6const list = [3, 8, 3, 5];
let dup = 0;
for (let i = 0; i < list.length; i++)
for (let j = i + 1; j < list.length; j++)
if (list[i] === list[j]) dup++;
console.log(dup);1Starting j at 0 compares every value with itself and counts each pair twice. Start j at i + 1: still O(n²), but the count is right.
20
Summary
- Big O describes how steps grow with n, ignoring constant factors and smaller terms.
- Common rates: 1, log n, n, n log n, n², 2ⁿ.
- A million values at 10⁹ steps/s: n log n about 0.02 s, n² about 17 minutes.
- One loop is O(n); two nested loops O(n²); halving O(log n).
- A single quoted Big O usually means the worst case.