M05 · Arrays

Dynamic Arrays: Capacity, Resizing and Amortized Append

A fixed-size array cannot grow, yet List<T>, list, ArrayList and std::vector all let you append forever. They keep a buffer with spare room and, when it fills up, move everything into a bigger one. This lesson shows exactly what that costs and why appending stays cheap on average.

~35 minBeginnerC# · Python · Java · C++
Curriculum: M05 Arrays · 5 of 5 lessons available

You will be able to

  • Tell size from capacity and predict when the next append will resize.
  • Trace an append, insert and removeAt slot by slot, including every copy and shift.
  • Derive why n appends cost O(n) in total when capacity grows geometrically, and why growing by a constant amount costs O(n²).
  • State which operations are O(1), amortized O(1) and O(n), and the assumptions behind each.
  • Explain what each language's built-in dynamic array guarantees and what is only an implementation detail.

Helpful before this lesson

  • M02 Memory Model — What a variable, a reference and a buffer really are, and why contiguous memory is fast.
  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.
  • M04 Built-in Collections — The collections every language ships, what each operation costs, and how to choose one.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

A plain array is one block of memory with room for a fixed number of elements. Because the elements sit side by side, the address of element i is start + i × elementSize, so reading or writing any index takes the same, constant time. The price is that the block cannot get longer: the memory right after it may already belong to something else.

A dynamic array wraps such a block (the buffer) and tracks two numbers:

  • size (Count, len, size()): how many elements you stored.
  • capacity: how many slots the buffer has. Slots from size to capacity - 1 exist in memory but hold no element of yours.

As long as size < capacity, appending just writes into the next free slot. When the buffer is full, the array allocates a larger buffer, copies every element across, and drops the old buffer. That single append costs O(n). The lab above lets you watch both buffers exist at the same time while the copy runs.

The teaching implementation used in the lab and in the code below doubles the capacity (0 → 1 → 2 → 4 → 8 …) and never shrinks. Real runtimes use different numbers; the runtime notes list what each one does.

Operation costs

Operation Time Why
get(i), set(i, v) O(1) Index arithmetic finds the slot directly.
append(v) with spare capacity O(1) One write into slot size.
append(v) when full O(n) Allocate, then copy all n elements.
append(v), averaged over a sequence amortized O(1) Resizes are rare enough; derived below.
insert(i, v) O(n − i), plus a resize if full Every element from i on moves one slot right.
removeAt(i) O(n − i) Every element after i moves one slot left.
remove the last element O(1) Nothing needs to move.
search by value O(n) No ordering to exploit; see linear search.

Auxiliary space for a resize is the new buffer: O(n) extra memory while both buffers are alive.

Amortized is not average. "Average case" averages over possible inputs and can be unlucky. "Amortized" is a guarantee about every sequence of operations: the total cost of any n appends is O(n), even though some individual appends cost O(n). Nothing probabilistic is involved.

Why append is amortized O(1)

Count element writes, as the lab's Element writes metric does. Start empty with the doubling rule and append n elements.

  • Each append writes its own element once: n writes in total.

  • A resize happens when size reaches 1, 2, 4, 8, …, and copies that many elements. The last resize copies fewer than n elements, the one before fewer than n/2, and so on:

    copies < n + n/2 + n/4 + … < 2n

So n appends cost fewer than n + 2n = 3n writes: O(n) in total, a constant per append on average. Run the Doubling from empty preset and watch the average writes per append stay below 3 in the cost chart.

The same argument works for any growth factor g > 1: the copies form a geometric series that sums to less than n · g / (g − 1). A factor of 2 gives under 2n copies; 1.5 gives under 3n. Smaller factors copy more often but waste less memory, which is why runtimes pick different numbers.

Growing by a constant amount does not work. If each resize adds a fixed k slots, resizes happen every k appends and copy k, 2k, 3k, … elements. That is about n²/(2k) copies for n appends: O(n²) total, O(n) per append. Geometric growth is what makes append cheap.

Insert and remove move data

