DSATime ComplexityDynamic array

Amortized Analysis Visualizer

What is Amortized Analysis

Worst-case per operation can lie. A dynamic-array push is usually O(1) and rarely O(n) when the table doubles. Amortized analysis spreads that rare bill across all pushes so each one is O(1) on average — even in the worst sequence.

  • Aggregate: total cost of n pushes is < 3n, so average < 3.
  • Accounting: charge 3 tokens every push; leftover tokens pay for the next copy.
  • Potential: Φ = 2·size − capacity. Amortized = actual + ΔΦ stays O(1).

How this visualizer works

Push 8 values into a table that doubles 1→2→4→8. Switch among Aggregate, Accounting, and Potential. The copies flash; the running amortized cost stays constant.

Interactive amortized analysis

dynamic_array.push

Live slots
Unused capacity
Copied this step

current_action

Each push costs 1, plus a full copy when the array doubles.

three_methods.txt

1Aggregate: total cost / n operations
2Accounting: overcharge cheap ops, pay later
3Potential: Φ = 2·size − capacity
4Push into free slot: actual 1
5Push that doubles: actual size+1
6Σ actual = n + (1+2+4+…+n) < 3n
7Amortized cost of push = O(1)

cost log

Speed Ready

Python model

dynamic_array.py

1class DynamicArray:
2 def __init__(self):
3 self.cap, self.a = 1, [None]
4 self.size = 0
5 def push(self, x):
6 if self.size == self.cap:
7 nxt = [None] * (self.cap * 2)
8 for i in range(self.size):
9 nxt[i] = self.a[i]
10 self.a, self.cap = nxt, self.cap * 2
11 self.a[self.size] = x
12 self.size += 1