data structureslinear

dynamic array

an array that doubles when it fills up, so adding to the end stays cheap.

report a mistake
.md

one block of slots, so item i is a single jump away. when the block fills, a new one twice the size takes everything over.

get / set
O(1) start + i slots, no search
push / pop
O(1) at the end. push is amortized
grow
O(n) copies everything, once per doubling
insert / remove at i
O(n) everything after i slides over
reach for it
  • most lists you'll ever need
  • a stack
  • building up results one at a time
  • lookups by position
on this page
  1. the idea
  2. the easy part
  3. the operations
  4. try it
  5. pseudocode
  6. the grow, up close
  7. complexity
  8. implementations
  9. pitfalls
  10. variants
  11. practice
  12. how real libraries do it
  13. sources

an array is one block of memory with its items side by side, so item i sits at the start plus i slots: one jump, however long the array is. the catch is that a block’s size is fixed when it’s made. a dynamic array keeps a block with spare room at the end, and when the room runs out, it moves everything into a block twice as big.

the idea

one block of slots. the item at index 2 is the start plus 2 slots, so getting it is one jump, not a search.

an animation in six steps. three items, 7, 3 and 9, sit in the first three of four slots; the item at index 2 is the start plus 2 slots. a push writes 4 into the last free slot, and the block is full. a new block of eight slots appears, and the four items copy across one by one, in order. the old block goes away and the next push, 5, lands in slot 4. last, inserting 8 at index 1 slides 5, 4, 9 and 3 one slot right, last first, before 8 goes in.

the easy part

with room at the end, everything at the end is cheap. push writes to slot length and adds one to it. pop takes one off and hands back what’s there. get and set jump straight to slot i. none of them move any other item.

the length and the capacity are different numbers: length is how many items there are, capacity is how many slots the block has. a push only gets expensive when they’re equal.

the operations

in

4 slots, length 0

0length
1
2
3
out

push past 4 items to see it grow, then insert near the front and count what slides.

moves this step
0
all pushes
0 moves for 0
pseudocode
push(a, x):  if a.length == a.cap: grow(a)  a.slots[a.length] = x  # the first free slot  a.length += 1 pop(a):  if a.length == 0: error "empty"  a.length -= 1  return a.slots[a.length] get(a, i):  if not 0 <= i < a.length: error "out of range"  return a.slots[i]  # one jump: start + i slots set(a, i, x):  if not 0 <= i < a.length: error "out of range"  a.slots[i] = x insert(a, i, x):  # 0 <= i <= a.length  if a.length == a.cap: grow(a)  for j from a.length down to i + 1:    a.slots[j] = a.slots[j - 1]  # back to front  a.slots[i] = x  a.length += 1 remove(a, i):  # 0 <= i < a.length  x = a.slots[i]  for j from i to a.length - 2:    a.slots[j] = a.slots[j + 1]  # front to back  a.length -= 1  return x grow(a):  # double, copying the items over in order  bigger = array of 2 * a.cap empty slots  for i in range(a.length):    bigger[i] = a.slots[i]  a.slots, a.cap = bigger, 2 * a.cap

an interactive dynamic array that starts with 4 slots. buttons push and pop at the end, and get, set, insert and remove at an index you pick. slots past the length are dimmed, the index is marked i and the first free slot is marked length. a push into a full array shows a second, twice-as-big block and copies the items across one at a time. inserts and removes show each item sliding over, the matching pseudocode line is highlighted, and counters show the moves for this step and the average per push so far.

push past 4 items to watch it grow, and keep an eye on the average moves per push: it jumps after each grow and falls back after, but never reaches 3. then insert near the front and count what slides.

try it

an empty array has 4 slots and doubles when it's full. after 9 pushes, how many slots does it have?

pick one.

0 / 0 right

a practice exercise. first: an empty array has 4 slots and doubles when full; after a number of pushes, how many slots does it have? then an array with an index marked: for an insert or a remove at that index, how many items slide over?

pseudocode