Inserting at index i must keep the order, so the elements at i … size-1 each move one slot to the right, starting from the end so nothing is overwritten before it is copied. Removing at i moves the elements after it one slot left and then clears the last slot. The lab draws a faded leftover copy in the slot a shift has just read from: the value is still in memory until the next write overwrites it, which is exactly why removeAt clears the vacated slot (otherwise a garbage-collected runtime would keep that object alive).

Inserting or removing at the end moves nothing. Inserting at the front moves everything. If your algorithm repeatedly inserts or removes at the front, a dynamic array is the wrong structure; a deque or a linked structure is the usual answer (covered in later modules).

Built-in dynamic arrays

All four languages ship a dynamic array. The guarantees below come from the language or library specification; growth numbers are implementation details observed on the toolchains this lab is tested with, and may differ on other versions or runtimes.

C# List<T> Python list Java ArrayList<E> C++ std::vector<T>
Append Add(x) append(x) add(x) push_back(x) / emplace_back(...)
Insert Insert(i, x) insert(i, x) add(i, x) insert(it, x)
Remove at RemoveAt(i) (no return) pop(i) (returns) remove(int i) (returns) erase(it)
Read capacity Capacity not exposed not exposed capacity()
Reserve EnsureCapacity(n), Capacity = n none ensureCapacity(n) reserve(n)
Shrink TrimExcess() automatic trimToSize() shrink_to_fit() (non-binding)
Append guarantee O(1) when Count < Capacity, otherwise O(n) (docs) amortized O(1) (CPython) "amortized constant time" (Javadoc) amortized constant (standard)
Observed growth 0 → 4, then doubles (.NET 10) 4, 8, 16, 24, 32, … ≈ 1.125× (CPython 3.14) 0 → 10, then ≈ 1.5× (OpenJDK 25) doubles in libstdc++ (GCC 15); MSVC's STL grows 1.5× per its source
Out of range ArgumentOutOfRangeException IndexError IndexOutOfBoundsException operator[]: undefined behaviour; at(): std::out_of_range

Things that differ in ways that matter:

  • Python indices can be negative (items[-1] is the last element) and pop() without an argument removes the last element in O(1). CPython's list also shrinks its buffer when it becomes much emptier; the other three never shrink unless you ask. Python integers are arbitrary precision, so a list of ints stores references to integer objects, not the numbers themselves.
  • Java's ArrayList stores references. An ArrayList<Integer> holds pointers to boxed Integer objects; the element data is not contiguous even though the references are. C#'s List<int> and C++'s std::vector<int> store the values themselves contiguously.
  • C++ reallocation invalidates everything. When a std::vector grows, every pointer, reference and iterator into it becomes invalid; an insert or erase without reallocation invalidates those at or after the position. Keeping &v[0] across a push_back is a classic bug. The C++ version below moves elements with std::move instead of copying, which is cheaper for types that own resources but still O(n) moves.
  • Modifying while iterating throws InvalidOperationException in C# (List's enumerator is versioned) and usually ConcurrentModificationException in Java (fail-fast, best effort, not guaranteed). In C++ it is undefined behaviour once iterators are invalidated. Python does not detect it; elements are silently skipped or revisited.
  • Pre-sizing helps. If you know you will add 10,000 elements, EnsureCapacity / reserve / ensureCapacity (or new List<T>(10000), new ArrayList<>(10000)) performs one allocation instead of a dozen copies. It changes the constant, not the complexity.

The teaching implementation

The code tabs in the lab, and the full listings below, are one implementation in four languages with the same growth rule and the same behaviour, checked by one shared set of test cases. Two deliberate simplifications: elements are copied in a plain loop (real libraries use Array.Copy, System.arraycopy, memmove or move construction, still O(n)), and the C++ version default-constructs its buffer slots, so T must be default-constructible. std::vector avoids that by constructing elements in raw, uninitialised storage.

