Arrays & Dynamic Arrays
Contiguous memory, constant-time indexing and the doubling trick.
Reading a[i] is the one data-structure operation a processor performs natively: one address computation and one load. Arrays have a single weakness, a fixed size, and the doubling trick turns it into a guarantee: appends cost fewer than element writes in total. The bugs live at the edges: off by one, out of bounds, and pointers into a block that has just moved.
What you’ll learn
- Compute the address of an element of a one- or two-dimensional array in row-major and column-major order, and choose the loop order that follows memory.
- Prove that growing by a constant factor copies fewer than elements per append, amortized, while growing by a constant amount costs per append.
- Weigh growth factors (copies against unused space), and shrink a dynamic array without thrashing.
- Rotate, reverse and delete in place, and avoid dangling references after a reallocation and quadratic front insertions.
- Recognize array problems in a statement, together with the bugs that come with them.
Addresses in one and two dimensions
A static array has a length fixed when it is created: elements of bytes each, in one block of contiguous memory, with valid indices to . Element lives at , so access by index costs in the worst case. Whether an index outside is caught depends on the language: Python and Java raise an exception, while in C and C++ a[n] silently reads or overwrites whatever lies next in memory, which is undefined behavior.
A two-dimensional array is stored as one block too, in one of two orders:
A array of 8-byte doubles is stored in row-major order, starting at address 0. At which address does start?
Show the answer
24056
Three full rows of 1000 elements come first, then 7 more elements: . In column-major order the same element would sit at .
The order decides which loop should be innermost. In a row-major array, for r: for c: total += a[r][c] walks through consecutive addresses, while swapping the two loops jumps bytes at every step. Both versions do the same additions, yet on a matrix of doubles the column-by-column loop ran 3 to 4 times slower in our test, because every jump lands on a different cache line. The Optimal lesson The Memory Hierarchy & Locality explains why, and how to exploit it.
Python's list of lists is a third layout: an array of pointers to separately allocated rows, a jagged array. Its rows may have different lengths, but they are not contiguous with one another.
Dynamic arrays: geometric growth
A dynamic array keeps a block of some capacity and a size . Appending writes slot when . When , it first allocates a block of capacity for a growth factor , copies the elements and frees the old block. Count the cost in element writes: 1 for the new element plus 1 per element copied.
Let the resizes happen at capacities ; the resize at capacity copies elements. Each capacity is at least times the previous one, so counting backward from the last:
The last resize found the array full at size while it still had to make room for at least one more append, so . Sum the geometric series:
Add the writes of the new elements. For the bound is , for it is :
Growing by a constant amount instead resizes at sizes , about times, and the -th resize copies about elements:
The bound is tight: just after a resize the running average comes close to it (for it reaches 2.9985 at ). The accounting method reaches the same constant in one line: under doubling, charge 3 per append and leave 2 as credit on the new element; at the next resize, the elements added since the last one pay for copying themselves and an equal number of older elements. The lesson Amortized Analysis develops the aggregate, accounting and potential methods in full.
Choosing the growth factor, and shrinking
| Growth factor | Copies per append, amortized: fewer than | Unused right after a resize: up to | Resizes from 1 to elements |
|---|---|---|---|
about 1.125: CPython's list | 9 | 11% | 86 (its added constant speeds up the start) |
1.5: MSVC's std::vector, Java's ArrayList | 3 | 33% | about 34 |
2: std::vector in libstdc++ and libc++ | 2 | 50% | 20 |
So a smaller factor copies more and wastes less in the worst case, but not at every size. At 100 elements a ×1.5 array holds 140 slots and a ×2 array only 128, because the two sequences of capacities, and , cross each other.
A subtler argument concerns reusing memory. Suppose an idealized allocator places blocks side by side and merges the blocks you free. When the array grows from block to block , block must stay alive during the copy, so the new block fits into old memory only if blocks together are at least as large as block .
With capacities , the freed blocks form a geometric series, and reuse needs
Multiply by and collect the powers of :
This can hold for some only if , that is, if is below the golden ratio. For it fails forever: the blocks sum to , one slot short of the next block, even counting the block just abandoned. For it first holds at ; with the rounded capacities above, the first chance comes at the growth from 12 to 18 slots, when the freed blocks hold .
This is one argument for factors such as 1.5. Real allocators round sizes, keep separate pools for different sizes and can sometimes extend a block in place, so treat it as a tendency, not a law.
Shrinking. A dynamic array that only grows keeps its peak capacity forever. Halving it when it becomes half full is a trap: alternate one append and one pop at that boundary, and every operation copies half the array. Halving when it is a quarter full leaves the halved array half full, so operations must pass before the next resize, and appends and pops in any mix stay amortized (proved in The Potential Method in Depth). C++'s std::vector and Java's ArrayList never shrink on their own (shrink_to_fit and trimToSize exist for that); CPython reallocates a list once it drops below half of its allocation.
One dynamic array grows by ×1.5 and another by ×2. Which statement is true?
- The ×1.5 array uses less memory than the ×2 array at every size
- Both copy the same number of elements in total, since both are amortized
- Over many appends the ×1.5 array copies more elements, but it never leaves more than about a third of its block unused, while the ×2 array can leave half unused
- The ×1.5 array is not amortized, because a block of 1.5 times the capacity cannot always be allocated
Show the answer
C. Over many appends the ×1.5 array copies more elements, but it never leaves more than about a third of its block unused, while the ×2 array can leave half unused
The copy bound is per append, 3 for ×1.5 against 2 for ×2, and the worst unused fraction is about , a third against a half. Neither array is smaller at every size: at 100 elements the ×1.5 array has 140 slots and the ×2 array 128.
Working in place
| Operation on a dynamic array of elements | Cost |
|---|---|
| read or write | worst case |
| append; pop from the end | amortized; for an append that resizes |
| insert or delete at index | : the elements after shift |
| insert or delete at the front | |
| delete at index when order does not matter | : move the last element into slot , then pop |
| find a value | ; by binary search if the array is sorted |
| reverse; rotate | time, extra space |
def reverse(a, lo, hi): # reverse a[lo..hi], both ends inclusive
while lo < hi:
a[lo], a[hi] = a[hi], a[lo]
lo, hi = lo + 1, hi - 1
def rotate_right(a, k): # in place: O(n) time, O(1) extra space
n = len(a)
if n == 0:
return
k %= n
reverse(a, 0, n - 1) # [1,2,3,4,5,6,7], k = 3 -> [7,6,5,4,3,2,1]
reverse(a, 0, k - 1) # -> [5,6,7,4,3,2,1]
reverse(a, k, n - 1) # -> [5,6,7,1,2,3,4]Rotation by three reversals: about swaps in all. The slicing expression a[n-k:] + a[:n-k] is shorter, but it builds a new list with extra space.
Split the array as with . Rotating right by must produce . Reversing a concatenation reverses the order of the parts and each part:
After the first reversal, the first elements are and the rest are . Reversing each part on its own undoes the inner reversals:
Front insertion is quadratic. a.insert(0, x) in a loop of iterations shifts elements. Append instead and reverse once at the end, or use collections.deque, whose appendleft is .
Reallocation moves the elements. A pointer, reference or iterator into a C++ std::vector points into its current block, and the next reallocation frees that block:
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3};
int& first = v[0]; // a reference into the current block
v.push_back(4); // if size() == capacity(), this reallocates...
// int x = first; // ...and reading 'first' would be undefined behavior
std::vector<int> w;
w.reserve(1000); // one allocation up front: capacity() >= 1000
for (int i = 0; i < 1000; i++)
w.push_back(i); // no reallocation, so references into w stay valid
}A reallocation invalidates every pointer, reference and iterator to the vector's elements; without one, those before the insertion point stay valid. Call reserve when you know the final size: it also saves the copies.
Recognizing it
The signals in a problem statement:
- access by position: "the -th", "index", "rank", "the cell in row and column ";
- "in place", " extra space", "do not allocate another array": swaps, reversals and write pointers;
- contiguous pieces such as subarrays, windows and prefixes, which the techniques of the next topic (two pointers, sliding windows, prefix sums) all work on;
- large , around to , with tight limits on time and memory, where contiguous storage and sequential scans win by large constant factors.
| Problem (in brief) | Key idea | Cost |
|---|---|---|
| Rotate an array right by in place | three reversals, with reduced modulo | time, space |
| Move all zeros to the end, keeping the order of the other elements | a write pointer : copy each nonzero to and advance , then fill the rest with zeros | , |
| Rotate an matrix by 90° clockwise in place | transpose (swap with ), then reverse each row | , |
| List the cells of a matrix in spiral order | four boundaries (top, bottom, left, right) that move inward after each side is walked | |
| Delete arbitrary elements from a collection whose order does not matter | swap with the last element, then pop | each |
A game keeps up to live particles. Every frame it adds new particles, removes dead ones (by their index), and updates all of them, in any order. Which approach makes each addition and each removal ?
- A singly linked list, because unlinking a node is
- A dynamic array that moves the last particle into the dead one's slot, then pops
- A dynamic array, deleting with
del a[i] - A sorted array, ordered by particle id
Show the answer
B. A dynamic array that moves the last particle into the dead one's slot, then pops
Order does not matter, so the hole left by a dead particle can be filled by the last one: one copy and one pop, . Additions are amortized appends, and the update loop scans contiguous memory.
Key takeaways
- lives at , and at in row-major order (C, C++, NumPy) or at in column-major order (Fortran, MATLAB, Julia, R); make the loop over neighboring addresses the innermost one.
- Growing by a factor copies fewer than elements per append, so appends are amortized, though a resizing append costs ; growing by a constant amount costs amortized.
- Smaller factors copy more but waste at most about of the block; libraries use about 1.125 (CPython), 1.5 (MSVC, Java) or 2 (libstdc++, libc++), as of 2025. Shrink at a quarter full, never at half.
- Inserting or deleting away from the end shifts elements, ; swap-remove is when order does not matter, and three reversals rotate in place.
- The classic bugs are off by one, out of bounds, dangling references after a reallocation, quadratic front insertion, aliased rows and 32-bit index overflow.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A dynamic array triples its capacity whenever it is full, starting from capacity 1. Over any sequence of appends, at most about how many elements are copied per append, on average?
- 3
- 1.5
- 2
- It grows with , like
Show the answer
B. 1.5
The copies form a geometric series, with , so fewer than copies in all: with . A larger factor copies less, but it can leave up to two thirds of its block unused.
A library grows its arrays by 4,096 slots whenever they are full. How does the total cost of appends grow for large ?
- : 4,096 slots is so much room that resizes are rare
- : there are about resizes, and the -th copies about elements
- , because each resize is spread over 4,096 appends
Show the answer
C. : there are about resizes, and the -th copies about elements
The copies total about : quadratic, with a small constant. For that is about copies, against fewer than for doubling.
A Fortran program stores a matrix (3 rows, 4 columns) of 8-byte numbers in column-major order, starting at address 0. With 0-based indices, at which address is the element in row 2, column 1?
- 40
- 72
- 48
- 24
Show the answer
A. 40
In column-major order whole columns come first: column 0 holds 3 elements, then come rows 0, 1 and 2 of column 1. The address is .
In C++, you take int* p = &v[0]; and then call v.push_back(x) on a vector whose size equals its capacity. What is true afterwards?
pstill points tov[0], sincepush_backonly adds at the endpnow points to the new last element- The vector refuses to grow while a pointer into it exists
ppoints into the freed old block, and reading*pis undefined behavior
Show the answer
D. p points into the freed old block, and reading *p is undefined behavior
The vector was full, so push_back allocated a larger block, moved the elements and freed the old block, while p still holds the old address. Take pointers again after any operation that may reallocate, or reserve enough capacity first.
Why should a dynamic array that doubles when full halve its capacity when it becomes a quarter full, rather than half full?
- Halving at a quarter saves more memory
- After halving at a quarter the array is half full, so many operations must pass before the next resize; halving at half allows an append–pop sequence that resizes on every operation
- Halving at half would make each pop cost
- It makes no difference to the amortized cost
Show the answer
B. After halving at a quarter the array is half full, so many operations must pass before the next resize; halving at half allows an append–pop sequence that resizes on every operation
At the half-full threshold, an array of capacity holding elements halves on a pop and doubles again on the next append, and so on: every operation copies about elements. Halving at a quarter leaves a gap of operations between resizes, which pays for each copy: amortized for any mix.
Go deeper
- The Memory Hierarchy & Locality · Caches, cache lines and why scanning an array beats chasing pointers.
- External-Memory & Cache-Oblivious Algorithms · The I/O model, B-trees, and algorithms that are fast on every level of cache.
- Bit Vectors & Succinct Data Structures · Rank and select in a few extra bits, near the information-theoretic minimum.
Further reading
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), sections 10.1 (arrays and matrices) and 16.4 (dynamic tables).
- R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), section 1.3 (resizing arrays).
- J. Bentley, Programming Pearls, 2nd ed. (Addison-Wesley, 2000), column 2 (rotating a vector by reversals).
- D. E. Knuth, The Art of Computer Programming, Vol. 1: Fundamental Algorithms, 3rd ed. (Addison-Wesley, 1997), section 2.2.2 (sequential allocation).