pseudocode
push(a, x):
  if a.length == a.cap: grow(a)
  a.slots[a.length] = x  # the first free slot
  a.length += 1

pop(a):
  if a.length == 0: error "empty"
  a.length -= 1
  return a.slots[a.length]

get(a, i):
  if not 0 <= i < a.length: error "out of range"
  return a.slots[i]  # one jump: start + i slots

set(a, i, x):
  if not 0 <= i < a.length: error "out of range"
  a.slots[i] = x

insert(a, i, x):  # 0 <= i <= a.length
  if a.length == a.cap: grow(a)
  for j from a.length down to i + 1:
    a.slots[j] = a.slots[j - 1]  # back to front
  a.slots[i] = x
  a.length += 1

remove(a, i):  # 0 <= i < a.length
  x = a.slots[i]
  for j from i to a.length - 2:
    a.slots[j] = a.slots[j + 1]  # front to back
  a.length -= 1
  return x

grow(a):  # double, copying the items over in order
  bigger = array of 2 * a.cap empty slots
  for i in range(a.length):
    bigger[i] = a.slots[i]
  a.slots, a.cap = bigger, 2 * a.cap

a.cap is the number of slots and a.length the number of items. insert shifts back to front and remove front to back, so each item moves into a slot that’s already been emptied.

the grow, up close

complexity

operationworstamortized
get, setO(1)O(1)
pushO(n)O(1)
popO(1)O(1)
insert, remove at iO(n − i)O(n − i)

a push’s worst case is the one that grows. insert and remove pay for every item after i, so the front is the most expensive place and the end the cheapest: a remove at the end is a pop.

space: right after a grow the block is half full, so it holds at most twice the slots the items need, until pops empty it out, since it never shrinks.

03161push 1push 64
64 pushes
124 moves
per push
1.94
a push that grows
average so far

a chart of 64 pushes into an array that starts with 4 slots. each push costs 1 move for its write, and a push that finds the array full also copies every item, so the chart spikes there, in amber. a white line tracks the average cost so far. a picker switches the growth rule between double it, grow by half and add 4 slots: doubling ends at 124 moves, under 2 per push, while adding 4 slots climbs to 544, 8.5 per push.

the same chart as on the stack + queue page: a ring buffer grows the same way. with doubling the running average never reaches 3 moves per push, and 64 pushes come to 124 moves, under 2 each. growing by half copies a bit more often, and adding 4 slots never settles.

implementations

each tab is the real file from the repo, checked by its tests (go test, cargo test, vitest, make test, swift test, python -m unittest), including 2000 seeded pushes, pops, gets, sets, inserts and removes checked against the language’s own list, or a plain array in c. every one starts at 4 slots and doubles, so the capacities match across languages. out of range is where they differ: go returns false, rust None, typescript undefined, c returns false, swift nil, and python raises IndexError. each language’s own list already does all this; these build it by hand on a fixed block, so you can see the grow.

go/algos/dynarray/dynarray.go
// Package dynarray is a reference dynamic array: O(1) get and set, O(1) amortized push.
// doubles when full; insert and remove shift everything after them.
package dynarray

// Array keeps its items in the first Len() of Cap() slots.
// go's own slices grow like this when you append; this one does it by hand, on a slice it never appends to.
// make one with New: the zero value has no slots, so pushing to it panics.
type Array[T any] struct {
	slots  []T
	length int
}

// New returns an empty array with room for 4 items.
func New[T any]() *Array[T] {
	return &Array[T]{slots: make([]T, 4)}
}

// Len returns how many items are in the array.
func (a *Array[T]) Len() int {
	return a.length
}

// Cap returns how many items fit before the next grow.
func (a *Array[T]) Cap() int {
	return len(a.slots)
}

// Push adds x at the end, doubling the slots first if they're full.
func (a *Array[T]) Push(x T) {
	if a.length == len(a.slots) {
		a.grow()
	}
	a.slots[a.length] = x
	a.length++
}

