Amortized time complexity
What you'll learn: How to evaluate the average cost of appending to a dynamic array, even when occasional resizing makes a single operation expensive.
The Cost of Growing
When a dynamic array is full, you must perform a "resize": allocate a larger block of memory, copy existing elements, and free the old memory. This resize takes time because it copies every element. If you only look at this worst-case moment, adding data seems slow. However, we do not resize on every insertion.
The Movie Theater Analogy
Imagine a movie theater that starts with 10 seats. Seating the first 10 people is fast (constant time). When the 11th person arrives, the manager pauses, builds a new 20-seat theater, moves the first 10 people over, and then seats the 11th person.
That 11th person had a long wait! But the next 9 people (numbers 12 through 20) sit down instantly. If you average the "build time" across all 20 people, the extra work per person is small. This "averaged-out" cost is called Amortized Time Complexity.
Growth by Doubling
To achieve efficient amortized time, we double the capacity instead of adding a single slot. By doubling, the expensive resizes happen exponentially less frequently as the array grows. The heavy cost of resizing is spread across many fast insertions, resulting in an amortized time per push (and total time for pushes).
When implementing this in C, always use size_t for dimensions, check for overflow before arithmetic, use a temporary pointer for realloc, and never attempt to append if the memory allocation fails.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
bool add_element(int **array, size_t *size, size_t *capacity, int value) {
if (*size == *capacity) {
// Check for capacity overflow before doubling
if (*capacity > SIZE_MAX / 2) {
return false;
}
size_t new_capacity = (*capacity == 0) ? 1 : (*capacity * 2);
// Check for allocation size overflow before multiplying
if (new_capacity > SIZE_MAX / sizeof(int)) {
return false;
}
// Use a temporary pointer for realloc
int *temp = realloc(*array, new_capacity * sizeof(int));
if (!temp) {
// Preserve array, size, and capacity on failure
return false;
}
*array = temp;
*capacity = new_capacity;
}
// Only append if we successfully ensured capacity
(*array)[(*size)++] = value;
return true;
}
int main(void) {
int *arr = NULL;
size_t size = 0;
size_t cap = 0;
if (add_element(&arr, &size, &cap, 42)) {
printf("Added %d. Size: %zu, Capacity: %zu\n", arr[0], size, cap);
}
free(arr);
return 0;
}
Key takeaway
Amortized complexity proves dynamic arrays are efficient: doubling capacity ensures an amortized cost per push, while rigorous overflow and allocation checks prevent failures from corrupting existing data.