Common mistakes

  • Confusing size with capacity. A List<T> created with capacity 100 still has Count == 0; list[5] throws. Capacity is room, not content. The Size is not capacity preset shows this.
  • Calling one resize "O(1)" or "amortized O(n)". A resizing append is O(n); the amortized bound is O(1) per append over a sequence.
  • Inserting at the front in a loop. n inserts at index 0 cost 0 + 1 + … + (n − 1) shifts: O(n²). Append and reverse once, or use a deque.
  • Removing while looping forward by index. After removeAt(i) the next element is now at i, so i++ skips it. Iterate backwards or build a new list.
  • Holding a C++ pointer, reference or iterator across push_back.
  • Assuming every runtime doubles. Code should not depend on a particular growth factor.

Edge cases

  • Capacity 0. The first append must allocate (the teaching version grows 0 → 1).
  • Insert at index size is valid and behaves like append, including the resize when full.
  • Remove the last element shifts nothing but still clears the slot.
  • Index equal to size is out of range for get, set and removeAt even when the buffer has a slot there.
  • Huge sizes. Real implementations cap capacity (e.g. near int.MaxValue in .NET and Java) and must avoid overflow when computing 2 × capacity; the teaching version does not handle this.

Worked practice

1. Starting from capacity 0 with the doubling rule, how many element copies do 9 appends cause, and what is the final capacity?

Resizes happen on appends 1, 2, 3, 5 and 9 (when size reaches 0, 1, 2, 4 and 8) and copy 0 + 1 + 2 + 4 + 8 = 15 elements. The final capacity is 16. Total writes: 9 own writes + 15 copies = 24 < 3 × 9 = 27.

2. A list holds 1,000 elements. Which is cheaper: removeAt(0) or removeAt(999)? By how much, in shifts?

removeAt(999) removes the last element and shifts nothing. removeAt(0) shifts the other 999 elements left.

3. A growth rule adds 100 slots each time. Roughly how many copies do 100,000 appends cause?

Resizes copy 100, 200, …, about 100,000 elements: about 1,000 resizes averaging 50,000 copies, so roughly 50 million copies (n²/(2k) with k = 100). With doubling the total stays under 200,000.

4. Why does the teaching removeAt set the vacated slot to null / None / default?

After the shift, the last used slot still holds a copy of a reference that now also lives one slot to the left (or the removed element itself, when removing the last one). In a garbage-collected language that stale reference would keep the object alive for as long as the slot is not overwritten. Clearing it removes the reference. In C++ the assignment T{} releases whatever that slot still owns.

Summary

  • A dynamic array is a fixed buffer plus size and capacity. Index access is O(1).
  • A full buffer is replaced by a larger one: O(n) for that append.
  • Geometric growth makes n appends cost O(n) in total: amortized O(1) per append. Constant growth makes them O(n²).
  • Insert and remove are O(n − i) because they shift; the end of the array is cheap, the front is expensive.
  • Each language guarantees the complexity, not the growth factor. Check the docs before relying on capacity details, and in C++ remember that reallocation invalidates pointers and iterators.

Full implementation

The same class in four languages, each checked against one shared set of test cases (append with and without a resize, front, middle and end inserts, removals, out-of-range indices, duplicates, extreme values) and a randomized comparison with the language's own dynamic array.

namespace Bekadan.Dsa.Examples.DynamicArrays;
 
/// <summary>
/// A growable array backed by a fixed-size buffer that doubles when full.
/// A teaching model of <see cref="List{T}"/>, which uses Array.Copy and starts
/// at capacity 4, but has the same costs.
/// </summary>
public sealed class DynamicArray<T>
{
    private T[] _items;
    private int _count;
 
    public DynamicArray(int initialCapacity = 0)
    {
        ArgumentOutOfRangeException.ThrowIfNegative(initialCapacity);
        _items = new T[initialCapacity];
    }
 
    public int Count => _count;
 
    public int Capacity => _items.Length;
 
    public T this[int index]
    {
        get
        {
            if (index < 0 || index >= _count)
                throw new ArgumentOutOfRangeException(nameof(index));
            return _items[index];
        }
        set
        {
            if (index < 0 || index >= _count)
                throw new ArgumentOutOfRangeException(nameof(index));
            _items[index] = value;
        }
    }
 
