Data structure · Linear structures

Dynamic array

A contiguous buffer that grows by reallocating: constant-time indexing, amortized constant-time append, linear-time insert and remove in the middle.

The derivations, edge cases and exercises are in the lesson Reallocation and invalidated references. Open it full width in the playground.

On this page
  1. The idea
  2. Operations
  3. Invariants
  4. When to use it
  5. Built-in equivalents
  6. Step through it
  7. Implementation
  8. Learn more
  9. References

The idea

A dynamic array keeps its elements side by side in one buffer and tracks two numbers: how many elements it holds (size) and how many slots the buffer has (capacity). Indexing is arithmetic on the base address, so any element is one step away.

When an append finds the buffer full, it allocates a larger one (the teaching implementation doubles it), copies every element across and frees the old buffer. Because the capacity grows geometrically, the copies average out to a constant per append.

Representation. One contiguous buffer of capacity slots, of which the first size are in use.

Operations

Dynamic array operations and their complexity
OperationTimeExtra spaceNotes
Get / set by indexO(1)O(1)Address = base + index × element size.
AppendO(1) amortizedO(1) amortizedO(n) for the append that triggers a resize.
Insert at indexO(n − i)O(1)Every element after i shifts right by one.
Remove at indexO(n − i)O(1)Every element after i shifts left by one; removing the last is O(1).
Search by valueO(n)O(1)O(log n) with binary search if the contents are kept sorted.

Invariants

What stays true before and after every operation.

  • 0 ≤ size ≤ capacity.
  • Slots 0 … size − 1 hold the elements in order; slots size … capacity − 1 are unused.
  • After a resize, capacity at least doubles, which is what makes appends amortized O(1).

When to use it

Use it when

  • You index by position, iterate in order or append at the end: the default sequence in all four languages.
  • Cache locality matters: a linear scan over contiguous memory is much faster than chasing pointers.

Avoid it when

  • You insert or remove at the front or in the middle often; a deque or linked structure avoids the shifting.
  • Other code keeps references or iterators into the buffer while you append: a resize moves every element.

Built-in equivalents

What the standard library of each language offers. Linked types have a full page in the collections encyclopedia with every operation’s complexity, memory effects and a tested example.

C#

List<T>

Python

list

Java

ArrayList<E>

C++

std::vector<T>

Step through it

The interactive lab for dynamic array: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.

Implementation in four languages

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

Learn more

Comparisons

  • Dynamic array vs linked list· One operation sequence on a doubling dynamic array and on a singly linked list with a tail reference. Different kinds of work, each counted exactly.

Problems, patterns and exercises

References