Big-O, measured

n went up 100 times; a List took 1,150 times longer and a HashSet 9. Why the wrong structure is invisible at the size you test with.

10 min read🧮 Data Structures and Algorithms in Java

Big-O is usually taught as a table to memorise, and a table is the least useful form of it. What it actually gives you is an answer to one question: when this gets bigger, what happens?

And the reason that question matters is the thing the table hides — a wrong choice is invisible at the size you test with.

The same program, three sizes

Two ways to ask "have I seen this before": a List and a HashSet. Both correct. Both obvious. Here is contains() called n times as n grows:

plaintext
###          n      List ms   HashSet ms
###       1000          3.0          0.2
###      10000         35.6          0.4
###     100000       3454.4          1.8

Read the columns, not the rows.

n went up 100×. The List time went up 1,150×. The HashSet time went up 9×.

That is what Big-O describes. List.contains scans until it finds the element, so one call is O(n) and n calls are O(n²). HashSet.contains computes a hash and looks in one bucket — one call is O(1), so n calls are O(n).

Now the row that explains why this ships:

plaintext
###       1000          3.0          0.2

Three milliseconds against two tenths. Nobody notices that. It passes review, it passes the test suite with its twenty rows of fixture data, and it is fifteen times slower in a way no one can feel. At a hundred thousand it is nineteen hundred times slower and the endpoint takes three and a half seconds.

The shapes worth recognising

NotationNameWhat doubling n doesWhere you meet it
O(1)constantnothingHashMap.get, array index
O(log n)logarithmicadds one stepbinary search, a balanced tree
O(n)lineardoublesone pass over a list
O(n log n)linearithmicslightly more than doublesa good sort
O(n²)quadraticquadruplesa loop inside a loop
O(2ⁿ)exponentialsquarestrying every subset

The middle column is the useful one. "Doubling n quadruples the time" is a sentence you can apply to your own code in your head; "quadratic" is a word.

And the practical boundary: O(n²) is fine until it is not, and the cliff is around a few tens of thousands. A nested loop over a hundred items is ten thousand operations and instant. Over a hundred thousand items it is ten billion, and you will be waiting.

What the notation deliberately throws away

Big-O keeps the growth and discards everything else, which is what makes it portable across machines and languages — and what makes it misleading when misused.

  • Constants are dropped. O(n) and O(100n) are both O(n). So an O(n) algorithm can genuinely be slower than an O(n²) one at the sizes you care about, and for small n it often is.
  • Lower-order terms are dropped. n² + n is O(n²).
  • It describes the worst case unless stated. HashMap.get is O(1) on average and O(log n) in a bucket that has degenerated into a tree — which is a real behaviour of Java's implementation and is covered by the collections course.

Amortised, which is why ArrayList is allowed to say O(1)

ArrayList.add is O(1), and occasionally it copies the entire backing array to a bigger one, which is plainly O(n). Both are true.

The resolution is amortised cost: the expensive copies are rare enough, and grow far enough apart, that the average over many adds is constant. Because the array doubles, adding n elements does at most about 2n copies in total — so the cost per add, spread out, is a constant.

This is worth understanding rather than accepting, because it is the same argument behind HashMap resizing, behind StringBuilder, and behind every buffer that doubles. And it has a real edge: amortised O(1) is not O(1) for any individual call. In a latency-sensitive path, the one add that triggers a copy of a million elements is a spike, and that is why new ArrayList<>(expectedSize) exists.

Where this actually lands: which collection you are choosing

The reason a Java engineer learns this is not interviews. It is that every collection in the standard library is a different set of these trade-offs, and choosing is a daily decision:

You needUseBecause
"have I seen this?"HashSetO(1) instead of O(n)
lookup by keyHashMapthe same argument
a list you indexArrayListcontiguous memory, O(1) get
a queueArrayDequeO(1) at both ends
always the smallestPriorityQueueO(log n) instead of sorting each time
sorted, with range queriesTreeMapO(log n) and ordered