// Pop takes the last item off. It returns false if the array is empty.
func (a *Array[T]) Pop() (T, bool) {
	var zero T
	if a.length == 0 {
		return zero, false
	}
	a.length--
	x := a.slots[a.length]
	a.slots[a.length] = zero // drop the reference so the item can be freed
	return x, true
}

// Get returns item i, and false unless 0 <= i < Len().
func (a *Array[T]) Get(i int) (T, bool) {
	if i < 0 || i >= a.length {
		var zero T
		return zero, false
	}
	return a.slots[i], true
}

// Set replaces item i. It returns false unless 0 <= i < Len().
func (a *Array[T]) Set(i int, x T) bool {
	if i < 0 || i >= a.length {
		return false
	}
	a.slots[i] = x
	return true
}

// Insert puts x at index i, shifting i and everything after it one slot right.
// i can be Len() (the end). It returns false outside 0 <= i <= Len().
func (a *Array[T]) Insert(i int, x T) bool {
	if i < 0 || i > a.length {
		return false
	}
	if a.length == len(a.slots) {
		a.grow()
	}
	for j := a.length; j > i; j-- { // back to front, so nothing is overwritten before it moves
		a.slots[j] = a.slots[j-1]
	}
	a.slots[i] = x
	a.length++
	return true
}

// Remove takes item i out, shifting everything after it one slot left.
// It returns false unless 0 <= i < Len().
func (a *Array[T]) Remove(i int) (T, bool) {
	var zero T
	if i < 0 || i >= a.length {
		return zero, false
	}
	x := a.slots[i]
	for j := i; j < a.length-1; j++ {
		a.slots[j] = a.slots[j+1]
	}
	a.length--
	a.slots[a.length] = zero
	return x, true
}

// grow doubles the slots and copies the items over in order.
func (a *Array[T]) grow() {
	bigger := make([]T, 2*len(a.slots))
	copy(bigger, a.slots[:a.length])
	a.slots = bigger
}
rust/algos/src/dyn_array.rs
//! dynamic array: O(1) get and set, O(1) amortized push. doubles when full; insert and remove shift everything after them.

/// A growable array on a fixed block of slots. `Vec` grows this way underneath; this one does the
/// growing by hand, using a `Vec` only as a block that never changes length.
pub struct DynArray<T> {
    slots: Vec<Option<T>>, // every slot exists; the ones past len hold None
    len: usize,
}

impl<T> DynArray<T> {
    /// Makes an empty array with 4 slots.
    pub fn new() -> Self {
        let mut slots = Vec::new();
        slots.resize_with(4, || None); // vec![None; 4] would need T: Clone
        Self { slots, len: 0 }
    }

    /// The number of items.
    pub fn len(&self) -> usize {
        self.len
    }

    /// Whether there are no items.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// The number of slots: how many items fit before the next grow.
    pub fn capacity(&self) -> usize {
        self.slots.len()
    }

    /// Adds `x` at the end, doubling the slots first if they're full.
    pub fn push(&mut self, x: T) {
        if self.len == self.capacity() {
            self.grow();
        }
        self.slots[self.len] = Some(x);
        self.len += 1;
    }

    /// Takes the last item off, or `None` if the array is empty.
    pub fn pop(&mut self) -> Option<T> {
        if self.len == 0 {
            return None;
        }
        self.len -= 1;
        self.slots[self.len].take()
    }

    /// Item `i`, or `None` unless `i < len`.
    pub fn get(&self, i: usize) -> Option<&T> {
        if i < self.len {
            self.slots[i].as_ref()
        } else {
            None
        }
    }

    /// Replaces item `i`. False unless `i < len`.
    pub fn set(&mut self, i: usize, x: T) -> bool {
        if i >= self.len {
            return false;
        }
        self.slots[i] = Some(x);
        true
    }

