Big O, by counting

Big O describes how the number of basic operations grows with the input size, ignoring constant factors. The explorer draws the common classes; the exercises ask you to derive the class of a code snippet, then show the derivation. Every answer here was checked by running the snippet's loop structure and counting.

Growth curves

Growth classes to draw
1101001000102030noperations (log scale)
O(log n)O(n)O(n log n)O(n²)
Operations at n = 32 (constants dropped)
ClassNamef(n)
O(1)constant1
O(log n)logarithmic5
O(√n)square root6
O(n)linear32
O(n log n)linearithmic160
O(n²)quadratic1,024
O(n³)cubic32,768
O(2ⁿ)exponential4,294,967,296
O(n!)factorial2.63e+35

Constant factors decide which algorithm wins for small n; growth decides it for large n. At n = 64, 2ⁿ is already about 1.8 × 10¹⁹: no constant factor rescues an exponential algorithm.

Measure an exercise

Each worked exercise below has a counter that runs its loop structure. Here its measured counts are drawn against its claimed class: if the claim is right, the two curves have the same shape.

020k40k20004000ncount
Measured: work callsO(n log n) (scaled)

O, Θ and Ω in one paragraph each

O(g(n)) is an upper bound: for large enough n, the count is at most a constant times g(n). Linear search is O(n), and also (uselessly) O(n²).

Ω(g(n)) is a lower bound: at least a constant times g(n). Any comparison sort is Ω(n log n) in the worst case.

Θ(g(n)) means both: the count grows exactly like g(n) up to constants. When people say "binary search is O(log n)" they usually mean Θ(log n) in the worst case.

A bound also needs a case (best, worst, average over stated inputs, expected over random choices, or amortized over a sequence) and a resource (time or extra space). The exercises name both.

Worked exercises (30)

Intermediate

  1. A linear loop around a doubling looploops · linearithmic · nested
  2. Inner loop bounded by a halving outer variableloops · geometric series · linear
  3. Loop until i² exceeds nloops · square root · primes
  4. Nested loops over two different inputsmultiple inputs · nested
  5. Naive recursive Fibonaccirecursion · exponential · recursion tree
  6. Recursion on half the inputrecursion · logarithmic · recurrences
  7. Two halves plus linear workrecursion · linearithmic · merge sort
  8. Two halves plus constant workrecursion · linear · recurrences
  9. Generating every subsetrecursion · exponential · backtracking
  10. Generating every permutationrecursion · factorial · backtracking
  11. Concatenating immutable strings in a loopstrings · quadratic · hidden cost
  12. Inserting at the front of an array list, n timesdynamic arrays · quadratic · hidden cost
  13. n appends to a doubling dynamic arrayamortized · dynamic arrays · linear
  14. Sort once, then binary search n timessorting · binary search · linearithmic
  15. Nested loop with a breakloops · quadratic · break
  16. Two pointers moving toward each othertwo pointers · linear · potential argument