Dynamic Array

Back Home

Category

Category: Sequence types

Topics

Topics: amortized analysis, resizing, contiguous storage, memory management

Definition

A resizable array that automatically grows or shrinks as elements are added or removed, providing O(1) amortized append operations.

Use cases

Attributes

Common operations

Operation Time Complexity Description
Access O(1) Get element at index
Search O(n) Linear scan for value
Append O(1) amortized Add to end, may trigger resize
Insert O(n) Shift elements right
Delete O(n) Shift elements left
Resize O(n) Copy all elements to new array

In code

# Python list IS a dynamic array
nums = []

# Append - O(1) amortized
for i in range(10):
    nums.append(i)

# Insert at position - O(n)
nums.insert(0, -1)

# Pop from end - O(1)
nums.pop()

# Pop from position - O(n)
nums.pop(0)

# Simple dynamic array implementation
class DynamicArray:
    def __init__(self):
        self._capacity = 1
        self._size = 0
        self._arr = [None] * self._capacity

    def append(self, item):
        if self._size == self._capacity:
            self._resize(2 * self._capacity)
        self._arr[self._size] = item
        self._size += 1

    def _resize(self, new_cap):
        new_arr = [None] * new_cap
        for i in range(self._size):
            new_arr[i] = self._arr[i]
        self._arr = new_arr
        self._capacity = new_cap

Time complexity

Amortized analysis: With 2x growth factor, the amortized cost per append is O(1) because expensive resizes happen exponentially less frequently.

Space complexity

O(n) for elements, but may use up to 2n space due to pre-allocated capacity. No auxiliary space during normal operations; O(n) temporary during resize.

Trade-offs

Pros:

Cons:

Variants

When to use vs avoid