    /// Puts `x` at index `i`, shifting `i` and everything after it one slot right. `i` can be `len`
    /// (the end). False if `i > len`.
    pub fn insert(&mut self, i: usize, x: T) -> bool {
        if i > self.len {
            return false;
        }
        if self.len == self.capacity() {
            self.grow();
        }
        // back to front, so nothing is overwritten before it moves. take() leaves None behind
        for j in (i..self.len).rev() {
            self.slots[j + 1] = self.slots[j].take();
        }
        self.slots[i] = Some(x);
        self.len += 1;
        true
    }

    /// Takes item `i` out, shifting everything after it one slot left. `None` unless `i < len`.
    pub fn remove(&mut self, i: usize) -> Option<T> {
        if i >= self.len {
            return None;
        }
        let x = self.slots[i].take();
        for j in i..self.len - 1 {
            self.slots[j] = self.slots[j + 1].take();
        }
        self.len -= 1;
        x
    }

    /// Doubles the slots and moves the items over in order.
    fn grow(&mut self) {
        let cap = self.capacity();
        let mut bigger = Vec::with_capacity(cap * 2);
        for slot in &mut self.slots[..self.len] {
            bigger.push(slot.take());
        }
        bigger.resize_with(cap * 2, || None);
        self.slots = bigger;
    }
}

impl<T> Default for DynArray<T> {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn contents(a: &DynArray<i64>) -> Vec<i64> {
        (0..a.len()).map(|i| *a.get(i).unwrap()).collect()
    }

    fn filled(n: i64) -> DynArray<i64> {
        let mut a = DynArray::new();
        for x in 1..=n {
            a.push(x);
        }
        a
    }

    #[test]
    fn starts_empty_with_room_for_4() {
        let mut a = DynArray::<i64>::new();
        assert!(a.is_empty());
        assert_eq!((a.len(), a.capacity()), (0, 4));
        assert_eq!(a.get(0), None);
        assert_eq!((a.pop(), a.remove(0)), (None, None));
    }

    #[test]
    fn the_5th_push_doubles_to_8_the_9th_to_16() {
        let mut a = DynArray::new();
        let mut caps = vec![];
        for x in 1..=9 {
            a.push(x);
            caps.push(a.capacity());
        }
        // 4, 8, 16: adding 4 slots each time would stop at 12
        assert_eq!(caps, [4, 4, 4, 4, 8, 8, 8, 8, 16]);
        assert_eq!(contents(&a), (1..=9).collect::<Vec<_>>());
    }

    #[test]
    fn get_and_set_in_range_only() {
        let mut a = filled(3);
        assert!(a.set(1, 20));
        assert_eq!(contents(&a), [1, 20, 3]);
        // i is a usize, so there's no negative index to try
        assert_eq!(a.get(3), None);
        assert!(!a.set(3, 0));
    }

    #[test]
    fn insert_shifts_right() {
        let mut a = filled(3);
        assert!(a.insert(0, 0) && a.insert(2, 15) && a.insert(a.len(), 4));
        assert_eq!(contents(&a), [0, 1, 15, 2, 3, 4]);
        assert!(!a.insert(a.len() + 1, 9));
        let mut full = filled(4);
        full.insert(1, 9);
        assert_eq!((full.capacity(), contents(&full)), (8, vec![1, 9, 2, 3, 4]));
    }

    #[test]
    fn remove_shifts_left() {
        let mut a = filled(5);
        assert_eq!(
            [a.remove(0), a.remove(1), a.remove(2)],
            [Some(1), Some(3), Some(5)]
        );
        assert_eq!(contents(&a), [2, 4]);
        assert_eq!(a.remove(2), None);
    }

    #[test]
    fn pop_takes_from_the_end_and_it_never_shrinks() {
        let mut a = filled(9);
        let popped: Vec<_> = std::iter::from_fn(|| a.pop()).collect();
        assert_eq!(popped, (1..=9).rev().collect::<Vec<_>>());
        assert_eq!((a.len(), a.capacity()), (0, 16));
    }

