# dynamic array

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

source: https://learning.anthnydas.com/ds/dynamic-array/

## tl;dr

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

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

> **interactive figure:** 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.

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

a push writes at slot `length`, the first free one. nothing else moves. the block is now full.

full, so the next push needs a bigger block: twice the slots.

every item copies across, in order: 4 moves for 4 items. this is the expensive push.

the old block is freed and the push lands in slot 4. the next three pushes are one write each.

insert 8 at index 1: everything from index 1 on slides right one slot, last first, so nothing is overwritten. 4 slides, then 1 write.

## 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

> **interactive figure:** 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

> **interactive figure:** 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

```text
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

- **grow before the write.** push checks for room first. a full block grows, then the item goes into the first slot of the new half
- **copy in order, then let go of the old block.** the items keep their indexes: item i is in slot i of the new block too. in c, `realloc` does the whole grow, and it may hand back the same block, grown in place, when there's room after it.[^c] the other tabs write the copy out
- **double, don't add.** growing by a fixed number of slots, say 4, means a copy every 4 pushes, and each copy is bigger than the last: n pushes cost O(n²). doubling makes copies rarer as they get bigger. the stack + queue page charts both ([moves per push](/ds/stack-queue/#complexity))
- **why doubling is O(1) amortized.** a grow that copies k items happens on a push that found the block full, and since the last grow at least k / 2 pushes came in. charge each push 2 extra moves and the copy is paid for before it happens: every push costs at most 3. as a sum: the copies are 4, 8, 16, ..., each twice the one before, and a sum like that is under twice its last term, so n pushes cost under 2n copies
- **capacity never shrinks here.** pop a thousand items and the block stays the size it grew to. a version that shrinks should halve at a quarter full, not at half: shrinking at half lets one push and one pop at the boundary grow and shrink, copying everything, over and over[^algs4]

## complexity

| operation           | worst    | amortized |
| ------------------- | -------- | --------- |
| get, set            | O(1)     | O(1)      |
| push                | O(n)     | O(1)      |
| pop                 | O(1)     | O(1)      |
| insert, remove at i | O(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.

> **interactive figure:** 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`

```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`

```rust
//! 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`

```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`

```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`

```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`

```python
"""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

- **holding on to a slot across a push.** a grow moves every item to a new block. in c, a pointer into the old block points at freed memory. in go, `append` reuses the array when there's room and makes a new one when there isn't, so two slices that shared an array can quietly stop sharing it.[^goappend] rust's borrow checker won't let you keep a reference into a `Vec` while you push to it
- **inserting at the front in a loop.** each insert at index 0 slides everything, so n of them cost O(n²). push to the end and reverse once, or use a [deque](/ds/stack-queue/)
- **growing by a constant.** +10 or +100 slots instead of doubling turns n pushes into O(n²) copying
- **removing while walking forward.** remove item i and item i + 1 slides into slot i, so the loop's next step skips it. walk backward, or build a new array of what you keep

## variants

- **a smaller growth factor.** 1.5 instead of 2 wastes less space and copies a little more often. java's `ArrayList` grows by half, and cpython's list by about an eighth plus a little
- **a shrink rule.** halve at a quarter full, as above, so memory follows the length
- **a ring buffer.** the same block, with a moving head, so the front is cheap too: the [stack + queue](/ds/stack-queue/) page builds one

## practice

- [remove element](https://leetcode.com/problems/remove-element/): remove in place in one pass, without sliding everything each time
- [remove duplicates from sorted array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/): a read index and a write index
- [move zeroes](https://leetcode.com/problems/move-zeroes/): the same two indexes, keeping the order
- [rotate array](https://leetcode.com/problems/rotate-array/): O(n) time and O(1) extra space, with three reversals

## how real libraries do it

- **python.** `list` over-allocates by about an eighth of its size plus a few slots, rounded to a multiple of 4: capacities run 0, 4, 8, 16, 24, 32, 40, 52, 64, 76. a mild factor, still enough for amortized O(1) appends[^cpython]
- **java.** `ArrayList` grows by half its capacity each time, 1.5x[^java]
- **go.** `append` doubles a slice's capacity below 256, then moves smoothly toward 1.25x for big slices[^go]
- **rust.** `Vec` doubles, and a non-empty vector starts with at least 4 slots, 8 for bytes, 1 for elements over a kilobyte[^rust]
- **swift.** `Array` doubles its capacity when an append needs more room[^swift]

[^c]: [n1570](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf), 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.

[^algs4]: [ResizingArrayStack.java](https://algs4.cs.princeton.edu/13stacks/ResizingArrayStack.java.html) from sedgewick and wayne's _algorithms_, 4th edition: double when full, halve at one-quarter full, constant amortized push and pop.

[^goappend]: [appending to and copying slices](https://go.dev/ref/spec#Appending_and_copying_slices) in the go spec: `append` makes a new underlying array when the capacity isn't enough, and otherwise reuses the old one.

[^cpython]: [listobject.c](https://github.com/python/cpython/blob/v3.15.0/Objects/listobject.c#L117-L129) 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.

[^java]: [ArrayList.java](https://github.com/openjdk/jdk/blob/jdk-21-ga/src/java.base/share/classes/java/util/ArrayList.java#L231-L241) at jdk-21-ga: `grow` asks for `oldCapacity >> 1` more slots as its preferred growth.

[^go]: [runtime/slice.go](https://github.com/golang/go/blob/go1.27.2/src/runtime/slice.go#L326-L358) at go1.27.2: `nextslicecap` doubles below a threshold of 256, then adds `(newcap + 3*threshold) >> 2` each step, a transition toward 1.25x.

[^rust]: [raw_vec/mod.rs](https://github.com/rust-lang/rust/blob/1.99.1/library/alloc/src/raw_vec/mod.rs#L503-L534) 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`](https://github.com/rust-lang/rust/blob/1.99.1/library/alloc/src/raw_vec/mod.rs#L158-L166): 8 for 1-byte elements, 4 up to 1024 bytes, else 1.

[^swift]: [ArrayShared.swift](https://github.com/swiftlang/swift/blob/swift-6.4.1-RELEASE/stdlib/public/core/ArrayShared.swift#L179-L198) in swift 6.4.1: `_growArrayCapacity` doubles, and appends grow exponentially.

## related

- https://learning.anthnydas.com/ds/stack-queue.md
- https://learning.anthnydas.com/ds/linked-list.md
- https://learning.anthnydas.com/ds/hash-table.md
- https://learning.anthnydas.com/ds/heap.md
