Simple Algorithm
Algorithms & Data Structures · Optimized · 20 min

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: nn appends cost fewer than 3n3n 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 g>1g > 1 copies fewer than g/(g−1)g/(g-1) elements per append, amortized, while growing by a constant amount costs Θ(n)\Theta(n) 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: nn elements of ss bytes each, in one block of contiguous memory, with valid indices 00 to n−1n - 1. Element a[i]a[i] lives at base+i⋅s\text{base} + i \cdot s, so access by index costs O(1)O(1) in the worst case. Whether an index outside [0,n)[0, n) 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 R×CR \times C array is stored as one block too, in one of two orders:

base+(r⋅C+c) s⏟row-major: C, C++, NumPy by defaultbase+(c⋅R+r) s⏟column-major: Fortran, MATLAB, Julia, R\underbrace{\text{base} + (r \cdot C + c)\, s}_{\text{row-major: C, C++, NumPy by default}} \qquad\qquad \underbrace{\text{base} + (c \cdot R + r)\, s}_{\text{column-major: Fortran, MATLAB, Julia, R}}
The address of a[r][c]a[r][c], with 0≤r<R0 \le r < R and 0≤c<C0 \le c < C. In row-major order the rows lie one after another, so a[r][c]a[r][c] and a[r][c+1]a[r][c+1] are neighbors; in column-major order the columns do, so a[r][c]a[r][c] and a[r+1][c]a[r+1][c] are.
Predict before you look

A 1000×10001000 \times 1000 array of 8-byte doubles is stored in row-major order, starting at address 0. At which address does a[3][7]a[3][7] start?

Show the answer

24056

Three full rows of 1000 elements come first, then 7 more elements: (3⋅1000+7)⋅8=24,056(3 \cdot 1000 + 7) \cdot 8 = 24{,}056. In column-major order the same element would sit at (7⋅1000+3)⋅8=56,024(7 \cdot 1000 + 3) \cdot 8 = 56{,}024.

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 C⋅sC \cdot s bytes at every step. Both versions do the same RCRC additions, yet on a 4096×40964096 \times 4096 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 cc and a size n≤cn \le c. Appending writes slot nn when n<cn < c. When n=cn = c, it first allocates a block of capacity g⋅cg \cdot c for a growth factor g>1g > 1, copies the nn elements and frees the old block. Count the cost in element writes: 1 for the new element plus 1 per element copied.

DerivationProof by the aggregate method
  1. ck−i  ≤  ck/g i(i=0,1,…,k−1)c_{k-i} \;\le\; c_k / g^{\,i} \qquad (i = 0, 1, \dots, k-1)

    Let the resizes happen at capacities c1<c2<⋯<ckc_1 < c_2 < \dots < c_k; the resize at capacity cjc_j copies cjc_j elements. Each capacity is at least gg times the previous one, so counting backward from the last:

  2. ∑j=1kcj  ≤  ck∑i≥0g−i  =  ck gg−1  <  gg−1 n\sum_{j=1}^{k} c_j \;\le\; c_k \sum_{i \ge 0} g^{-i} \;=\; c_k\,\frac{g}{g-1} \;<\; \frac{g}{g-1}\, n

    The last resize found the array full at size ckc_k while it still had to make room for at least one more append, so ck≤n−1<nc_k \le n - 1 < n. Sum the geometric series:

  3. total  <  (1+gg−1) n⟹amortized cost  <  1+gg−1  =  O(1)\text{total} \;<\; \Big(1 + \frac{g}{g-1}\Big)\, n \qquad\Longrightarrow\qquad \text{amortized cost} \;<\; 1 + \frac{g}{g-1} \;=\; O(1)

    Add the nn writes of the new elements. For g=2g = 2 the bound is 3n3n, for g=1.5g = 1.5 it is 4n4n:

  4. ∑j=1n/kjk  ≈  n22k  =  Θ(n2)⟹Θ(n) amortized per append\sum_{j=1}^{n/k} jk \;\approx\; \frac{n^2}{2k} \;=\; \Theta(n^2) \qquad\Longrightarrow\qquad \Theta(n) \text{ amortized per append}

    Growing by a constant amount kk instead resizes at sizes 1,1+k,1+2k,…1, 1 + k, 1 + 2k, \dots, about n/kn/k times, and the jj-th resize copies about jkjk elements:

