edubun
English
1 / 20

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 questions

You 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.

n
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);
Output
10
100
3

5Problem

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.

GrowthSteps for n = 1,000,000Time at 10⁹ steps per second
O(1)1about a nanosecond
O(log n)about 20about 20 nanoseconds
O(n)1,000,0001 millisecond
O(n log n)about 20,000,000about 0.02 seconds
O(n²)1,000,000,000,000about 17 minutes
O(2ⁿ)more than 300,000 digits longnever 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.

  1. O(2ⁿ)
  2. O(1)
  3. O(n log n)
  4. O(n)
  5. O(n²)
  6. O(log n)
Hint

Try n = 1,000 in each.

Solution

Answer:

  1. O(1)
  2. O(log n)
  3. O(n)
  4. O(n log n)
  5. O(n²)
  6. 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.

Expected output
45
190
Your code
function 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.

Expected output
9
19
Your code
function 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

Mistake
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);
Output
6
Fixed
const 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);
Output
1

Starting 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.

Next unitRecursion
Full text · The whole lesson as one text

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.

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.

The common growth rates

  • O(1), constant. The work does not depend on n: reading the first value of a list, or a value at a known position.
  • O(log n), logarithmic. Each step halves the problem: binary search. A million values, about 20 steps.
  • O(n), linear. Each value is handled once: linear search, finding the largest value, adding up a list.
  • O(n log n). Merge sort, and quicksort on average. The best that comparison sorting can do.
  • O(n²), quadratic. Every pair is looked at: bubble, selection and insertion sort in the worst case, or two loops nested inside each other.
  • O(2ⁿ), exponential. The work doubles with every extra value: trying every subset of n items, or moving n disks in the Tower of Hanoi.
Six growth rates drawn on the same axes. Move n and switch on the log scale; the table gives the step counts at your n and the time for a million values at a billion steps per second.

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. O(n²) is 10¹² steps, a thousand seconds, about 17 minutes. O(2ⁿ) cannot be finished: 2 to the power of a million is a number with more than 300,000 digits. This is why choosing the right algorithm usually matters far more than buying a faster computer. A machine ten times faster turns 17 minutes into 1.7 minutes; switching from O(n²) to O(n log n) turns it into a fiftieth of a second.

GrowthSteps for n = 1,000,000Time at 10⁹ steps per second
O(1)1about a nanosecond
O(log n)about 20about 20 nanoseconds
O(n)1,000,0001 millisecond
O(n log n)about 20,000,000about 0.02 seconds
O(n²)1,000,000,000,000about 17 minutes
O(2ⁿ)more than 300,000 digits longnever finishes

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++; }

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. That is why many real sorting routines switch to insertion sort for short pieces of the list.

Big O can describe memory as well as time. Merge sort uses O(n) extra memory for its second list; insertion sort uses O(1) extra memory, just a few variables.
Key points
  • 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.

Practice questions from How fast? Big O notation on edubun

Embed this quiz

Free to embed. Please keep the credit line.

Sources for this course (11)
  • MIT OpenCourseWare 6.006 Introduction to Algorithms, Spring 2020 (Demaine, Ku, Solomon)
  • lecture notes 1 Introduction, 3 Sorting, 9 Breadth-First Search, 10 Depth-First Search (ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/pages/lecture-notes) and Fall 2011 lecture 13 BFS notes (ocw.mit.edu/courses/6-006-introduction-to-algorithms-fall-2011)
  • Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms (MIT Press)
  • with the CLRS-based Khan Academy algorithms unit by Thomas Cormen and Devin Balkcom of Dartmouth (khanacademy.org/computing/computer-science/algorithms: binary search, selection sort analysis, merge sort, quicksort overview and analysis)
  • MacTutor History of Mathematics, Al-Khwarizmi (mathshistory.st-andrews.ac.uk/Biographies/Al-Khwarizmi: word algorithm from the Latin title Algoritmi de numero Indorum)
  • D. E. Joyce, Euclid's Elements Book VII Propositions 1 and 2 (mathcs.clarku.edu/~djoyce/elements/bookVII)
  • Wolfram MathWorld, Merge Sort (mathworld.wolfram.com/MergeSort.html: proposed by John von Neumann in 1945, after Knuth 1998 p. 159)
  • Stanford CS "Tony Hoare: Quicksort" (cs.stanford.edu/people/eroberts/courses/soco/projects/2008-09/tony-hoare/quicksort.html: devised while a student at Moscow State University for Russian-English machine translation with a tape dictionary, programmed in Algol 60 and published 1961; the year 1959 from the Wikipedia Quicksort article and its cited sources)
  • Bodleian Libraries, Ada Lovelace (blogs.bodleian.ox.ac.uk/adalovelace: 1843 paper, Note G Bernoulli numbers)
  • Fourmilab text of Menabrea's Sketch with Lovelace's notes (fourmilab.ch/babbage/sketch.html)
  • Seven Bridges of Konigsberg (Euler 1736) and Tower of Hanoi (Edouard Lucas, 1883) checked against the Wikipedia articles and their cited sources.

Checked: 2026-10-17