    #[test]
    fn agrees_with_vec_over_2000_seeded_ops() {
        // xorshift32 seeded with 42, like the other tests here
        let mut state: u32 = 42;
        let mut next = || {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            state as usize
        };
        let mut a = DynArray::new();
        let mut model: Vec<i64> = Vec::new();
        for n in 0..2000 {
            let n = n as i64;
            let i = next() % (model.len() + 2); // one past the end is out of range for most ops
            match next() % 6 {
                0 => {
                    a.push(n);
                    model.push(n);
                }
                1 => assert_eq!(a.pop(), model.pop()),
                2 => assert_eq!(a.get(i), model.get(i)),
                3 => {
                    let ok = i < model.len();
                    assert_eq!(a.set(i, n), ok);
                    if ok {
                        model[i] = n;
                    }
                }
                4 => {
                    let ok = i <= model.len();
                    assert_eq!(a.insert(i, n), ok);
                    if ok {
                        model.insert(i, n);
                    }
                }
                _ => {
                    let want = (i < model.len()).then(|| model.remove(i));
                    assert_eq!(a.remove(i), want);
                }
            }
            assert_eq!(a.len(), model.len());
        }
        assert_eq!(contents(&a), model);
        assert!(a.capacity() >= model.len());
    }
}
site/src/visuals/dynamic-array/dyn-array.ts
/**
 * Dynamic array: O(1) get and set, O(1) amortized push. Doubles when full; insert and remove shift
 * everything after them.
 */
export class DynArray<T> {
  #slots: (T | undefined)[] = new Array<T | undefined>(4).fill(undefined);
  #length = 0;

  get length(): number {
    return this.#length;
  }

  /** How many items fit before the next grow. */
  get capacity(): number {
    return this.#slots.length;
  }