    public void Add(T item)
    {
        if (_count == _items.Length)
            Grow();
        _items[_count] = item;
        _count++;
    }
 
    public void Insert(int index, T item)
    {
        if (index < 0 || index > _count)
            throw new ArgumentOutOfRangeException(nameof(index));
        if (_count == _items.Length)
            Grow();
        for (int i = _count; i > index; i--)
            _items[i] = _items[i - 1];
        _items[index] = item;
        _count++;
    }
 
    public T RemoveAt(int index)
    {
        if (index < 0 || index >= _count)
            throw new ArgumentOutOfRangeException(nameof(index));
        T removed = _items[index];
        for (int i = index; i < _count - 1; i++)
            _items[i] = _items[i + 1];
        _items[_count - 1] = default!; // drop the leftover reference for the GC
        _count--;
        return removed;
    }
 
    private void Grow()
    {
        int newCapacity = _items.Length == 0 ? 1 : _items.Length * 2;
        var newItems = new T[newCapacity];
        for (int i = 0; i < _count; i++)
            newItems[i] = _items[i];
        _items = newItems; // the old array becomes garbage
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/DynamicArrays/DynamicArray.cs

"""A growable array backed by a fixed-size buffer that doubles when full.
 
Python's own list is already a dynamic array (CPython over-allocates by about
1/8). This class models one with an explicit buffer so each resize, copy and
shift is visible. Negative indices are not supported, unlike list.
"""
 
 
class DynamicArray[T]:
    def __init__(self, initial_capacity: int = 0) -> None:
        if initial_capacity < 0:
            raise ValueError("initial_capacity must not be negative")
        self._items: list[T | None] = [None] * initial_capacity
        self._count = 0
 
    def __len__(self) -> int:
        return self._count
 
    @property
    def capacity(self) -> int:
        return len(self._items)
 
    def __getitem__(self, index: int) -> T:
        if not 0 <= index < self._count:
            raise IndexError("index out of range")
        return self._items[index]  # type: ignore[return-value]
 
    def __setitem__(self, index: int, value: T) -> None:
        if not 0 <= index < self._count:
            raise IndexError("index out of range")
        self._items[index] = value
 
    def append(self, value: T) -> None:
        if self._count == len(self._items):
            self._grow()
        self._items[self._count] = value
        self._count += 1
 
    def insert(self, index: int, value: T) -> None:
        if not 0 <= index <= self._count:
            raise IndexError("index out of range")
        if self._count == len(self._items):
            self._grow()
        for i in range(self._count, index, -1):
            self._items[i] = self._items[i - 1]
        self._items[index] = value
        self._count += 1
 
    def remove_at(self, index: int) -> T:
        if not 0 <= index < self._count:
            raise IndexError("index out of range")
        removed = self._items[index]
        for i in range(index, self._count - 1):
            self._items[i] = self._items[i + 1]
        self._items[self._count - 1] = None  # drop the leftover reference
        self._count -= 1
        return removed  # type: ignore[return-value]
 
    def _grow(self) -> None:
        new_capacity = 1 if not self._items else len(self._items) * 2
        new_items: list[T | None] = [None] * new_capacity
        for i in range(self._count):
            new_items[i] = self._items[i]
        self._items = new_items  # the old list loses its last reference

Tested on CPython 3.14.0 · examples/python/dsa_examples/dynamic_array.py

package dev.bekadan.dsa.arrays;
 
/**
 * A growable array backed by a fixed-size buffer that doubles when full.
 * A teaching model of what ArrayList does; OpenJDK's ArrayList grows by
 * about 1.5x and uses System.arraycopy, but the costs are the same.
 */
public final class DynamicArray<E> {
    private Object[] items;
    private int size;
 
    public DynamicArray(int initialCapacity) {
        if (initialCapacity < 0) {
            throw new IllegalArgumentException("initialCapacity must not be negative");
        }
        items = new Object[initialCapacity];
    }
 
    public DynamicArray() {
        this(0);
    }
 
    public int size() {
        return size;
    }
 
    public int capacity() {
        return items.length;
    }
 
    @SuppressWarnings("unchecked")
    public E get(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index " + index + " out of bounds for size " + size);
        }
        return (E) items[index];
    }
 
    public void set(int index, E element) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index " + index + " out of bounds for size " + size);
        }
        items[index] = element;
    }
 
    public void add(E element) {
        if (size == items.length) {
            grow();
        }
        items[size] = element;
        size++;
    }
 
    public void add(int index, E element) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("Index " + index + " out of bounds for size " + size);
        }
        if (size == items.length) {
            grow();
        }
        for (int i = size; i > index; i--) {
            items[i] = items[i - 1];
        }
        items[index] = element;
        size++;
    }
 
    @SuppressWarnings("unchecked")
    public E remove(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index " + index + " out of bounds for size " + size);
        }
        E removed = (E) items[index];
        for (int i = index; i < size - 1; i++) {
            items[i] = items[i + 1];
        }
        items[size - 1] = null; // drop the leftover reference for the GC
        size--;
        return removed;
    }
 
    private void grow() {
        int newCapacity = items.length == 0 ? 1 : items.length * 2;
        Object[] newItems = new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newItems[i] = items[i];
        }
        items = newItems; // the old array becomes garbage
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/arrays/DynamicArray.java