The bound is tight: just after a resize the running average comes close to it (for g=2g = 2 it reaches 2.9985 at n=2049n = 2049). 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 ggCopies per append, amortized: fewer thanUnused right after a resize: up toResizes from 1 to 10610^6 elements
about 1.125: CPython's list911%86 (its added constant speeds up the start)
1.5: MSVC's std::vector, Java's ArrayList333%about 34
2: std::vector in libstdc++ and libc++250%20
Copies: g/(g−1)g/(g-1). Unused space: a block that has just grown from cc to gcgc slots holds c+1c + 1 elements, so close to 1−1/g1 - 1/g of it is empty. Library choices as of 2025; CPython's rule is "new size, plus an eighth of it, plus 6, rounded down to a multiple of 4".

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, 1,2,3,5,8,12,18,27,41,62,93,140,…1, 2, 3, 5, 8, 12, 18, 27, 41, 62, 93, 140, \dots and 1,2,4,…,1281, 2, 4, \dots, 128, 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 kk to block k+1k + 1, block kk must stay alive during the copy, so the new block fits into old memory only if blocks 0,…,k−10, \dots, k - 1 together are at least as large as block k+1k + 1.

DerivationFactors at or above the golden ratio never reuse memory
  1. ∑j=0k−1gj  =  gk−1g−1  ≥  gk+1\sum_{j=0}^{k-1} g^j \;=\; \frac{g^k - 1}{g - 1} \;\ge\; g^{k+1}

    With capacities g0,g1,g2,…g^0, g^1, g^2, \dots, the freed blocks form a geometric series, and reuse needs

  2. gk (1+g−g2)  ≥  1g^k\,\big(1 + g - g^2\big) \;\ge\; 1

    Multiply by g−1>0g - 1 > 0 and collect the powers of gg:

  3. 1+g−g2>0  ⟺  g  <  φ=1+52≈1.6181 + g - g^2 > 0 \iff g \;<\; \varphi = \frac{1 + \sqrt5}{2} \approx 1.618

    This can hold for some kk only if 1+g−g2>01 + g - g^2 > 0, that is, if gg is below the golden ratio. For g=2g = 2 it fails forever: the blocks 1,2,…,2k1, 2, \dots, 2^k sum to 2k+1−12^{k+1} - 1, one slot short of the next block, even counting the block just abandoned. For g=1.5g = 1.5 it first holds at k=4k = 4; with the rounded capacities above, the first chance comes at the growth from 12 to 18 slots, when the freed blocks hold 1+2+3+5+8=191 + 2 + 3 + 5 + 8 = 19.

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 Θ(c)\Theta(c) operations must pass before the next resize, and appends and pops in any mix stay O(1)O(1) 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.

Check your understanding

One dynamic array grows by ×1.5 and another by ×2. Which statement is true?

  1. The ×1.5 array uses less memory than the ×2 array at every size
  2. Both copy the same number of elements in total, since both are O(1)O(1) amortized
  3. 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
  4. The ×1.5 array is not O(1)O(1) 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 g/(g−1)g/(g-1) per append, 3 for ×1.5 against 2 for ×2, and the worst unused fraction is about 1−1/g1 - 1/g, 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 nn elementsCost
read or write a[i]a[i]O(1)O(1) worst case
append; pop from the endO(1)O(1) amortized; Θ(n)\Theta(n) for an append that resizes
insert or delete at index iiΘ(n−i)\Theta(n - i): the elements after ii shift
insert or delete at the frontΘ(n)\Theta(n)
delete at index ii when order does not matterO(1)O(1): move the last element into slot ii, then pop
find a valueO(n)O(n); O(log⁡n)O(\log n) by binary search if the array is sorted
reverse; rotateO(n)O(n) time, O(1)O(1) extra space
python
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 nn swaps in all. The slicing expression a[n-k:] + a[:n-k] is shorter, but it builds a new list with O(n)O(n) extra space.

DerivationWhy three reversals rotate
  1. (XY)R  =  YRXR(XY)^R \;=\; Y^R X^R

    Split the array as a=XYa = XY with ∣Y∣=k\abs{Y} = k. Rotating right by kk must produce YXYX. Reversing a concatenation reverses the order of the parts and each part:

  2. (YR)R(XR)R  =  YX\big(Y^R\big)^R \big(X^R\big)^R \;=\; Y X

    After the first reversal, the first kk elements are YRY^R and the rest are XRX^R. Reversing each part on its own undoes the inner reversals:

Front insertion is quadratic. a.insert(0, x) in a loop of 10510^5 iterations shifts 0+1+⋯+(105−1)≈5×1090 + 1 + \dots + (10^5 - 1) \approx 5 \times 10^9 elements. Append instead and reverse once at the end, or use collections.deque, whose appendleft is O(1)O(1).

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:

cpp
#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 ii-th", "index", "rank", "the cell in row rr and column cc";
  • "in place", "O(1)O(1) 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 nn, around 10610^6 to 10710^7, with tight limits on time and memory, where contiguous storage and sequential scans win by large constant factors.
