---
title: "Dynamic Arrays and Amortised Analysis"
book: "University Computer Science — Year 1"
subject: computer-science
language: en
chapter: 14
exercises: 12
source: https://one-course.com/books/computer-science/3/en/chapter/14-dynamic-arrays-and-amortised-analysis
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 14 — Dynamic Arrays and Amortised Analysis

A Python list grows by one element at a time, millions of times, and each `append` takes about the same short time however long the list already is. Yet a list lives in one block of memory, and a block cannot grow in place: when it is full, a larger block must be reserved and every element copied into it, which costs time proportional to the length. Both statements are true. The way out is to make the copies rare, and to count the cost of a long sequence of operations rather than of one: this is amortised analysis, and this chapter builds the growing [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) on which it works, in C, behind an interface that hides how it is made.

**You already know.**

A C module is a header, which declares what its users may call, and a [source file](https://one-course.com/books/computer-science/3/en/chapter/1-from-source-code-to-a-running-program#def-b1-compilation-pipeline-source-file), which defines it; the users include the header only ([Chapter 7](https://one-course.com/books/computer-science/3/en/chapter/7-modular-programs-makefiles-and-tests#ch-b1-c-modules-make-tests)). `malloc` reserves a block on the heap and `free` returns it ([Chapter 4](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#ch-b1-pointers-and-arrays)). A cost in $\Theta(1)$ is bounded by a constant independent of the [input size](https://one-course.com/books/computer-science/3/en/chapter/13-asymptotic-analysis-and-recurrences#def-b1-asymptotic-analysis-cost) ([Chapter 13](https://one-course.com/books/computer-science/3/en/chapter/13-asymptotic-analysis-and-recurrences#ch-b1-asymptotic-analysis)).

## 14.1 Abstract types and implementations

**Definition 14.1 (Abstract data type).**

An *abstract data type* is a type given by a set of operations and their specification, without saying how its values are represented. Its *interface* is the list of the operations with their signatures; an *implementation* chooses a representation and writes the operations. Code that uses only the interface works unchanged with any implementation that meets the specification.

**Definition 14.2 (Constructor, accessor, transformer).**

The operations of an abstract type are of three kinds: a *constructor* creates a value of the type, an *accessor* returns information about a value without changing it, and a *transformer* changes it.

```cpp
// vec.h: the interface of the abstract type "dynamic array of int".
#ifndef VEC_H
#define VEC_H
#include <stddef.h>

typedef struct vec vec;               // opaque: the fields stay in the implementation

vec *vec_new(void);                   // constructor: an empty array
void vec_free(vec *v);
size_t vec_size(const vec *v);        // accessors
int vec_get(const vec *v, size_t i);  // precondition: i < size
void vec_set(vec *v, size_t i, int x);  // transformers; precondition: i < size
void vec_push(vec *v, int x);         // add x at the end
int vec_pop(vec *v);                  // remove and return the last; precondition: size > 0
size_t vec_capacity(const vec *v);    // for the experiments: cells reserved
long vec_copies(const vec *v);        // for the experiments: elements copied so far
#endif
```

***Listing 14.1.** The interface of the [dynamic array](#def-b1-dynamic-arrays-dynamic-array) code/bachelor-1/14-dynamic-arrays/listings/vec.h*

The declaration `typedef struct vec vec;` names a structure without giving its fields: a user can hold a `vec *` and pass it to the functions, but cannot read or change the fields, which are defined only in the implementation. The [compiler](https://one-course.com/books/computer-science/3/en/chapter/1-from-source-code-to-a-running-program#def-b1-compilation-pipeline-compiler) enforces the interface. Two files implement it: `vec.c`, the growing [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) of this chapter, and `fixed.c`, an [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) of 16 cells that refuses a seventeenth element.

![An abstract type: the user depends on the interface only, and either implementation can be linked behind it. The fields of struct vec differ between the two files.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-dynamic-arrays/fig-aad54192de2e.svg)

*An abstract type: the user depends on the interface only, and either implementation can be linked behind it. The fields of `struct vec` differ between the two files.*

```
$ gcc -std=c17 -O2 -Wall -Wextra vec_demo.c vec.c -o demo_vec
$ gcc -std=c17 -O2 -Wall -Wextra vec_demo.c fixed.c -o demo_fixed
$ ./demo_vec | sed -n '15,18p'
push 15: size 15  capacity 16  copies so far 15
push 16: size 16  capacity 16  copies so far 15
push 17: size 17  capacity 32  copies so far 31
sum of the elements: 153
$ ./demo_fixed 2>&1 | sed -n '15,18p'
push 15: size 15  capacity 16  copies so far  0
push 16: size 16  capacity 16  copies so far  0
vec: full at 16 elements
```

***Output 14.1.** The same demonstration linked with each implementation: the fixed one stops at its [capacity](#def-b1-dynamic-arrays-dynamic-array).*

## 14.2 The doubling array

**Definition 14.3 (Dynamic array, size and capacity).**

A *dynamic array* stores a sequence in a block of memory larger than needed. Its *size* is the number of elements, its *capacity* the number of cells in the block. Adding an element to a full [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) first moves the elements to a larger block, whose capacity is a constant factor larger.

**Definition 14.4 (Representation invariant).**

A *representation invariant* is a condition on the fields of an implementation that every operation may assume on entry and must restore before returning. It says which values of the fields represent a value of the abstract type.

```c
struct vec {
    int *data;
    size_t size, capacity;
    long copies;
};
// representation invariant: 1 <= capacity, size <= capacity, data holds capacity
// cells, and size > capacity / 4 unless capacity == 1 or the array was just made

static void resize(vec *v, size_t capacity) {
    int *data = malloc(capacity * sizeof *data);
    if (data == NULL) {
        perror("vec");
        exit(1);
    }
    for (size_t i = 0; i < v->size; i++) data[i] = v->data[i];
    v->copies += (long)v->size;
    free(v->data);
    v->data = data;
    v->capacity = capacity;
}
void vec_push(vec *v, int x) {
    if (v->size == v->capacity) resize(v, 2 * v->capacity);
    v->data[v->size++] = x;
}

int vec_pop(vec *v) {
    int x = v->data[--v->size];
    if (v->capacity > 1 && v->size <= v->capacity / 4) resize(v, v->capacity / 2);
    return x;
}
```

***Listing 14.2.** The doubling [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array): the representation, the resize, and the two operations that change the [size](#def-b1-dynamic-arrays-dynamic-array) code/bachelor-1/14-dynamic-arrays/listings/vec.c*

The [capacity](#def-b1-dynamic-arrays-dynamic-array) doubles when a push finds the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) full, and halves when a pop leaves it a quarter full. Shrinking at a half would be a mistake ([Section 14.3](#sec-b1-dynamic-arrays-shrinking)). The function `resize` copies every element and counts the copies, so that the experiments can report them.

```
$ gcc -std=c17 -O2 -Wall -Wextra -o vec_demo vec_demo.c vec.c -lm && ./vec_demo
push  1: size  1  capacity  1  copies so far  0
push  2: size  2  capacity  2  copies so far  1
push  3: size  3  capacity  4  copies so far  3
push  4: size  4  capacity  4  copies so far  3
push  7: size  7  capacity  8  copies so far  7
push  8: size  8  capacity  8  copies so far  7
push  9: size  9  capacity 16  copies so far 15
push 15: size 15  capacity 16  copies so far 15
push 16: size 16  capacity 16  copies so far 15
push 17: size 17  capacity 32  copies so far 31
sum of the elements: 153
pop   9: size  8  capacity 16  copies so far 39
pop   5: size  4  capacity  8  copies so far 43
pop   3: size  2  capacity  4  copies so far 45
pop   2: size  1  capacity  2  copies so far 46
pop   1: size  0  capacity  1  copies so far 46
```

***Output 14.2.** Seventeen pushes, then the pops that shrink the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array). Some lines are left out.*

## 14.3 Amortised cost

A push usually costs one write; the push that finds the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) full costs one write plus as many copies as there are elements. The worst case of one push is therefore $\Theta(n)$, which is true and misleading: such pushes are rare.

**Definition 14.5 (Amortised cost).**

Operations on a data structure have *amortised cost* $a$ if every sequence of $m$ operations, starting from the empty structure, costs at most $a \cdot m$ in total. The bound concerns the worst sequence, not an average over inputs: no probability is involved.

**Definition 14.6 (Aggregate, accounting and potential methods).**

Three methods prove amortised bounds. The *aggregate method* bounds the total cost of any sequence directly. The *accounting method* charges each operation a fixed number of credits, spends one credit per unit of actual cost, and shows that the credits stored never become negative. The *potential method* chooses a *potential function* $\Phi$ from the states of the structure to the reals, and calls $c_i + \Phi_i - \Phi_{i-1}$ the [amortised cost](#def-b1-dynamic-arrays-amortised) of the $i$-th operation, of actual cost $c_i$; if $\Phi_m \geq \Phi_0$ after every sequence, the total actual cost is at most the total [amortised cost](#def-b1-dynamic-arrays-amortised).

The last claim is a telescoping sum: $\sum_i (c_i + \Phi_i - \Phi_{i-1}) = \sum_i c_i + \Phi_m - \Phi_0 \geq \sum_i
c_i$.

**Proposition 14.7 (Pushes on the doubling array).**

Starting from an empty [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) of [capacity](#def-b1-dynamic-arrays-dynamic-array) 1, $n$ pushes make fewer than $2n$ copies, and cost fewer than $3n$ writes and copies in all: a push has [amortised cost](#def-b1-dynamic-arrays-amortised) 3.

**Proof.** *Aggregate*: the copies happen when the [size](#def-b1-dynamic-arrays-dynamic-array) reaches $1, 2, 4, \dots, 2^j$ with $2^j < n$, and copy that many elements: $1 + 2 + \dots + 2^j = 2^{j+1} - 1 < 2n$. With the $n$ writes, the total is below $3n$.

*Accounting*: charge 3 credits per push. One pays its write; two are stored with the new element. When an [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) of [capacity](#def-b1-dynamic-arrays-dynamic-array) $c$ fills up, the $c/2$ elements pushed since the last resize have stored $c$ credits, which pay for the $c$ copies. The store never goes negative.

*Potential*: let $\Phi = 2 \cdot \text{size} - \text{capacity}$, which is $-1$ for the empty [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) and at least 0 after any push. A push without resize costs 1 and raises $\Phi$ by 2: amortised 3. A push on a full [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) of [size](#def-b1-dynamic-arrays-dynamic-array) $s$ costs $1 + s$, and $\Phi$ goes from $2s - s = s$ to $2(s + 1) - 2s = 2$: amortised $1 + s + 2 - s = 3$. ∎

![Seventeen pushes on the doubling array, from . The capacity doubles at pushes 2, 3, 5, 9 and 17, where a push costs one write and as many copies as there are elements; every other push costs 1. The spikes double, but so does the gap between them.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-dynamic-arrays/fig-185c88428b97.svg)

*Seventeen pushes on the doubling [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array), from [Output 14.2](#out-b1-dynamic-arrays-demo). The [capacity](#def-b1-dynamic-arrays-dynamic-array) doubles at pushes 2, 3, 5, 9 and 17, where a push costs one write and as many copies as there are elements; every other push costs 1. The spikes double, but so does the gap between them.*

![The potential = 2 size - capacity along the same pushes: it rises by 2 at each cheap push, storing credit, and falls to 2 at each resize, spending it on the copies. The first dot is the empty array, = -1.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-dynamic-arrays/fig-d0ffd0433b4a.svg)

*The potential $\Phi = 2 \cdot \text{size} - \text{capacity}$ along the same pushes: it rises by 2 at each cheap push, storing credit, and falls to 2 at each resize, spending it on the copies. The first dot is the empty [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array), $\Phi = -1$.*

The same analysis applies to any [growth factor](https://one-course.com/books/computer-science/3/en/chapter/5-dynamic-memory#def-b1-dynamic-memory-growth) $r > 1$, with $r/(r - 1)$ copies per push in place of 2 ([Exercise 14.10](#exo-b1-dynamic-arrays-10)); but not to a growth by a constant number of cells, which makes the copies quadratic. C++’s `std::vector` specifies `push_back` as amortised constant time, which rules out a constant increment.

```
$ gcc -std=c17 -O2 -Wall -Wextra -o copies copies.c -lm && ./copies
        n x1.5: copies, per push   x2: copies, per push  +16: copies, per push
     1000           2104    2.10           1023    1.02          31311   31.31
    10000          24239    2.42          16383    1.64        3120625  312.06
   100000         276464    2.76         131071    1.31      312456250 3124.56
  1000000        2099686    2.10        1048575    1.05    31249562500 31249.56
```

***Output 14.3.** Element copies for $n$ pushes, and per push, for growth by 1.5, by 2 and by 16 cells.*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o timing timing.c -lm && ./timing
       n       x1.5         x2        +16   (ns per push)
    4096       0.54       0.41       5.58
   16384       0.49       0.38      34.08
   65536       2.69       0.31     149.83
  262144       2.70       0.37     817.84
```

***Output 14.4.** The same three policies timed on the author’s laptop (best of three, nanoseconds per push).*

Copies per push oscillate with $n$ (they depend on where $n$ falls between two resizes) but stay below 2 for doubling and below 3 for the factor 1.5, as the bound says; with 16 more cells each time, they grow like $n/32$. The times agree: doubling costs under half a nanosecond per push and the factor 1.5 from half a nanosecond to under three, while the increment costs four to six times more at each fourfold increase of $n$, as copies growing like $n/32$ predict.

The binary counter is the second classic example. A counter of $K$ bits is incremented by turning its trailing 1s into 0s and the next 0 into a 1. An increment can flip all $K$ bits, but bit 0 flips at every increment, bit 1 at every second, bit $j$ at every $2^j$-th: $n$ increments make fewer than $n(1 + \frac12 + \frac14 + \cdots) = 2n$ flips (Exercises [14.8](#exo-b1-dynamic-arrays-8) and [14.9](#exo-b1-dynamic-arrays-9)).

```c
static int increment(int bits[K]) {  // returns the number of bits flipped
    int i = 0;
    while (i < K && bits[i] == 1) bits[i++] = 0;  // the trailing 1s become 0
    if (i < K) bits[i] = 1;                         // and the next 0 becomes 1
    return i < K ? i + 1 : i;
}
```

***Listing 14.3.** An increment, counting the flipped bits code/bachelor-1/14-dynamic-arrays/listings/counter.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o counter counter.c -lm && ./counter
      n        flips  per incr.
      8           15     1.8750
     64          127     1.9844
    512         1023     1.9980
   4096         8191     1.9998
  32768        65535     2.0000
```

***Output 14.5.** Total flips for $n$ increments from zero. Some lines are left out.*

### Shrinking

An [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) that only grows wastes memory after many pops. Halving the [capacity](#def-b1-dynamic-arrays-dynamic-array) when the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) is half full looks symmetric with doubling, and is a trap: at a [size](#def-b1-dynamic-arrays-dynamic-array) just above a power of 2, a push doubles the [capacity](#def-b1-dynamic-arrays-dynamic-array), a pop halves it, and each copies every element. Shrinking at a quarter leaves room in both directions after each resize.

```
$ gcc -std=c17 -O2 -Wall -Wextra -o thrash thrash.c -lm && ./thrash
shrink at 1/2: 1000 operations after the fill, 1024000 copies, 1024.0 each
shrink at 1/4: 1000 operations after the fill, 1024 copies, 1.0 each
```

***Output 14.6.** After filling to 1024 elements, 1000 alternating pushes and pops under each shrinking policy.*

## 14.4 The circular buffer

A queue takes elements at the front and adds them at the back. In an [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array), taking the front would shift every element, or leave the used part drifting to the right; a [circular buffer](#def-b1-dynamic-arrays-ring) lets it wrap around.

**Definition 14.8 (Circular buffer).**

A *circular buffer* stores a queue in an [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) of [capacity](#def-b1-dynamic-arrays-dynamic-array) $c$ with a head index $h$ and a count $k$: the queue is $a[h], a[(h + 1) \bmod c], \dots, a[(h + k - 1) \bmod c]$. Taking the front advances $h$ modulo $c$; adding at the back writes $a[(h + k) \bmod c]$.

```c
void ring_put(ring *r, int x) {
    if (r->count == r->capacity) {  // full: copy in queue order into twice the room
        int *data = checked(calloc(2 * r->capacity, sizeof(int)));
        for (size_t i = 0; i < r->count; i++)
            data[i] = r->data[(r->head + i) % r->capacity];
        free(r->data);
        *r = (ring){data, 0, r->count, 2 * r->capacity};
    }
    r->data[(r->head + r->count) % r->capacity] = x;
    r->count++;
}

int ring_take(ring *r) {
    int x = r->data[r->head];
    r->head = (r->head + 1) % r->capacity;
    r->count--;
    return x;
}
```

***Listing 14.4.** Adding and taking, with growth when full code/bachelor-1/14-dynamic-arrays/listings/ring.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o ring_demo ring_demo.c ring.c -lm && ./ring_demo
put 1..4     [ 1]  2   3   4   .    size 4
take 1, 2     .   . [ 3]  4   .    size 2
put 5, 6       6   . [ 3]  4   5    size 4
put 7          6   7 [ 3]  4   5    size 5
put 8 (grow) [ 3]  4   5   6   7   8   .   .   .   .    size 6
```

***Output 14.7.** A queue in five cells: the front, in brackets, moves right, the back wraps to the start, and the eighth element makes it grow.*

![A circular buffer before and after it grows. On the left, the queue 3, 4, 5, 6 has wrapped: it starts at index 2 and continues at index 0. Growing copies the queue in order to the start of a larger array.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-dynamic-arrays/fig-ff5ab465e978.svg)

*A [circular buffer](#def-b1-dynamic-arrays-ring) before and after it grows. On the left, the queue 3, 4, 5, 6 has wrapped: it starts at index 2 and continues at index 0. Growing copies the queue in order to the start of a larger [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array).*

Keeping the count rather than a second index matters: with a head and a tail index only, the full and the empty buffer both have $h = t$ ([Exercise 14.5](#exo-b1-dynamic-arrays-5)). Growth copies the elements in queue order, from the head, not in the order of the cells: copying the cells as they are would break the wrap-around.

**In practice.**

Python’s `list` and C++’s `std::vector` are [dynamic arrays](#def-b1-dynamic-arrays-dynamic-array). Python’s `collections.deque` is a chain of [fixed-size](#def-b1-dynamic-arrays-dynamic-array) blocks, and the buffers between a producer and a consumer, from keyboard input to network cards, are queues in fixed blocks with wrapping indices. A program that knows how many elements it will push can reserve the [capacity](#def-b1-dynamic-arrays-dynamic-array) once and avoid every copy.

## 14.5 Exercises

**Exercise 14.1 ★.**

Predict the three lines this program prints, with the doubling [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) of [Listing 14.2](#lst-b1-dynamic-arrays-vec).

```c
int main(void) {
    vec *v = vec_new();
    for (int i = 0; i < 6; i++) vec_push(v, i);
    printf("%zu %zu\n", vec_size(v), vec_capacity(v));
    for (int i = 0; i < 4; i++) vec_pop(v);
    printf("%zu %zu\n", vec_size(v), vec_capacity(v));
    vec_push(v, 9);
    vec_push(v, 9);
    vec_push(v, 9);
    printf("%zu %zu %ld\n", vec_size(v), vec_capacity(v), vec_copies(v));
    vec_free(v);
    return 0;
}
```

***Listing 14.5.** Pushes and pops code/bachelor-1/14-dynamic-arrays/listings/exo_ops.c*

**Solution of Exercise 14.1.**

```
6 8
2 4
5 8 13
```

***Output 14.11.** The three lines. Some lines are left out.*

Six pushes leave [size](#def-b1-dynamic-arrays-dynamic-array) 6 in [capacity](#def-b1-dynamic-arrays-dynamic-array) 8, after copies $1 + 2 + 4 = 7$. The pops bring the [size](#def-b1-dynamic-arrays-dynamic-array) to 5, 4, 3, 2; at 2, $2 \leq
8/4$, and the [capacity](#def-b1-dynamic-arrays-dynamic-array) halves to 4 with 2 copies. Three pushes: [sizes](#def-b1-dynamic-arrays-dynamic-array) 3 and 4 fit, the fifth element doubles the [capacity](#def-b1-dynamic-arrays-dynamic-array) to 8 with 4 copies: $7 + 2 + 4 = 13$.

**Exercise 14.2 ★.**

How many element copies do 10 pushes make on the doubling [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array), starting from [capacity](#def-b1-dynamic-arrays-dynamic-array) 1? And 10 pushes when each resize adds 2 cells?

**Solution of Exercise 14.2.**

Doubling: resizes at pushes 2, 3, 5 and 9, copying $1 + 2 + 4 + 8 = 15$ elements. Adding 2 cells: capacities 1, 3, 5, 7, 9, 11, with resizes when the [size](#def-b1-dynamic-arrays-dynamic-array) is 1, 3, 5, 7 and 9: $1 + 3 + 5 + 7 + 9 = 25$ copies, already more, and growing quadratically.

**Exercise 14.3 ★.**

A [circular buffer](#def-b1-dynamic-arrays-ring) of [capacity](#def-b1-dynamic-arrays-dynamic-array) 4 starts empty. Draw its cells, head and count after: put 1, put 2, put 3, take, take, put 4, put 5, put 6, take.

**Solution of Exercise 14.3.**

After three puts: `[1 2 3 .]`, $h = 0$, $k = 3$. After two takes: $h = 2$, $k = 1$ (the queue is 3). Put 4 goes to cell 3, put 5 to cell $(2 + 2) \bmod 4 = 0$, put 6 to cell 1: `[5 6 3 4]`, $h = 2$, $k = 4$, full. The last take returns 3: $h = 3$, $k = 3$, the queue is 4, 5, 6.

**Exercise 14.4 ★.**

How many bits do 8 increments flip, starting from 0? List the flips of each increment.

**Solution of Exercise 14.4.**

The increments from 0 to 8 flip 1, 2, 1, 3, 1, 2, 1 and 4 bits: 15 in all, $2 \cdot 8 - 1$.

**Exercise 14.5 ★★.**

This buffer keeps a head and a tail index. Explain the output, and give two ways to repair it.

```c
enum { N = 4 };
int data[N];
int head = 0, tail = 0;  // the queue is data[head..tail), modulo N

int empty(void) { return head == tail; }
void put(int x) { data[tail] = x; tail = (tail + 1) % N; }
int take(void) { int x = data[head]; head = (head + 1) % N; return x; }

int main(void) {
    for (int x = 1; x <= 4; x++) put(x);
    printf("after four puts, empty() says %d\n", empty());
    int n = 0;
    while (!empty()) n++, take();
    printf("taken: %d elements\n", n);
    return 0;
}
```

***Listing 14.6.** Head and tail only code/bachelor-1/14-dynamic-arrays/listings/exo_ring_bug.c*

```
after four puts, empty() says 1
taken: 0 elements
```

***Output 14.8.** Four puts, and nothing to take. Some lines are left out.*

**Solution of Exercise 14.5.**

After four puts in four cells, `tail` has wrapped to 0, equal to `head`: the full buffer looks empty, and the loop takes nothing. With two indices modulo $N$ there are only $N$ possible differences `tail - head` for $N + 1$ possible [sizes](#def-b1-dynamic-arrays-dynamic-array), 0 to $N$. Two repairs: keep the count (as [Listing 14.4](#lst-b1-dynamic-arrays-ring) does), or never fill the last cell, declaring the buffer full when `(tail + 1) % N == head`, at the price of one unused cell.

**Exercise 14.6 ★★.**

In [Output 14.6](#out-b1-dynamic-arrays-thrash), explain the 1024 copies per operation of the half policy, and the one copy per operation of the quarter policy. Give a sequence of $m$ operations that costs $\Theta(m^2)$ copies under the half policy.

**Solution of Exercise 14.6.**

Half policy: at [size](#def-b1-dynamic-arrays-dynamic-array) 1024 in [capacity](#def-b1-dynamic-arrays-dynamic-array) 1024, a push doubles (1024 copies) to [size](#def-b1-dynamic-arrays-dynamic-array) 1025 in 2048; the pop brings the [size](#def-b1-dynamic-arrays-dynamic-array) to $1024 \leq 2048/2$, and the [capacity](#def-b1-dynamic-arrays-dynamic-array) halves (1024 copies). Every operation copies 1024 elements. Quarter policy: the first push copies 1024; then the [size](#def-b1-dynamic-arrays-dynamic-array) moves between 1024 and 1025 in [capacity](#def-b1-dynamic-arrays-dynamic-array) 2048, far from both 2048 and 512: no other copy, so $1024/1000 \approx 1$ per operation. For $\Theta(m^2)$: $m/2 = 2^k$ pushes, then $m/2$ alternating operations of $2^k = m/2$ copies each.

**Exercise 14.7 ★★.**

Write an abstract type “stack of int” (`stack.h`, `stack.c`) on top of `vec.h`, with a [constructor](#def-b1-dynamic-arrays-operations), two [accessors](#def-b1-dynamic-arrays-operations) (`stack_empty`, `stack_top`) and two [transformers](#def-b1-dynamic-arrays-operations), and test it, including on a bracket checker.

**Solution of Exercise 14.7.**

```c
struct stack {
    vec *items;  // the top is the last element
};

stack *stack_new(void) {
    stack *s = malloc(sizeof *s);
    if (s == NULL) exit(1);
    s->items = vec_new();
    return s;
}

void stack_free(stack *s) {
    vec_free(s->items);
    free(s);
}

bool stack_empty(const stack *s) { return vec_size(s->items) == 0; }
int stack_top(const stack *s) { return vec_get(s->items, vec_size(s->items) - 1); }
void stack_push(stack *s, int x) { vec_push(s->items, x); }
int stack_pop(stack *s) { return vec_pop(s->items); }
```

*A stack on the [dynamic array](#def-b1-dynamic-arrays-dynamic-array) code/bachelor-1/14-dynamic-arrays/exercises/stack.c*

The header `exercises/stack.h` declares the six operations with `typedef struct stack stack;`. The top is the last element of the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array), so push and pop are those of the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array), with [amortised cost](#def-b1-dynamic-arrays-amortised) $O(1)$. The test pushes and pops 1000 values and checks brackets: `([()[]])` is balanced, `([)]` and `((` are not.

**Exercise 14.8 ★★.**

By the [aggregate method](#def-b1-dynamic-arrays-methods), prove that $n$ increments of a binary counter, from 0, flip fewer than $2n$ bits.

**Solution of Exercise 14.8.**

Bit $j$ changes at the increment from $x$ to $x + 1$ exactly when $2^j$ divides $x + 1$, which happens $\lfloor n/2^j
\rfloor$ times for $x + 1 = 1, \dots, n$. The total is $\sum_{j \geq 0} \lfloor n/2^j \rfloor < n \sum_j 2^{-j} = 2n$.

**Exercise 14.9 ★★.**

Prove the same bound by the [accounting method](#def-b1-dynamic-arrays-methods): how many credits per increment, and where are they stored?

**Solution of Exercise 14.9.**

Charge 2 credits per increment. An increment sets exactly one bit from 0 to 1 (unless it overflows): one credit pays that flip, and the other is stored on the bit that is now 1. The flips from 1 to 0 are paid by the credits stored on those bits. Every bit at 1 holds one credit, so the store is never negative, and $n$ increments flip at most $2n$ bits.

**Exercise 14.10 ★★★.**

The [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) grows by a factor $r > 1$ when full ([capacity](#def-b1-dynamic-arrays-dynamic-array) $c$ becomes at least $rc$, for instance $\lceil rc \rceil$; the factor 1.5 of the programs gives $c + \lfloor c/2 \rfloor + 1$). Prove with a potential that $n$ pushes make at most about $\frac{r}{r - 1} n$ copies, and compare with [Output 14.3](#out-b1-dynamic-arrays-copies).

**Solution of Exercise 14.10.**

Let $\Phi = \alpha s - c/(r - 1)$ for [size](#def-b1-dynamic-arrays-dynamic-array) $s$ and [capacity](#def-b1-dynamic-arrays-dynamic-array) $c$. A push without resize copies nothing and raises $\Phi$ by $\alpha$. A push on a full [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) of [size](#def-b1-dynamic-arrays-dynamic-array) $s = c$ copies $c$ elements, and, the [capacity](#def-b1-dynamic-arrays-dynamic-array) growing by at least $(r - 1)c$, $\Phi$ changes by at most $\alpha - (r - 1)c/(r - 1) = \alpha - c$: amortised $c + \alpha - c = \alpha$ copies. Right after a resize $s \geq c/r$, so $\Phi \geq c(\alpha/r -
1/(r - 1))$, which is non-negative for $\alpha = r/(r - 1)$; it stays so as pushes raise it. Hence $n$ pushes copy at most $\frac{r}{r - 1} n$ plus a constant from $\Phi_0$ and the rounding of the new [capacity](#def-b1-dynamic-arrays-dynamic-array). For $r = 1.5$ the bound is 3 (the table reaches 2.76), for $r = 2$ it is 2 (the table reaches 1.64).

**Exercise 14.11 ★★★.**

With growth $\times 2$ and shrinking to half when a quarter full, prove that any sequence of $m$ pushes and pops from the empty [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) makes at most $2m$ copies. Use $\Phi = 2s - c$ when $s \geq c/2$ and $\Phi = c/2 - s$ when $s < c/2$, for [size](#def-b1-dynamic-arrays-dynamic-array) $s$ and [capacity](#def-b1-dynamic-arrays-dynamic-array) $c$.

**Solution of Exercise 14.11.**

$\Phi \geq 0$ always, and $\Phi_0 = \frac12$ for the empty [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) of [capacity](#def-b1-dynamic-arrays-dynamic-array) 1. Pushes: in the upper half, $\Delta\Phi =
+2$; in the lower half, $-1$; on a full [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) of [size](#def-b1-dynamic-arrays-dynamic-array) $c$, $c$ copies and $\Phi$ goes from $c$ to 2, amortised $2 - c + c =
2$. Pops without resize: $-2$ in the upper half, $+1$ in the lower. A pop that shrinks leaves [size](#def-b1-dynamic-arrays-dynamic-array) $c/4$ in [capacity](#def-b1-dynamic-arrays-dynamic-array) $c/2$: $\Phi$ goes from $c/2 - (c/4 + 1) = c/4 - 1$ to $2 \cdot c/4 - c/2 = 0$, with $c/4$ copies: amortised 1 (the small capacities 4 and 2 give 1 and $\frac12$). Every [amortised cost](#def-b1-dynamic-arrays-amortised) is at most 2, so $m$ operations copy at most $2m +
\Phi_0 - \Phi_m \leq 2m + \frac12$, hence at most $2m$, an integer. The test checks it along 200 000 random operations.

**Exercise 14.12 ★★★.**

Write a [dynamic array](#def-b1-dynamic-arrays-dynamic-array) of elements of any type: the [constructor](#def-b1-dynamic-arrays-operations) takes the size of an element in bytes, push copies an element from an address, and `gvec_at` returns the address of an element. Test it with `double` and with a structure.

**Solution of Exercise 14.12.**

```c
struct gvec {
    unsigned char *data;
    size_t elem_size, size, capacity;
};

static void resize(gvec *v, size_t capacity) {
    unsigned char *data = malloc(capacity * v->elem_size);
    if (data == NULL) exit(1);
    if (v->size > 0) memcpy(data, v->data, v->size * v->elem_size);
    free(v->data);
    v->data = data;
    v->capacity = capacity;
}
size_t gvec_size(const gvec *v) { return v->size; }
void *gvec_at(gvec *v, size_t i) { return v->data + i * v->elem_size; }

void gvec_push(gvec *v, const void *elem) {
    if (v->size == v->capacity) resize(v, 2 * v->capacity);
    memcpy(gvec_at(v, v->size++), elem, v->elem_size);
}

void gvec_pop(gvec *v, void *out) {
    memcpy(out, gvec_at(v, --v->size), v->elem_size);
    if (v->capacity > 1 && v->size <= v->capacity / 4) resize(v, v->capacity / 2);
}
```

*The generic [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array): bytes and an element [size](#def-b1-dynamic-arrays-dynamic-array) code/bachelor-1/14-dynamic-arrays/exercises/gvec.c*

Elements are copied with `memcpy`, `elem_size` bytes at a time, and the address of element $i$ is the start of the block plus $i \cdot \text{elem\_size}$. The user [casts](https://one-course.com/books/computer-science/3/en/chapter/2-c-types-operators-and-control-flow#def-b1-c-types-and-control-cast) it back: `*(double *)gvec_at(d, 4000)`. The test pushes 5000 doubles and pops them back in reverse, then stores three `book` structures and changes one in place through its address.

## 14.6 Problem: The binary counter and the elastic array

**Problem 14.1.**

Weekend problem — The binary counter and the elastic array

A program tries every sequence of $m$ pushes and pops on the policy of `vec.c` (double when full, halve when a quarter full), for even $m$ up to 26, and prints the largest number of copies with one sequence that makes them.

```c
static long copies_of(long m, long mask) {  // bit i of mask: 1 push, 0 pop
    long size = 0, capacity = 1, copies = 0;
    for (long i = 0; i < m; i++) {
        if (mask >> i & 1) {
            if (size == capacity) {
                copies += size;
                capacity *= 2;
            }
            size++;
        } else {
            if (size == 0) return -1;  // a pop on the empty array: not allowed
            size--;
            if (capacity > 1 && size <= capacity / 4) {
                copies += size;
                capacity /= 2;
            }
        }
    }
    return copies;
}
```

***Listing 14.7.** Copies of one sequence of operations code/bachelor-1/14-dynamic-arrays/listings/elastic.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o elastic elastic.c -lm && ./elastic
 m copies  copies/m  a worst sequence (+ push, - pop)
 2      1     0.500  ++
 4      3     0.750  +++-
 6      7     1.167  +++++-
 8      9     1.125  +++++---
10     15     1.500  +++++++++-
12     15     1.250  +++++++++---
14     19     1.357  +++++++++-----
16     21     1.312  +++++++++-------
18     31     1.722  +++++++++++++++++-
20     31     1.550  +++++++++++++++++---
22     34     1.545  +++--++++++++++++++++-
24     37     1.542  +++++---+++++++++++++++-
26     40     1.538  +++++----++++++++++++++++-
```

***Output 14.9.** The worst sequences found.*

```
from 2^15 - 1, 1000 increments and decrements alternating: 16000 flips, 16.0 each
```

***Output 14.10.** The counter of [Listing 14.3](#lst-b1-dynamic-arrays-counter), with a decrement, alternating around $2^{15}$. Some lines are left out.*

**Part I — The counter.**

1. Show that an increment from $x$ flips $t + 1$ bits, where $t$ is the number of trailing 1s of $x$ (when $t < K$ ).
2. How many of the integers $0 \leq x < 2^K$ have exactly $t$ trailing 1s?
3. Show that bit $j$ flips exactly $\lfloor n/2^j \rfloor$ times in $n$ increments from 0.
4. Deduce that the total is $\sum_j \lfloor n/2^j \rfloor < 2n$ , and that it equals $2n - 1$ when $n$ is a power of 2.
5. Check the table of [Output 14.5](#out-b1-dynamic-arrays-counter) .
6. What is the worst case of a single increment, and why does it not contradict the amortised bound?

**Part II — The doubling array, three ways.**

7. Count exactly the copies made by $n$ pushes from [capacity](#def-b1-dynamic-arrays-dynamic-array) 1, as a function of $n$ .
8. Write the accounting argument for pushes with 3 credits each, and say why 2 credits would not do.
9. Check that $\Phi = 2 \cdot \text{size} - \text{capacity}$ is at least 0 after every push.
10. Give the [amortised cost](#def-b1-dynamic-arrays-amortised) of each push of [Output 14.2](#out-b1-dynamic-arrays-demo) with this $\Phi$ .
11. With $n$ pushes, what is the largest [capacity](#def-b1-dynamic-arrays-dynamic-array) , and so the largest unused memory, as a fraction of the [size](#def-b1-dynamic-arrays-dynamic-array) ?
12. Which of the three methods would you use to explain the result to a colleague, and why?

**Part III — Shrinking.**

13. With shrinking at a half, describe the state after filling to $2^k$ elements, then one push, then one pop.
14. Deduce that $m$ alternating operations after the fill cost $\Theta(m \cdot 2^k)$ copies.
15. With shrinking at a quarter, show that after any resize the [size](#def-b1-dynamic-arrays-dynamic-array) is exactly half the new [capacity](#def-b1-dynamic-arrays-dynamic-array) .
16. Deduce that between two resizes at least a quarter of the [capacity](#def-b1-dynamic-arrays-dynamic-array) ’s worth of operations happen.
17. Read the table of [Output 14.9](#out-b1-dynamic-arrays-elastic) : which sequences are the worst, and what is the largest ratio of copies to operations?
18. Show that $2^k + 1$ pushes make $2^{k+1} - 1$ copies, so that the ratio approaches 2.

**Part IV — A decrement breaks the bound.**

19. Write the decrement of the counter, and give the flips of a decrement from $2^j$ .
20. From $2^{15} - 1$ , alternate increment and decrement: how many flips per operation? Check with [Output 14.10](#out-b1-dynamic-arrays-counter-dec) .
21. Deduce that $n$ operations among increments and decrements can cost $\Theta(n \log n)$ flips when the counter has $\log_2 n$ bits.
22. With digits $-1$ , 0 and 1 in base 2 (each number then has several representations), an increment and a decrement can each be made to change a bounded number of digits in the amortised sense. Why does this not contradict the previous question?
23. Is the amortised bound of the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) , $2m$ copies, still valid for any mix of pushes and pops? Why do pops not break it as decrements break the counter’s?
24. State the named result of the problem, *the elastic [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) theorem* : the constant $c$ with at most $c \cdot m$ copies for any $m$ operations, why it is the smallest, and the worst ratios found by the program.

**Solution of Problem 14.1.**

**1.** The $t$ trailing 1s become 0 and the next bit, a 0, becomes 1: $t + 1$ flips.

**2.** Bits 0 to $t - 1$ are 1, bit $t$ is 0, the $K - t - 1$ others are free: $2^{K - t - 1}$ integers.

**3.** Bit $j$ flips from $x$ to $x + 1$ exactly when $2^j$ divides $x + 1$: $\lfloor n/2^j \rfloor$ times.

**4.** $\sum_j \lfloor n/2^j \rfloor < n \sum_j 2^{-j} = 2n$; for $n = 2^k$ the sum is $2^k + 2^{k-1} + \dots + 1 =
2^{k+1} - 1$.

**5.** 15, 127, 1023, 8191 and 65 535 flips for $n = 8, 64, 512, 4096, 32\,768$: each is $2n - 1$.

**6.** From $2^K - 1$, all $K$ bits flip. Such increments are rare: one in $2^{K}$ from 0.

**7.** $2^{\lceil \log_2 n \rceil} - 1$: the resizes copy $1, 2, \dots, 2^j$ with $2^j < n$. For $n = 17$, 31.

**8.** A push pays its write and stores two credits on its element. When [capacity](#def-b1-dynamic-arrays-dynamic-array) $c$ fills, the $c/2$ elements pushed since the last resize hold $c$ credits, one per copy. With 2 credits, only $c/2$ would be stored.

**9.** After a push the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) holds more than half its [capacity](#def-b1-dynamic-arrays-dynamic-array): either no resize happened and the [size](#def-b1-dynamic-arrays-dynamic-array) grew, or a resize left [size](#def-b1-dynamic-arrays-dynamic-array) $c + 1$ in [capacity](#def-b1-dynamic-arrays-dynamic-array) $2c$. So $2s - c > 0$.

**10.** 3 for each of the seventeen pushes, as the dashed line of the figure shows.

**11.** The [capacity](#def-b1-dynamic-arrays-dynamic-array) is $2^{\lceil \log_2 n \rceil} < 2n$: the unused cells are fewer than the elements, nearly as many right after a resize.

**12.** The [accounting method](#def-b1-dynamic-arrays-methods): credits stored on elements show where the cost of a copy comes from.

**13.** [Size](#def-b1-dynamic-arrays-dynamic-array) $2^k$ in [capacity](#def-b1-dynamic-arrays-dynamic-array) $2^k$; the push copies $2^k$ elements into [capacity](#def-b1-dynamic-arrays-dynamic-array) $2^{k+1}$; the pop leaves [size](#def-b1-dynamic-arrays-dynamic-array) $2^k$, half of it, and copies $2^k$ elements back into [capacity](#def-b1-dynamic-arrays-dynamic-array) $2^k$. The state is the same as after the fill.

**14.** Each operation then copies $2^k$ elements: $m \cdot 2^k$ copies.

**15.** A growth copies $c$ elements into [capacity](#def-b1-dynamic-arrays-dynamic-array) $2c$; a shrink copies $c/4$ elements into [capacity](#def-b1-dynamic-arrays-dynamic-array) $c/2$. Either way the copied elements fill exactly half the new [capacity](#def-b1-dynamic-arrays-dynamic-array) $C$.

**16.** The next growth needs $C/2$ more pushes, the next shrink at least $C/4$ pops; a resize copies at most $C$ elements, so the copies are paid by at least $C/4$ operations: a first, crude bound of 4 per operation.

**17.** The worst sequences push up to just past a power of 2, sometimes after a shrink and a regrowth (`+++--+++`…). The largest ratio is $31/18 \approx 1.722$, at $m = 18$: seventeen pushes and one pop.

**18.** The resizes copy $1 + 2 + \dots + 2^k = 2^{k+1} - 1$ elements, and $\frac{2^{k+1} - 1}{2^k + 1} \to 2$.

**19.** The trailing 0s become 1 and the next 1 becomes 0. From $2^j$: $j + 1$ flips.

**20.** 16 per operation: from $2^{15} - 1$ (fifteen 1s), the increment flips 16 bits to reach $2^{15}$, the decrement flips them back. The output shows 16 000 flips for 1000 operations.

**21.** Each operation flips $\log_2 n + 1$ bits when the counter alternates between $2^k - 1$ and $2^k$ with $2^k
\approx n$: $\Theta(n \log n)$ in all.

**22.** Question 21 is about the standard representation, which is unique: $2^k - 1$ and $2^k$ differ in $k + 1$ bits, so any method that stores them must flip them. A redundant representation does not store either, but some equivalent form of each, which leaves room to absorb a carry later.

**23.** Yes: the potential of [Exercise 14.11](#exo-b1-dynamic-arrays-11) covers any mix. The quarter rule leaves slack in both directions after each resize; the binary counter has no slack between $2^k - 1$ and $2^k$.

**24.** *The elastic [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) theorem*: with growth $\times 2$ and shrinking to half when a quarter full, any $m$ pushes and pops from the empty [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) make at most $2m$ element copies ([Exercise 14.11](#exo-b1-dynamic-arrays-11)). The constant 2 is the smallest possible: $2^k + 1$ pushes make $2^{k+1} - 1$ copies, a ratio that approaches 2. The exhaustive search finds at most 1.722 copies per operation for $m \leq 26$, at seventeen pushes and a pop.