#pragma once
 
#include <cstddef>
#include <memory>
#include <stdexcept>
#include <utility>
 
namespace bekadan::dsa {
 
// A growable array backed by a fixed-size buffer that doubles when full.
// A teaching model of std::vector. Simplification: the buffer is created with
// make_unique<T[]>, which default-constructs every slot, so T must be default
// constructible; std::vector instead constructs elements in raw storage.
template <typename T>
class DynamicArray {
public:
    explicit DynamicArray(std::size_t initial_capacity = 0)
        : data_(std::make_unique<T[]>(initial_capacity)), capacity_(initial_capacity) {}
 
    [[nodiscard]] std::size_t size() const noexcept { return size_; }
    [[nodiscard]] std::size_t capacity() const noexcept { return capacity_; }
 
    [[nodiscard]] const T& at(std::size_t index) const {
        if (index >= size_) {
            throw std::out_of_range("DynamicArray::at: index out of range");
        }
        return data_[index];
    }
 
    void set(std::size_t index, T value) {
        if (index >= size_) {
            throw std::out_of_range("DynamicArray::set: index out of range");
        }
        data_[index] = std::move(value);
    }
 
    void push_back(T value) {
        if (size_ == capacity_) {
            grow();
        }
        data_[size_] = std::move(value);
        ++size_;
    }
 
    void insert(std::size_t index, T value) {
        if (index > size_) {
            throw std::out_of_range("DynamicArray::insert: index out of range");
        }
        if (size_ == capacity_) {
            grow();
        }
        for (std::size_t i = size_; i > index; --i) {
            data_[i] = std::move(data_[i - 1]);
        }
        data_[index] = std::move(value);
        ++size_;
    }
 
    T remove_at(std::size_t index) {
        if (index >= size_) {
            throw std::out_of_range("DynamicArray::remove_at: index out of range");
        }
        T removed = std::move(data_[index]);
        for (std::size_t i = index; i + 1 < size_; ++i) {
            data_[i] = std::move(data_[i + 1]);
        }
        data_[size_ - 1] = T{};  // release whatever the vacated slot still owns
        --size_;
        return removed;
    }
 
private:
    void grow() {
        const std::size_t new_capacity = capacity_ == 0 ? 1 : capacity_ * 2;
        auto new_data = std::make_unique<T[]>(new_capacity);
        for (std::size_t i = 0; i < size_; ++i) {
            new_data[i] = std::move(data_[i]);
        }
        data_ = std::move(new_data);  // frees the old buffer immediately
        capacity_ = new_capacity;
    }
 
    std::unique_ptr<T[]> data_;
    std::size_t capacity_ = 0;
    std::size_t size_ = 0;
};
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/dynamic_array.hpp

References