Part 16 / Topic 1 of 12
Big-O: measuring growth, not seconds
Big-O describes how the amount of work a piece of code does grows as the input size (conventionally n) grows — not how many milliseconds it takes on your laptop today. A stopwatch answer changes with the machine, the JVM warm-up, and what else is running; a growth-shape answer does not.
Think of a courier comparing routes: "this route is twice as long" is useful on any vehicle, any day; "this route took 14 minutes" depends on the scooter, the traffic, and the time of day.
| Notation | Name | Shape | Example |
|---|---|---|---|
O(1) |
constant | same work, any n |
reading list.get(0) |
O(log n) |
logarithmic | halves the problem each step | binary search (section 7) |
O(n) |
linear | one pass over the input | summing a list |
O(n log n) |
log-linear | a sort, or n passes that each halve something |
merge sort, quicksort (section 6) |
O(n²) |
quadratic | a loop inside a loop over the same n |
comparing every pair |
static long countPairComparisons(int n) {
long comparisons = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
comparisons++;
}
}
return comparisons;
}
$ javac BigODemo.java
$ java BigODemo
-- same input, different shapes --
first element: 1
sum: 21
pairs summing to 7: 3
sorted copy: [1, 2, 3, 4, 5, 6]
-- O(n^2) comparisons as n grows: watch the ratio, not the count --
n=1000 -> 499500 comparisons
n=2000 -> 1999000 comparisons (4.0x)
n=4000 -> 7998000 comparisons (4.0x)
doubling n roughly quadruples the work: that is what n^2 means in practice
-- O(n) list.contains vs O(1) set.contains, same data --
found in list: true, found in set: true
list.contains took longer than set.contains: true (timings vary)
Doubling n from 1,000 to 2,000 nearly quadruples (4.0x) the comparison count, and doubling again from 2,000 to 4,000 quadruples it again — that ratio, not the raw numbers, is what "O(n²)" is telling you to expect. The last block repeats the point with real wall-clock time: ArrayList.contains scans linearly (O(n)), HashSet.contains jumps straight to the answer with a hash lookup (O(1), the subject of section 2) — the timing will vary run to run, but the O(n) search losing to the O(1) search on 200,000 elements will not.
⚠️ Big-O describes the worst case by default, unless stated otherwise ("average case," "amortized").
ArrayList.addis amortized O(1) (occasional resizing costs more, spread thin across many cheap adds) but O(n) in the single worst-case call that triggers a resize.
Full program: examples/big-o/BigODemo.java.
Done here? The practice set for Part 16 — including the solutions — is on the part page.