Skip to content

Amortised cost: why push is O(1) on average

Working knowledgeConcept

Every so often, appending to a dynamic array copies every item, yet append is listed as O(1). That is not a rounding error. When rare expensive steps are always paid for by many cheap ones, you can bound the total, and the total divided by the count is the amortised cost.

01 One slow push among many fast ones

A dynamic array, such as a Python list or a Java ArrayList, writes into a spare slot when it has one. When it is full, it allocates a bigger block and copies everything across. With doubling, that copy gets bigger every time, but it also happens half as often.

The cost of each of 16 pushes into an array that starts with 1 slot and doubles when full
Work done by push 1, 2, 3 … 16
1
#22
#33
1
#55
1
1
1
#99
1
1
1
1
1
1
1
  • one write
  • resize: copy, then write

Push 9 does 9 units of work: copy 8 items, then write one. The 16 pushes do 31 units in all, under 2 per push.

The worst push here costs 9, and with a million items one push copies over half a million. So in the worst case, one push is `O(n)`. But the expensive pushes are rare, and the sum stays small. That gap between one operation and a whole sequence is what amortised analysis is about. (How the array grows in memory is drawn step by step in How a growing array stays fast when it fills up.)

02 What amortised promises, and what it does not

An operation has amortised cost `f(n)` when any sequence of m operations, starting from empty, costs at most m × f(n) in total. It is a worst-case promise about the total, not about each step.

Worst case, one pushO(n)The push that triggers a resize copies every item. Any single call might be that one.
Amortised, per pushO(1)Any m pushes cost at most about 3m. No input, order or luck makes the total worse.
Average casea different ideaAn average over likely inputs, such as random keys. A bad input can still be slow on every step.

Amortised does not involve probability. It is about how expensive steps are spaced out, so it holds for every sequence of operations, including one chosen to be as bad as possible.

03 Method 1: add up the whole sequence

The direct way is to add up the total. n pushes do n writes. The resizes copy 1 + 2 + 4 + … items, up to the largest power of two below n. Each term in that series is one more than the sum of all the terms before it, so the whole series is less than 2n.

Total work for n pushes, starting from 1 slot and doubling
Pushes (n)WritesCopies in resizesTotalPer push
881+2+4 = 715≈ 1.9
16161+2+4+8 = 1531≈ 1.9
1,000,0001,000,0001,048,5752,048,575≈ 2.0

Writes plus copies stay under 3n, so n pushes are O(n) in total and O(1) each, amortised. This works whenever you can add up the costs in closed form.

04 Method 2: prepay with coins

The other way is to charge every push a fixed price that is a little more than it usually costs, and save the extra. If the savings always cover the expensive steps, the fixed price is an amortised bound. For doubling, 3 coins is enough: 1 for its own write, 1 to copy itself at the next resize, and 1 to copy an older item whose own coins are already spent.

Pay 3 coins per push: the bank never goes below zero
Step 1 of 9
Coins spent 0Bank 0
The array’s block (moves on each resize)
0
1
2
3
4
5
6
7
Work done by each push
Empty
  • just written
  • copied in a resize
  • stored
  • spare slot
  • not allocated yet

An empty array with room for 1 item. Every push will pay 3 coins, whatever it really costs. One coin buys one write or one copy. The bank is empty.

0 coins paid in

The bank never goes negative, so 3 coins per push always covers the real work. That proves the same O(1) amortised bound without adding up a series. It is often the easier method: you only check that each expensive step finds enough saved.

05 Another case: a queue made of two stacks

A stack gives back the newest item; a queue gives back the oldest. You can build a queue from two stacks: push onto inbox, pop from outbox, and when outbox is empty, move all of inbox across. Moving reverses the order, which puts the oldest item on top.

two_stacks.py
class Queue:
def __init__(self):
self.inbox, self.outbox = [], []
def push(self, x):
self.inbox.append(x)
def pop(self):
if not self.outbox:
while self.inbox: # the rare, expensive part
self.outbox.append(self.inbox.pop())
return self.outbox.pop()
A queue from two stacks: one push, move or pop per step
Step 1 of 10
inbox · push() adds here
Empty
outbox · pop() takes from here
Empty
Returned by pop()
Empty
  • just arrived
  • waiting

Both stacks are empty. push will always go on inbox; pop will always come off outbox.

0 moves so far

One pop can move n items. But follow a single item instead of a single call: it is pushed onto inbox once, moved to outbox once, and popped once. It can never move back. So each item causes at most a fixed handful of steps, and n operations cost O(n) in total: O(1) amortised per operation.

06 Spot it in code: charge the work to the items

A while inside a for looks like O(n²). Often it is not. Ask how many times, over the whole run, the inner loop can do its work, not how many times it can run inside one outer step.

next_greater.py
def next_greater(nums):
ans = [-1] * len(nums)
stack = [] # indexes still waiting for an answer
for i, x in enumerate(nums):
while stack and nums[stack[-1]] < x:
ans[stack.pop()] = x # each index is popped at most once...
stack.append(i) # ...and pushed exactly once
return ans
print(next_greater([2, 1, 5, 3, 4])) # [5, 5, -1, 4, -1]

One pass of the while can pop many indexes. But each index is pushed once and popped at most once, so across the whole loop there are at most n pops. The function is O(n), and each outer step is O(1) amortised.

Operations that are slow now and then, cheap in total
OperationWorst single callAmortisedWhy it averages out
Dynamic array push (doubling)O(n)O(1)Each resize is twice as far from the last
Two-stack queue popO(n)O(1)Each item moves across once
Monotonic stack stepO(n)O(1)Each index is popped at most once
Binary counter +1O(number of bits)O(1)Bit k flips only every 2ᵏ increments

07 When the average does not save you

grow ×2 when full shrink ÷2 when half fullShrinking at the same point you growAt 8 items in 8 slots, a push grows to 16 and copies 8. A pop leaves 8 in 16, half full, so it shrinks and copies 8. Alternate the two and every call is O(n). Shrink only when a quarter full, so a resize is always far from the next.
One call can still be slowAmortised bounds the total, not each call. If one request, frame or packet has a time limit, the push that resizes a large array can miss it. Reserve capacity up front when you know the size.
xs.pop(0) xs.insert(0, x)Slow every time is not amortisedOn a CPython list, these shift every other item, every call. Nothing averages out: n of them are O(n²). Use collections.deque for work at the front.
def push(self, x): self.refill_inbox() # moves outbox back self.inbox.append(x)Letting items move backThe two-stack proof relies on each item crossing once. Move items back to inbox on every push, and alternating push and pop makes each call move everything.

Hash map lookups are O(1) on average, and their resizes are O(1) amortised. These are separate claims. Amortised analysis covers the resizing; the average-case part assumes the hashes spread well, and keys that all collide are slow on every lookup.

08 Check yourself

Question

A dynamic array doubles when full. Which statement is true?

Question

Using the two-stack queue, you push n items, then pop all n. How many moves from inbox to outbox happen in total?

Question

Why does the inner while not make next_greater O(n²)?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?