If a List is being searched with contains inside a loop, that is the first table row and the measurement at the top of this lesson. It is the single most common accidental O(n²) in ordinary business code, and it is one line to fix.

Under the hood: what "amortised" actually adds up over a real run

"Amortised O(1)" is a specific arithmetic argument, not a synonym for "usually fast", and it is worth doing the sum once.

ArrayList grows by 1.5× when full (oldCapacity + (oldCapacity >> 1), straight from the OpenJDK source), copying every existing element into the new backing array each time. Starting from capacity 10 and adding a million elements, the array resizes roughly log₁.₅(100,000) ≈ 28 times — and each resize costs a full copy of everything held so far. Summed across all 28 resizes, the total number of element copies is bounded by a constant multiple of n (a standard result for any growth factor greater than 1: the copies form a geometric series that sums to O(n), not O(n²)), so the total work across a million add calls is O(n), which is exactly what "the average cost per add is O(1)" means. It is genuinely a proof, not an approximation — but it is a statement about the sum over many calls, which is why it says nothing about any individual call.

That last clause is where amortised analysis gets misapplied. "Amortised O(1)" does not mean "every call is fast" — it means "the calls that are slow are rare enough, and get proportionally rarer, that the average stays constant." The one add that triggers copying 666,666 elements because the array just crossed a resize threshold is a real O(n) pause on that specific call, felt in full by whatever thread is waiting on it. A latency-sensitive path — a request handler with a P99 budget, not a batch job that only cares about total throughput — can be hurt by exactly the call the "O(1) average" summary told you not to worry about. new ArrayList<>(expectedSize) sidesteps the whole question by never triggering a resize in the first place, which is the concrete, one-line form of "know the difference between average and worst-case-per-call before you promise a latency budget."

Try it yourself

Reason about where the "slow" resizes land

An ArrayList starts at capacity 10 and grows by 1.5× (oldCapacity + oldCapacity/2, integer division) whenever it is full. Without running anything: roughly how many times does it resize while growing from empty to holding 1,000 elements, and is the last resize (the one nearest 1,000 elements) more or less expensive, in elements copied, than the first one?

Why the last resize dominates the total cost, not the first

Capacity grows 10 → 15 → 22 → 33 → 49 → 73 → 109 → 163 → 244 → 366 → 549 → 823 → 1234, roughly a dozen resizes to pass 1,000. The first resize (10 → 15) copies 10 elements — trivial. The last resize before crossing 1,000 (823 → 1234) copies 823 elements — by far the single most expensive individual operation in the whole sequence, even though it is only one of about twelve resizes. This is the geometric-series shape behind "the total is O(n)": most of the total copying work is concentrated in the last resize or two, not spread evenly across all of them, which is exactly why the one add call that triggers it can be a real, felt pause even though the average across all thousand add calls stays small.

Misconceptions

  • "Amortised O(1) means every individual call is fast." It means the average across many calls is constant — a small fraction of calls (the ones that trigger a resize) are genuinely O(n), and as the earlier exercise shows, the later resizes in a growing collection's life are the expensive ones, not the early ones.
  • "Big-O and 'amortised' are two names for the same idea." Big-O describes a single operation's cost as a function of input size; amortised analysis describes the average cost of an operation across a sequence of calls, specifically to justify calling something "O(1)" when some individual calls in that sequence are provably more expensive than O(1).

Sources

  • OpenJDK java.util.ArrayList source, the grow() method — the 1.5× growth factor this lesson's arithmetic is built on.
  • Robert Sedgewick and Kevin Wayne, Algorithms (4th ed.) — amortised analysis and the dynamic-array (ArrayList-equivalent) resizing argument.
  • Thomas H. Cormen et al., Introduction to Algorithms (CLRS), the chapter on amortised analysis — the aggregate/accounting/potential-method framing of why geometric growth gives O(1) amortised cost.
Progress is saved on this device and to your account when signed in.