Mental model
A plain array is one block of memory with room for a fixed number of elements. Because the
elements sit side by side, the address of element i is start + i × elementSize, so reading or
writing any index takes the same, constant time. The price is that the block cannot get longer:
the memory right after it may already belong to something else.
A dynamic array wraps such a block (the buffer) and tracks two numbers:
- size (
Count,len,size()): how many elements you stored. - capacity: how many slots the buffer has. Slots from
sizetocapacity - 1exist in memory but hold no element of yours.
As long as size < capacity, appending just writes into the next free slot. When the buffer is
full, the array allocates a larger buffer, copies every element across, and drops the old
buffer. That single append costs O(n). The lab above lets you watch both buffers exist at the
same time while the copy runs.
The teaching implementation used in the lab and in the code below doubles the capacity
(0 → 1 → 2 → 4 → 8 …) and never shrinks. Real runtimes use different numbers; the
runtime notes list what each one does.
Operation costs
| Operation | Time | Why |
|---|---|---|
get(i), set(i, v) |
O(1) | Index arithmetic finds the slot directly. |
append(v) with spare capacity |
O(1) | One write into slot size. |
append(v) when full |
O(n) | Allocate, then copy all n elements. |
append(v), averaged over a sequence |
amortized O(1) | Resizes are rare enough; derived below. |
insert(i, v) |
O(n − i), plus a resize if full | Every element from i on moves one slot right. |
removeAt(i) |
O(n − i) | Every element after i moves one slot left. |
| remove the last element | O(1) | Nothing needs to move. |
| search by value | O(n) | No ordering to exploit; see linear search. |
Auxiliary space for a resize is the new buffer: O(n) extra memory while both buffers are alive.
Amortized is not average. "Average case" averages over possible inputs and can be unlucky. "Amortized" is a guarantee about every sequence of operations: the total cost of any n appends is O(n), even though some individual appends cost O(n). Nothing probabilistic is involved.
Why append is amortized O(1)
Count element writes, as the lab's Element writes metric does. Start empty with the doubling rule and append n elements.
-
Each append writes its own element once: n writes in total.
-
A resize happens when size reaches 1, 2, 4, 8, …, and copies that many elements. The last resize copies fewer than n elements, the one before fewer than n/2, and so on:
copies < n + n/2 + n/4 + … < 2n
So n appends cost fewer than n + 2n = 3n writes: O(n) in total, a constant per append on average. Run the Doubling from empty preset and watch the average writes per append stay below 3 in the cost chart.
The same argument works for any growth factor g > 1: the copies form a geometric series that sums to less than n · g / (g − 1). A factor of 2 gives under 2n copies; 1.5 gives under 3n. Smaller factors copy more often but waste less memory, which is why runtimes pick different numbers.
Growing by a constant amount does not work. If each resize adds a fixed k slots, resizes happen every k appends and copy k, 2k, 3k, … elements. That is about n²/(2k) copies for n appends: O(n²) total, O(n) per append. Geometric growth is what makes append cheap.
Insert and remove move data
Inserting at index i must keep the order, so the elements at i … size-1 each move one slot to
the right, starting from the end so nothing is overwritten before it is copied. Removing at i
moves the elements after it one slot left and then clears the last slot. The lab draws a faded
leftover copy in the slot a shift has just read from: the value is still in memory until the next
write overwrites it, which is exactly why removeAt clears the vacated slot (otherwise a
garbage-collected runtime would keep that object alive).
Inserting or removing at the end moves nothing. Inserting at the front moves everything. If your algorithm repeatedly inserts or removes at the front, a dynamic array is the wrong structure; a deque or a linked structure is the usual answer (covered in later modules).
Built-in dynamic arrays
All four languages ship a dynamic array. The guarantees below come from the language or library specification; growth numbers are implementation details observed on the toolchains this lab is tested with, and may differ on other versions or runtimes.
C# List<T> |
Python list |
Java ArrayList<E> |
C++ std::vector<T> |
|
|---|---|---|---|---|
| Append | Add(x) |
append(x) |
add(x) |
push_back(x) / emplace_back(...) |
| Insert | Insert(i, x) |
insert(i, x) |
add(i, x) |
insert(it, x) |
| Remove at | RemoveAt(i) (no return) |
pop(i) (returns) |
remove(int i) (returns) |
erase(it) |
| Read capacity | Capacity |
not exposed | not exposed | capacity() |
| Reserve | EnsureCapacity(n), Capacity = n |
none | ensureCapacity(n) |
reserve(n) |
| Shrink | TrimExcess() |
automatic | trimToSize() |
shrink_to_fit() (non-binding) |
| Append guarantee | O(1) when Count < Capacity, otherwise O(n) (docs) | amortized O(1) (CPython) | "amortized constant time" (Javadoc) | amortized constant (standard) |
| Observed growth | 0 → 4, then doubles (.NET 10) | 4, 8, 16, 24, 32, … ≈ 1.125× (CPython 3.14) | 0 → 10, then ≈ 1.5× (OpenJDK 25) | doubles in libstdc++ (GCC 15); MSVC's STL grows 1.5× per its source |
| Out of range | ArgumentOutOfRangeException |
IndexError |
IndexOutOfBoundsException |
operator[]: undefined behaviour; at(): std::out_of_range |
Things that differ in ways that matter:
- Python indices can be negative (
items[-1]is the last element) andpop()without an argument removes the last element in O(1). CPython's list also shrinks its buffer when it becomes much emptier; the other three never shrink unless you ask. Python integers are arbitrary precision, so alistof ints stores references to integer objects, not the numbers themselves. - Java's
ArrayListstores references. AnArrayList<Integer>holds pointers to boxedIntegerobjects; the element data is not contiguous even though the references are. C#'sList<int>and C++'sstd::vector<int>store the values themselves contiguously. - C++ reallocation invalidates everything. When a
std::vectorgrows, every pointer, reference and iterator into it becomes invalid; an insert or erase without reallocation invalidates those at or after the position. Keeping&v[0]across apush_backis a classic bug. The C++ version below moves elements withstd::moveinstead of copying, which is cheaper for types that own resources but still O(n) moves. - Modifying while iterating throws
InvalidOperationExceptionin C# (List's enumerator is versioned) and usuallyConcurrentModificationExceptionin Java (fail-fast, best effort, not guaranteed). In C++ it is undefined behaviour once iterators are invalidated. Python does not detect it; elements are silently skipped or revisited. - Pre-sizing helps. If you know you will add 10,000 elements,
EnsureCapacity/reserve/ensureCapacity(ornew List<T>(10000),new ArrayList<>(10000)) performs one allocation instead of a dozen copies. It changes the constant, not the complexity.
The teaching implementation
The code tabs in the lab, and the full listings below, are one implementation in four languages with
the same growth rule and the same behaviour, checked by one shared set of test cases. Two deliberate
simplifications: elements are copied in a plain loop (real libraries use Array.Copy,
System.arraycopy, memmove or move construction, still O(n)), and the C++ version
default-constructs its buffer slots, so T must be default-constructible. std::vector avoids that by
constructing elements in raw, uninitialised storage.
Common mistakes
- Confusing size with capacity. A
List<T>created with capacity 100 still hasCount == 0;list[5]throws. Capacity is room, not content. The Size is not capacity preset shows this. - Calling one resize "O(1)" or "amortized O(n)". A resizing append is O(n); the amortized bound is O(1) per append over a sequence.
- Inserting at the front in a loop. n inserts at index 0 cost 0 + 1 + … + (n − 1) shifts: O(n²). Append and reverse once, or use a deque.
- Removing while looping forward by index. After
removeAt(i)the next element is now ati, soi++skips it. Iterate backwards or build a new list. - Holding a C++ pointer, reference or iterator across
push_back. - Assuming every runtime doubles. Code should not depend on a particular growth factor.
Edge cases
- Capacity 0. The first append must allocate (the teaching version grows 0 → 1).
- Insert at index
sizeis valid and behaves like append, including the resize when full. - Remove the last element shifts nothing but still clears the slot.
- Index equal to size is out of range for
get,setandremoveAteven when the buffer has a slot there. - Huge sizes. Real implementations cap capacity (e.g. near
int.MaxValuein .NET and Java) and must avoid overflow when computing2 × capacity; the teaching version does not handle this.
Worked practice
1. Starting from capacity 0 with the doubling rule, how many element copies do 9 appends cause, and what is the final capacity?
Resizes happen on appends 1, 2, 3, 5 and 9 (when size reaches 0, 1, 2, 4 and 8) and copy 0 + 1 + 2 + 4 + 8 = 15 elements. The final capacity is 16. Total writes: 9 own writes + 15 copies = 24 < 3 × 9 = 27.
2. A list holds 1,000 elements. Which is cheaper: removeAt(0) or removeAt(999)? By how much, in shifts?
removeAt(999) removes the last element and shifts nothing. removeAt(0) shifts the other 999 elements left.
3. A growth rule adds 100 slots each time. Roughly how many copies do 100,000 appends cause?
Resizes copy 100, 200, …, about 100,000 elements: about 1,000 resizes averaging 50,000 copies, so roughly 50 million copies (n²/(2k) with k = 100). With doubling the total stays under 200,000.
4. Why does the teaching removeAt set the vacated slot to null / None / default?
After the shift, the last used slot still holds a copy of a reference that now also lives one slot to the left (or the
removed element itself, when removing the last one). In a garbage-collected language that stale reference would keep the
object alive for as long as the slot is not overwritten. Clearing it removes the reference. In C++ the assignment
T{} releases whatever that slot still owns.
Summary
- A dynamic array is a fixed buffer plus
sizeandcapacity. Index access is O(1). - A full buffer is replaced by a larger one: O(n) for that append.
- Geometric growth makes n appends cost O(n) in total: amortized O(1) per append. Constant growth makes them O(n²).
- Insert and remove are O(n − i) because they shift; the end of the array is cheap, the front is expensive.
- Each language guarantees the complexity, not the growth factor. Check the docs before relying on capacity details, and in C++ remember that reallocation invalidates pointers and iterators.