Arrays and dynamic arrays · append amortized O(1); insert/remove O(n)

Dynamic array

Append, insert and remove with capacity, resizing and copies.

The full explanation, derivation and practice are in the lesson Dynamic arrays: capacity, resizing and amortized append.

Implementation

The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.

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