Sub topic 16
When to Use a Dynamic Array
This chapter assumes you know how a dynamic array tracks size and capacity, why append is amortized O(1), and the basics of Big-O notation. The goal is to turn that knowledge into a decision: given a workload, should you reach for an array-based structure or something else?
What a dynamic array does well
A dynamic array stores elements in one contiguous block. That layout gives it three strengths:
- Index access in O(1). The address of element
iis the start address plusitimes the element size. - Cheap appends and pops at the end. Append is amortized O(1) and pop is O(1).
- Fast traversal. Neighbouring elements share cache lines, so a scan runs close to memory speed.
What it does poorly
Its weaknesses come from the same layout:
- Insertion or deletion near the front or middle costs O(n), because later elements must shift.
- Occasional resizes cost O(n) for a single append. The average is fine, but one call can be slow.
- Spare capacity wastes memory. With a growth factor of 2, up to half the block can be unused.
- Searching an unsorted array costs O(n).
Comparing the options
| Operation | Dynamic array | Linked list | Hash table |
|---|---|---|---|
| Access by index | O(1) | O(n) | Not supported |
| Append at end | Amortized O(1) | O(1) with a tail pointer | Amortized O(1) |
| Insert at front | O(n) | O(1) | Not applicable |
| Insert in middle | O(n) | O(1) once you hold the node, O(n) to find it | Not applicable |
| Search by value | O(n) | O(n) | Expected O(1) |
| Memory locality | Excellent | Poor | Moderate |
A linked list wins on paper for middle insertion, but you usually need O(n) steps to reach the position first. Its nodes are also scattered in memory, so the constant factors are worse in practice.
A decision procedure
Ask these questions in order:
- Do you read by position or scan everything often? Choose a dynamic array.
- Do you mostly add and remove at the end? Choose a dynamic array, which also works as a stack.
- Do you add and remove at both ends? Choose a deque, which is built for that.
- Do you look up by key or test membership often? Choose a hash table or a set.
- Do you need sorted order with frequent inserts? Consider a balanced tree or a heap.
- Do you hold node references and splice constantly? A linked list may fit.
Seeing the cost of a bad fit
Removing from the front of a Python list shifts every remaining element. A deque removes from the front in O(1). The program below compares the two.
import time
from collections import deque
n = 100_000
as_list = list(range(n))
as_deque = deque(range(n))
start = time.perf_counter()
while as_list:
as_list.pop(0)
list_time = time.perf_counter() - start
start = time.perf_counter()
while as_deque:
as_deque.popleft()
deque_time = time.perf_counter() - start
print(f"list pop(0): {list_time:.3f}s")
print(f"deque popleft: {deque_time:.3f}s")The list version is quadratic overall, so it is far slower. Exact times vary by machine.
Summary of criteria
Pick a dynamic array when access by position, appends at the end, and fast scans dominate. Move to another structure when the dominant operation is front or middle insertion, key lookup, or ordered access.
Exercise
A program reads a stream of tasks, adds each to the end of a collection, and processes them from the front in arrival order. Tasks are never inserted elsewhere. Which structure fits best, and why is a plain dynamic array a poor choice?
Show answer
A deque (or queue). Processing from the front with a dynamic array requires removing element 0, which shifts every remaining element and costs O(n) per removal. A deque supports O(1) removal at the front and O(1) append at the end.
Exercise
You must build a list of 1,000,000 numbers by appending in a loop, and the final size is known. How can you reduce the cost of resizing?
Show answer
Reserve or preallocate capacity for 1,000,000 elements before the loop, for example with reserve in C++ or an initial capacity in Java's ArrayList. The array then never needs to resize while you append.