Problem (in brief)Key ideaCost
Rotate an array right by kk in placethree reversals, with kk reduced modulo nnO(n)O(n) time, O(1)O(1) space
Move all zeros to the end, keeping the order of the other elementsa write pointer ww: copy each nonzero to a[w]a[w] and advance ww, then fill the rest with zerosO(n)O(n), O(1)O(1)
Rotate an n×nn \times n matrix by 90° clockwise in placetranspose (swap a[r][c]a[r][c] with a[c][r]a[c][r]), then reverse each rowO(n2)O(n^2), O(1)O(1)
List the cells of a matrix in spiral orderfour boundaries (top, bottom, left, right) that move inward after each side is walkedO(RC)O(RC)
Delete arbitrary elements from a collection whose order does not matterswap with the last element, then popO(1)O(1) each
A look-alike that does not fit: keeping a sequence sorted under many insertions. Binary search finds the position in O(log⁡n)O(\log n), but the insertion still shifts Θ(n)\Theta(n) elements, so nn insertions cost Θ(n2)\Theta(n^2). Use a balanced search tree or a skip list, or collect everything and sort once if the queries come only at the end.
Check your understanding

A game keeps up to 10610^6 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 O(1)O(1)?

  1. A singly linked list, because unlinking a node is O(1)O(1)
  2. A dynamic array that moves the last particle into the dead one's slot, then pops
  3. A dynamic array, deleting with del a[i]
  4. 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, O(1)O(1). Additions are O(1)O(1) amortized appends, and the update loop scans contiguous memory.

Key takeaways

  • a[i]a[i] lives at base+i⋅s\text{base} + i \cdot s, and a[r][c]a[r][c] at base+(r⋅C+c) s\text{base} + (r \cdot C + c)\,s in row-major order (C, C++, NumPy) or at base+(c⋅R+r) s\text{base} + (c \cdot R + r)\,s in column-major order (Fortran, MATLAB, Julia, R); make the loop over neighboring addresses the innermost one.
  • Growing by a factor g>1g > 1 copies fewer than g/(g−1)g/(g-1) elements per append, so appends are O(1)O(1) amortized, though a resizing append costs Θ(n)\Theta(n); growing by a constant amount costs Θ(n)\Theta(n) amortized.
  • Smaller factors copy more but waste at most about 1−1/g1 - 1/g 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, Θ(n−i)\Theta(n - i); swap-remove is O(1)O(1) 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.

Question 1

A dynamic array triples its capacity whenever it is full, starting from capacity 1. Over any sequence of nn appends, at most about how many elements are copied per append, on average?

  1. 3
  2. 1.5
  3. 2
  4. It grows with nn, like log⁡3n\log_3 n
Show the answer

B. 1.5

The copies form a geometric series, ck (1+13+19+… )=32 ckc_k\,(1 + \tfrac13 + \tfrac19 + \dots) = \tfrac32\,c_k with ck<nc_k < n, so fewer than 1.5 n1.5\,n copies in all: g/(g−1)g/(g-1) with g=3g = 3. A larger factor copies less, but it can leave up to two thirds of its block unused.

Question 2

A library grows its arrays by 4,096 slots whenever they are full. How does the total cost of nn appends grow for large nn?

  1. Θ(n)\Theta(n): 4,096 slots is so much room that resizes are rare
  2. Θ(nlog⁡n)\Theta(n \log n)
  3. Θ(n2)\Theta(n^2): there are about n/4096n/4096 resizes, and the jj-th copies about 4096 j4096\,j elements
  4. Θ(n)\Theta(n), because each resize is spread over 4,096 appends
Show the answer

C. Θ(n2)\Theta(n^2): there are about n/4096n/4096 resizes, and the jj-th copies about 4096 j4096\,j elements

The copies total about ∑j4096 j≈n2/8192\sum_j 4096\,j \approx n^2/8192: quadratic, with a small constant. For n=106n = 10^6 that is about 1.2×1081.2 \times 10^8 copies, against fewer than 2×1062 \times 10^6 for doubling.

Question 3

A Fortran program stores a 3×43 \times 4 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?

  1. 40
  2. 72
  3. 48
  4. 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 (c⋅R+r) s=(1⋅3+2)⋅8=40(c \cdot R + r)\,s = (1 \cdot 3 + 2) \cdot 8 = 40.

Question 4

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?

  1. p still points to v[0], since push_back only adds at the end
  2. p now points to the new last element
  3. The vector refuses to grow while a pointer into it exists
  4. p points into the freed old block, and reading *p is 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.

Question 5

Why should a dynamic array that doubles when full halve its capacity when it becomes a quarter full, rather than half full?

  1. Halving at a quarter saves more memory
  2. 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
  3. Halving at half would make each pop cost O(log⁡n)O(\log n)
  4. 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 cc holding c/2c/2 elements halves on a pop and doubles again on the next append, and so on: every operation copies about c/2c/2 elements. Halving at a quarter leaves a gap of Θ(c)\Theta(c) operations between resizes, which pays for each copy: O(1)O(1) amortized for any mix.

Go deeper

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).