AlgoVerse

Dynamic table (amortized analysis)

An array that doubles whenever it fills up; the copies are sometimes expensive, but the amortized cost per insert is at most 3.

We want an array we can keep inserting into. When the table is full, make one twice as big and copy every item into it.

Read the full explanation ↓
Input:
n=9PDF export

9 inserts; the table grows at inserts 2, 3, 5 and 9, needing 1+2+4+8 = 15 copies. The total cost is 24, under 3 × 9.

  1. def dynamic_table(items):
  2. capacity = 1
  3. table = [None]
  4. size = 0
  5. copies = 0
  6. for item in items:
  7. if size == capacity:
  8. capacity = 2 * capacity
  9. bigger = [None] * capacity
  10. for i in range(size):
  11. bigger[i] = table[i]
  12. copies = copies + 1
  13. table = bigger
  14. table[size] = item
  15. size = size + 1
  16. return size + copies

Invariant: After every insert, the total number of copies is less than twice the number of items, so the total cost is at most 3n.

Start

503182139425764768

Local variables

Orange = changed in this step

items list

538192746

Call stack

  1. dynamic_table()line 1
Step 1 of 104
Black = insert · Orange = key stepinsert: 0/9 · copy: 0/15 · grow: 0/4 · total_cost: 0/1

    How the work grows with input size

    Average of 12 random graphs per n (fixed seeds). Hollow marker = the input on screen.

    • insert
    • copy
    • current input (n=9)
    0510152046810121416n = number of itemsinsertcopy
    Show as a table
    ninsertcopy
    443
    667
    887
    101015
    121215
    141415
    161615
    Explanation

    The idea

    We want an array we can keep inserting into. When the table is full, make one twice as big and copy every item into it.

    Amortized analysis

    A single insert can be expensive (copying the whole table), but such inserts are rare. After n inserts the copies add up to 1 + 2 + 4 + … < 2n; so the total cost is under 3n, and the amortized cost of an insert is O(1).

    The accounting method: pay 3 coins per insert: one for the insert itself, one for this item's future copy, and one for the future copy of an older item. The coins always suffice.

    What to watch in the trace

    • The bars are the current table, empty slots included.
    • The growth chart shows that the copies grow linearly, not quadratically.