awelgorithms

Grow the backing array

Updated

When size == capacity, push must allocate a larger array, copy the occupied prefix, then write the new top. Doubling is the usual growth so push stays amortized O(1).

What to focus on

Copy only 0..size-1, not garbage past the top. Empty growth is allocating the first capacity. Shrinking is optional.

Worked examples

full

a = [4, 1, 9], cap 3, push 8
  1. alloc cap 6
  2. copy 4,1,9
  3. write 8

Result: [4, 1, 9, 8]

not full

a = [4, 1, 9, _, _], cap 5, size 3, push 8
  1. no copy
  2. write at index 3

Result: [4, 1, 9, 8]

empty first grow

a = [], cap 0, push 4
  1. alloc cap 1 or 8
  2. write 4

Result: [4]

Try it

Write growPush(a, x). a is the array-backed stack. x is the integer to push. size is occupied length. capacity is allocated length. If size equals capacity, allocate a larger array, copy 0..size-1, then write x. If not full, do not copy. Push onto full [4, 1, 9] copies 3 then writes 8. Size-3 cap-5 copies 0. Empty cap-0 allocates.

Values are integers. You may grow from cap 0. When not full, do not copy.