Dynamic array

Values stored side by side in one block of memory that grows by doubling: O(1) access by index and amortized O(1) appends.

Description

An array stores values next to each other in memory. Because every slot has the same size, the address of item i is simply the start address plus i times the slot size, so reading or writing any index takes the same constant time, whatever the array's length.

A plain array has a fixed size. A dynamic array, such as JavaScript's Array, Python's list, Java's ArrayList or C++'s vector, adds growth: it reserves some spare capacity, and when that runs out it allocates a bigger block, usually twice the size, and copies everything across.

Copying is O(n), but because the capacity doubles each time, copies become rarer as the array grows. Spread over all the appends, the cost per append is constant: amortized O(1).

Inserting or deleting in the middle is different: every later item must shift one slot, which is O(n). Arrays are fastest at the end, and at index-based access. Their contiguous layout also makes them very cache-friendly: scanning an array is often several times faster than scanning a linked structure of the same length.

How it works

703192434567size

Size 4, capacity 8: four slots used, four spare

  1. index 0: 7
  2. index 1: 3
  3. index 2: 9
  4. index 3: 4
  5. index 4:
  6. index 5:
  7. index 6:
  8. index 7:
Size 4, capacity 8: four slots used, four spare

Complexity

OperationAverageWorst
Read or write by indexO(1)O(1)
Append at the endAmortized O(1): an occasional resize copies everything.O(1)O(n)
Insert or delete in the middleLater items shift one slot.O(n)O(n)
Remove from the endO(1)O(1)
Search (unsorted)O(log n) with binary search if sorted.O(n)O(n)

Space: O(n), with up to 2× capacity headroom

In practice, dynamic arrays beat linked lists for most workloads, even with some middle inserts, because contiguous memory is much friendlier to CPU caches.

TypeScript implementation

A dynamic array that doubles its capacity when full, written on top of a fixed-size typed array to show what the runtime does for you.

dynamic-array.ts
// A dynamic array on top of a fixed-size Float64Array, doubling its capacity
// when full. JavaScript's Array does this for you; here you can see the cost.

export class DynamicArray {
  private data: Float64Array;
  private length = 0;
  copies = 0; // how many elements were copied by resizes

  constructor(capacity = 4) {
    this.data = new Float64Array(capacity);
  }

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

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

  get(i: number): number {
    if (i < 0 || i >= this.length) throw new RangeError(`index ${i} out of bounds`);
    return this.data[i];
  }

  push(value: number): void {
    if (this.length === this.data.length) this.grow();
    this.data[this.length++] = value;
  }

  pop(): number | undefined {
    return this.length ? this.data[--this.length] : undefined;
  }

  /** O(n): every later element shifts one slot to the right. */
  insertAt(i: number, value: number): void {
    if (this.length === this.data.length) this.grow();
    this.data.copyWithin(i + 1, i, this.length);
    this.data[i] = value;
    this.length++;
  }

  private grow(): void {
    const bigger = new Float64Array(this.data.length * 2);
    bigger.set(this.data);
    this.copies += this.data.length;
    this.data = bigger;
  }

  toArray(): number[] {
    return Array.from(this.data.subarray(0, this.length));
  }
}

export function demo(): string[] {
  const a = new DynamicArray(4);
  for (const v of [7, 3, 9, 4]) a.push(v);
  const lines = [`[${a.toArray().join(", ")}] size ${a.size}, capacity ${a.capacity}`];
  a.push(1); // full: doubles to 8
  a.insertAt(1, 5);
  lines.push(`after push and insertAt(1): [${a.toArray().join(", ")}] capacity ${a.capacity}`);

  const big = new DynamicArray(1);
  for (let i = 0; i < 1_000_000; i++) big.push(i);
  lines.push(`1 000 000 pushes caused ${big.copies.toLocaleString("en")} element copies: about ${(big.copies / big.size).toFixed(2)} per push (amortized O(1))`);
  return lines;
}

When to use it

Use it when

  • The default list for most code: ordered items, mostly appended and read by index or in order.
  • You need fast random access, or to sort and binary search.
  • Performance-sensitive loops over many items, where cache friendliness matters.

Avoid it when

  • You insert and remove often at the front: use a deque or ring buffer.
  • You need fast lookup by key: use a hash table.
  • You constantly insert in the middle of very large sequences and hold references into them: a linked list or balanced tree may fit better.

Pitfalls

  • Inserting at the front in a loop (unshift in JavaScript), which makes the whole loop O(n²).
  • Holding references to elements in languages where a resize moves the memory (C++ iterators, Go slices), which then point to stale data.
  • Pre-allocating far too much, or never shrinking after removing most items.
  • Off-by-one errors at the boundaries: valid indexes are 0 to length − 1.

Alternatives

Linked list

Choose it when you insert or remove in the middle through references you already hold, and never need random access.

Ring buffer

Choose it when you add at one end and remove at the other with a fixed capacity.

Hash table

Choose it when you look items up by key rather than by position.