  push(x: T): void {
    if (this.#length === this.#slots.length) this.#grow();
    this.#slots[this.#length] = x;
    this.#length += 1;
  }

  pop(): T | undefined {
    if (this.#length === 0) return undefined;
    this.#length -= 1;
    const x = this.#slots[this.#length];
    this.#slots[this.#length] = undefined; // drop the reference so the item can be freed
    return x;
  }

  get(i: number): T | undefined {
    return this.#has(i) ? this.#slots[i] : undefined;
  }

  /** Replace item i. False if there's no item i. */
  set(i: number, x: T): boolean {
    if (!this.#has(i)) return false;
    this.#slots[i] = x;
    return true;
  }

  /** Put x at index i, shifting i and everything after it one slot right. i can be length (the end). */
  insert(i: number, x: T): boolean {
    if (!Number.isInteger(i) || i < 0 || i > this.#length) return false;
    if (this.#length === this.#slots.length) this.#grow();
    for (let j = this.#length; j > i; j--) this.#slots[j] = this.#slots[j - 1]; // back to front
    this.#slots[i] = x;
    this.#length += 1;
    return true;
  }

  /** Take item i out, shifting everything after it one slot left. */
  remove(i: number): T | undefined {
    if (!this.#has(i)) return undefined;
    const x = this.#slots[i];
    for (let j = i; j < this.#length - 1; j++) this.#slots[j] = this.#slots[j + 1]; // front to back
    this.#length -= 1;
    this.#slots[this.#length] = undefined;
    return x;
  }

  #has(i: number): boolean {
    return Number.isInteger(i) && i >= 0 && i < this.#length;
  }

  /** Twice the slots, the items copied over in order. */
  #grow(): void {
    const bigger = new Array<T | undefined>(this.#slots.length * 2).fill(undefined);
    for (let i = 0; i < this.#length; i++) bigger[i] = this.#slots[i];
    this.#slots = bigger;
  }
}
c/algos/dyn_array.c
/* dynamic array: O(1) get and set, O(1) amortized push. doubles when full; insert and remove shift everything after them. */
#include "dyn_array.h"

#include <stdlib.h>
#include <string.h>

bool da_init(DynArray *a) {
    a->items = malloc(4 * sizeof *a->items);
    a->len = 0;
    a->cap = a->items ? 4 : 0;
    return a->items != NULL;
}

void da_free(DynArray *a) {
    free(a->items);
    a->items = NULL;
    a->len = a->cap = 0;
}

/* doubles the slots. realloc extends the block in place when it can; otherwise it allocates a bigger
   one, copies the items over and frees the old one, which is the grow the other tabs write out */
static bool grow(DynArray *a) {
    int *bigger = realloc(a->items, 2 * a->cap * sizeof *bigger);
    if (!bigger) return false; /* a->items is still valid, so nothing is lost */
    a->items = bigger;
    a->cap *= 2;
    return true;
}

bool da_push(DynArray *a, int x) {
    if (a->len == a->cap && !grow(a)) return false;
    a->items[a->len++] = x;
    return true;
}

bool da_pop(DynArray *a, int *out) {
    if (a->len == 0) return false;
    *out = a->items[--a->len];
    return true;
}

bool da_get(const DynArray *a, size_t i, int *out) {
    if (i >= a->len) return false;
    *out = a->items[i];
    return true;
}

bool da_set(DynArray *a, size_t i, int x) {
    if (i >= a->len) return false;
    a->items[i] = x;
    return true;
}

bool da_insert(DynArray *a, size_t i, int x) {
    if (i > a->len) return false;
    if (a->len == a->cap && !grow(a)) return false;
    /* memmove, not memcpy: the two ranges overlap, and memmove copies as if through a scratch buffer */
    memmove(a->items + i + 1, a->items + i, (a->len - i) * sizeof *a->items);
    a->items[i] = x;
    a->len++;
    return true;
}

bool da_remove(DynArray *a, size_t i, int *out) {
    if (i >= a->len) return false;
    *out = a->items[i];
    memmove(a->items + i, a->items + i + 1, (a->len - i - 1) * sizeof *a->items);
    a->len--;
    return true;
}
swift/algos/DynArray.swift
/// dynamic array: O(1) get and set, O(1) amortized push. doubles when full; insert and remove shift everything after them.
/// swift's own Array grows this way; this one does it by hand, on a block of optional slots it never appends to.
public struct DynArray<Element> {
    private var slots = [Element?](repeating: nil, count: 4)
    public private(set) var count = 0

    public init() {}

    /// how many items fit before the next grow
    public var capacity: Int { slots.count }

    public mutating func push(_ x: Element) {
        if count == capacity { grow() }
        slots[count] = x
        count += 1
    }

    public mutating func pop() -> Element? {
        guard count > 0 else { return nil }
        count -= 1
        let x = slots[count]
        slots[count] = nil // drop the reference so the item can be freed
        return x
    }

    public func get(_ i: Int) -> Element? {
        guard 0 <= i, i < count else { return nil }
        return slots[i]
    }

    /// replaces item i. false unless 0 <= i < count
    @discardableResult
    public mutating func set(_ i: Int, _ x: Element) -> Bool {
        guard 0 <= i, i < count else { return false }
        slots[i] = x
        return true
    }

    /// puts x at index i, shifting i and everything after it one slot right. i can be count (the end)
    @discardableResult
    public mutating func insert(_ x: Element, at i: Int) -> Bool {
        guard 0 <= i, i <= count else { return false }
        if count == capacity { grow() }
        var j = count
        while j > i { // back to front, so nothing is overwritten before it moves
            slots[j] = slots[j - 1]
            j -= 1
        }
        slots[i] = x
        count += 1
        return true
    }

    /// takes item i out, shifting everything after it one slot left
    public mutating func remove(at i: Int) -> Element? {
        guard 0 <= i, i < count else { return nil }
        let x = slots[i]
        for j in i..<(count - 1) {
            slots[j] = slots[j + 1]
        }
        count -= 1
        slots[count] = nil
        return x
    }

    /// twice the slots, the items copied over in order
    private mutating func grow() {
        var bigger = [Element?](repeating: nil, count: capacity * 2)
        for i in 0..<count { bigger[i] = slots[i] }
        slots = bigger
    }
}
python/algos/dyn_array.py
"""dynamic array: O(1) get and set, O(1) amortized push. doubles when full; insert and remove shift everything after them."""

from __future__ import annotations

from typing import Any, Generic, TypeVar

T = TypeVar("T")


class DynArray(Generic[T]):
    """A growable array on a fixed block of slots. Python's own list works this way underneath."""

    def __init__(self) -> None:
        self._slots: list[Any] = [None] * 4  # the block. only a grow replaces it with a bigger one
        self._length = 0

    def __len__(self) -> int:
        return self._length

    @property
    def capacity(self) -> int:
        return len(self._slots)

    def push(self, x: T) -> None:
        if self._length == self.capacity:
            self._grow()
        self._slots[self._length] = x
        self._length += 1

    def pop(self) -> T:
        if self._length == 0:
            raise IndexError("pop from an empty array")
        self._length -= 1
        x = self._slots[self._length]
        self._slots[self._length] = None  # drop the reference so the item can be freed
        return x

    def get(self, i: int) -> T:
        """Return item i. Raises IndexError outside 0 <= i < len. Unlike a list, -1 isn't the last item."""
        self._check(i)
        return self._slots[i]

    def set(self, i: int, x: T) -> None:
        self._check(i)
        self._slots[i] = x

    def insert(self, i: int, x: T) -> None:
        """Put x at index i, shifting i and everything after it one slot right. i can be len (the end).

        Raises IndexError past either end, where list.insert would quietly clamp.
        """
        if not 0 <= i <= self._length:
            raise IndexError("array index out of range")
        if self._length == self.capacity:
            self._grow()
        for j in range(self._length, i, -1):  # back to front, so nothing is overwritten before it moves
            self._slots[j] = self._slots[j - 1]
        self._slots[i] = x
        self._length += 1

    def remove(self, i: int) -> T:
        """Take item i out, shifting everything after it one slot left."""
        self._check(i)
        x = self._slots[i]
        for j in range(i, self._length - 1):
            self._slots[j] = self._slots[j + 1]
        self._length -= 1
        self._slots[self._length] = None
        return x

    def _check(self, i: int) -> None:
        if not 0 <= i < self._length:
            raise IndexError("array index out of range")

    def _grow(self) -> None:
        """Twice the slots, the items copied over in order."""
        bigger: list[Any] = [None] * (2 * self.capacity)
        for i in range(self._length):
            bigger[i] = self._slots[i]
        self._slots = bigger

pitfalls

variants

practice

how real libraries do it

sources

  1. n1570 (opens in a new tab), the c draft standard: 7.22.3.5 says realloc returns a new object with the old contents, whose pointer “may have the same value” as the old one, and leaves the old object alone if it fails; 7.24.2.2 says memmove copies as if through a temporary array, so overlapping ranges are safe. ↩

  2. ResizingArrayStack.java (opens in a new tab) from sedgewick and wayne’s algorithms, 4th edition: double when full, halve at one-quarter full, constant amortized push and pop. ↩

  3. appending to and copying slices (opens in a new tab) in the go spec: append makes a new underlying array when the capacity isn’t enough, and otherwise reuses the old one. ↩

  4. listobject.c (opens in a new tab) in cpython 3.15.0: list_resize over-allocates by newsize >> 3 plus 6, rounded down to a multiple of 4, with the growth pattern in its comment. ↩

  5. ArrayList.java (opens in a new tab) at jdk-21-ga: grow asks for oldCapacity >> 1 more slots as its preferred growth. ↩

  6. runtime/slice.go (opens in a new tab) at go1.27.2: nextslicecap doubles below a threshold of 256, then adds (newcap + 3*threshold) >> 2 each step, a transition toward 1.25x. ↩

  7. raw_vec/mod.rs (opens in a new tab) at rust 1.99.1: grow_amortized takes twice the old capacity or what’s needed, whichever is bigger, and at least min_non_zero_cap (opens in a new tab): 8 for 1-byte elements, 4 up to 1024 bytes, else 1. ↩

  8. ArrayShared.swift (opens in a new tab) in swift 6.4.1: _growArrayCapacity doubles, and appends grow exponentially. ↩