
The key takeaways
- A dynamic array stores elements in a contiguous heap buffer tracked by three fields: pointer, length, and capacity.
- Amortized O(1) append holds because doubling capacity means total copy work across all resizes sums to n, so n appends cost O(n) in total.
- Index access and tail-pop are O(1) exact; insert or delete at any other position shifts elements and costs O(n).
- Growth factors differ by language: CPython uses ~1.125, Java ArrayList 1.5, and C++/Rust/.NET double at 2.0; any factor above 1 gives amortized O(1).
- Cache-friendly layout makes dynamic array iteration measurably faster in practice than a linked list, even though both are O(n) on paper.
- Use a dynamic array for sliding window, two-pointer, prefix sum, and "collect then query" patterns where O(1) random access is load-bearing.
- Switch to a deque when you need O(1) at both ends, or a linked list when most operations are cursor-based middle insertions.
You type arr.append(x) and move on. What you just did might have allocated a brand-new heap buffer twice the size of the old one, copied every existing element across, freed the original block, and handed you back an amortized O(1) result. The whole thing happened in a single line without you noticing.
Understanding the dynamic array time complexity behind that one call is what separates "I know the API" from "I know why it's fast." In a technical interview, that difference is the entire ballgame.
A dynamic array is a contiguous heap-allocated buffer with a fixed capacity, wrapped by a header that tracks how much of that capacity is actually used. The mental model: a static array that quietly swaps itself for a bigger one whenever it fills up. When the buffer is full, the structure grows (usually doubling), copies, and continues. Reach for it whenever you need O(1) random access, cache-friendly iteration, or a sequence you'll build by appending.

Know your O(). The interviewer always does.
The Three-Field Header: What's Really in Memory
Every list, Vec, ArrayList, and std::vector stores the same three things internally:
struct DynArray<T> {
data: *T // pointer to heap-allocated buffer
length: int // elements currently stored
capacity: int // total slots allocated
}That's it. The header lives on the stack (or embedded in the object). The elements live on the heap at the address stored in data.
When length < capacity, appending is one pointer write and one increment. When length == capacity, the array must grow before accepting another element.
Here is the in-memory layout of a dynamic array holding [10, 20, 30] with capacity 8:

The header is tiny. The heap buffer is where the actual work happens. Slots 3 through 7 belong to the allocator. You do not touch them.
Slots 3 through 7 are allocated but uninitialized. They belong to the allocator. You do not read them.
The Growth Factor: Why Doubling (Mostly)
When the buffer fills, the array allocates a new block of size capacity * growth_factor, copies every element, and frees the old block. Growth factors vary by language and implementation:
| Language | Structure | Growth Factor | Notes |
|---|---|---|---|
| Python 3 (CPython) | list |
~1.125 | new = old + old/8 + (3 or 6) |
| Java | ArrayList |
1.5 | old + (old >> 1) |
| C++ GCC | std::vector |
2.0 | Exact doubling |
| C++ MSVC | std::vector |
1.5 | Microsoft's CRT |
| Go | slice | 2.0 small, ~1.25 large | Blends above cap 256 |
| Rust | Vec |
2.0 (typical) | Not formally specified |
| .NET | List<T> |
2.0 | Initial capacity 4 |
Python's conservative ~1.125 reflects a practical tradeoff. Python lists are used for everything: small temp buffers, huge result sets, argument lists in function calls, and whatever someone named my_list at 2am. Memory efficiency matters more than raw append throughput. Java's 1.5 splits the difference. C++ and Rust prefer 2.0, accepting slightly more wasted space in exchange for fewer total allocations.
Any growth factor strictly greater than 1 gives amortized O(1) appends. The math does not care whether you use 1.5 or 2.0. It cares that each resize is geometrically rarer than the last.
![Diagram showing a dynamic array resize: an old buffer of capacity 4 holding [10, 20, 30, 40] is marked "BUFFER FULL" and freed. A new buffer of capacity 8 is allocated, the four elements are copied, and four empty slots remain.](https://assets.spacecomplexity.ai/blog/content-images/dynamic-array-time-complexity/1779639880803-growth-doubling.png)
The copy is O(n). That's fine. It only happens once every n appends, and each time it happens, n doubles.
Why append() Doesn't Cost What You Think It Costs
The worst-case cost of one append is O(n): you might trigger a resize that copies n elements. But that copy happens at most once every n appends, and each time it happens, n doubles, so it happens exponentially less often as the array grows.
Start from an empty array with capacity 1, doubling each resize. Insert n elements.
Resizes happen when the array size hits 1, 2, 4, 8, ..., n/2. The copy cost at each resize:
resize at size 1: copy 1 element
resize at size 2: copy 2 elements
resize at size 4: copy 4 elements
...
resize at size n/2: copy n/2 elements
total copy work = 1 + 2 + 4 + ... + n/2 = n - 1That geometric series sums to n minus 1. Add n for the n actual insertions. Total work for n appends is less than 2n, so average cost per append is less than 2. O(1) amortized.
The accounting (banker's) argument makes the mechanism concrete. Charge each append 2 credits instead of 1:
- 1 credit covers the current write.
- 1 credit is banked on the newly inserted element.
When the array next doubles (say from size k to 2k), we have k banked credits, one per element added since the last resize. That covers copying all k elements to the new buffer. Each element is moved at most once between doublings, and doublings happen at exponentially increasing intervals.

The spikes are real. They're also rare. That's the whole trick.
The potential method formalizes this. Define potential Φ = 2 × length - capacity. Analyze two cases:
Normal append (no resize). Actual cost = 1. New length = old length + 1, capacity unchanged. ΔΦ = 2. Amortized cost = 1 + 2 = 3.
Resize append (length = capacity = n before append). Actual cost = n + 1 (copy n elements, write new one). After resize, capacity = 2n, length = n + 1. ΔΦ = (2(n+1) - 2n) - (2n - n) = 2 - n. Amortized cost = (n + 1) + (2 - n) = 3.
Both cases cost 3. Amortized O(1), confirmed. n appends cost at most 3n work total, O(n).
Dynamic Array Time Complexity: What Every Operation Actually Costs
| Operation | Avg Time | Worst Time | Extra Space |
|---|---|---|---|
| Get / set by index | O(1) | O(1) | O(1) |
| Append (push to end) | O(1) amortized | O(n) | O(1) amortized |
| Pop from end | O(1) | O(1) | O(1) |
| Insert at arbitrary index | O(n) | O(n) | O(1) |
| Delete at arbitrary index | O(n) | O(n) | O(1) |
| Search (unsorted) | O(n) | O(n) | O(1) |
| Iterate all elements | O(n) | O(n) | O(1) |
Get and set by index are O(1) because elements sit at predictable addresses. Given base pointer data, element size s (known at compile time for typed languages), and index i, the address is always data + i * s. One multiply, one add. No pointer chasing, no hash computation, no tree walk.
Pop from the end is O(1). You decrement length. The element is still physically in the buffer but invisible to the API. No shifting required. This is why you always pop from the tail, not the front.
Insert at an arbitrary index is O(n). To place a new element at position i, every element from i to length - 1 must shift one slot to the right. In the worst case, inserting at index 0 shifts every element. The shift is a contiguous memory move (memmove), which is fast in practice due to CPU block copy instructions, but it's still proportional to n.
Delete at an arbitrary index is O(n) for the same reason. The gap left by the removed element must be closed by shifting everything after it left by one slot.
One non-obvious fact: insert and delete at index 0 are not just worst-case examples, they are fully O(n) on every call. If you repeatedly prepend, you are paying n copies per prepend. That adds up fast and your interviewer will notice. A deque (double-ended queue) beats a dynamic array for workloads that need O(1) at both ends. A linked list beats it for workloads that mostly insert and delete in the middle with a cursor already in place. The dynamic array wins at the tail and at random access. Everything else is a tradeoff.
One Structure, Every Language
Python's list is a dynamic array backed by a C array of PyObject* pointers. Every element is a heap-allocated object reference, so the buffer stores pointers, not values directly.
arr: list[int] = []
# Append - O(1) amortized
arr.append(10)
arr.append(20)
arr.append(30)
# Index access - O(1)
print(arr[1]) # 20
# Pop from end - O(1)
last = arr.pop()
# Insert at index - O(n)
arr.insert(1, 99)
# Delete at index - O(n)
del arr[1]
# Search - O(n)
index = arr.index(10) if 10 in arr else -1
# Inspect overallocation
import sys
print(sys.getsizeof(arr)) # header + capacity slots (not just length)arr = []
# Append - O(1) amortized
arr.append(10)
arr.append(20)
arr.append(30)
# Index access - O(1)
print arr[1] # 20
# Pop from end - O(1)
last = arr.pop()
# Insert at index - O(n)
arr.insert(1, 99)
# Delete at index - O(n)
del arr[1]
# Search - O(n)
index = arr.index(10) if 10 in arr else -1JavaScript's Array is not a typed contiguous array internally. V8 uses a fast path that stores small integer arrays contiguously (Smi elements), but for mixed types it falls back to a hash-backed store. For typed numeric work, Int32Array or Float64Array gives true contiguous memory.
const arr = [];
// Append - O(1) amortized
arr.push(10);
arr.push(20);
arr.push(30);
// Index access - O(1)
console.log(arr[1]); // 20
// Pop from end - O(1)
const last = arr.pop();
// Insert at index - O(n)
arr.splice(1, 0, 99);
// Delete at index - O(n)
arr.splice(1, 1);
// Search - O(n)
const index = arr.indexOf(10);const arr: number[] = [];
// Append - O(1) amortized
arr.push(10);
arr.push(20);
arr.push(30);
// Index access - O(1)
console.log(arr[1]); // 20
// Pop from end - O(1)
const last: number | undefined = arr.pop();
// Insert at index - O(n)
arr.splice(1, 0, 99);
// Delete at index - O(n)
arr.splice(1, 1);
// Search - O(n)
const index: number = arr.indexOf(10);ArrayList<E> starts with a backing array of capacity 10 (deferred until the first add). When full, it grows to oldCapacity + (oldCapacity >> 1), a 50% increase.
import java.util.ArrayList;
import java.util.List;
List<Integer> arr = new ArrayList<>();
// Append - O(1) amortized
arr.add(10);
arr.add(20);
arr.add(30);
// Index access - O(1)
int value = arr.get(1); // 20
// Pop from end - O(1) amortized
int last = arr.remove(arr.size() - 1);
// Insert at index - O(n)
arr.add(1, 99);
// Delete at index - O(n)
arr.remove(1);
// Search - O(n)
int index = arr.indexOf(10);std::vector<T> stores elements directly (not pointers to elements), giving you true value semantics and a fully contiguous block. GCC grows by 2x. Call reserve() upfront when you know the final size to avoid all reallocations.
#include <algorithm>
#include <vector>
std::vector<int> arr;
arr.reserve(10); // optional: skip reallocations if size is known
// Append - O(1) amortized
arr.push_back(10);
arr.push_back(20);
arr.push_back(30);
// Index access - O(1)
int value = arr[1]; // 20
// Pop from end - O(1)
arr.pop_back();
// Insert at index - O(n)
arr.insert(arr.begin() + 1, 99);
// Delete at index - O(n)
arr.erase(arr.begin() + 1);
// Search - O(n)
auto it = std::find(arr.begin(), arr.end(), 10);
int index = (it != arr.end()) ? static_cast<int>(std::distance(arr.begin(), it)) : -1;No standard dynamic array in C. Here is a clean, minimal manual implementation.
#include <stdlib.h>
#include <string.h>
typedef struct {
int *data;
size_t length;
size_t capacity;
} DynArray;
DynArray *dynarray_create(void) {
DynArray *arr = malloc(sizeof(DynArray));
arr->capacity = 4;
arr->length = 0;
arr->data = malloc(arr->capacity * sizeof(int));
return arr;
}
static void grow_if_needed(DynArray *arr) {
if (arr->length < arr->capacity) {
return;
}
arr->capacity *= 2;
arr->data = realloc(arr->data, arr->capacity * sizeof(int));
}
void dynarray_push(DynArray *arr, int value) {
grow_if_needed(arr);
arr->data[arr->length++] = value;
}
int dynarray_pop(DynArray *arr) {
return arr->data[--arr->length];
}
int dynarray_get(DynArray *arr, size_t index) {
return arr->data[index];
}
void dynarray_insert(DynArray *arr, size_t index, int value) {
grow_if_needed(arr);
memmove(arr->data + index + 1,
arr->data + index,
(arr->length - index) * sizeof(int));
arr->data[index] = value;
arr->length++;
}
void dynarray_delete(DynArray *arr, size_t index) {
memmove(arr->data + index,
arr->data + index + 1,
(arr->length - index - 1) * sizeof(int));
arr->length--;
}
int dynarray_search(DynArray *arr, int target) {
for (size_t i = 0; i < arr->length; i++) {
if (arr->data[i] == target) {
return (int)i;
}
}
return -1;
}
void dynarray_free(DynArray *arr) {
free(arr->data);
free(arr);
}Go slices carry the three-field header (pointer, length, capacity) in exactly the form described above. The append built-in handles growth and returns a new slice header, which is why you must always reassign: arr = append(arr, x). Forgetting the reassignment is the Go rite of passage. Everyone does it once.
package main
import "fmt"
func main() {
arr := make([]int, 0, 4) // len=0, cap=4
// Append - O(1) amortized
arr = append(arr, 10, 20, 30)
// Index access - O(1)
fmt.Println(arr[1]) // 20
// Pop from end - O(1)
last := arr[len(arr)-1]
arr = arr[:len(arr)-1]
// Insert at index - O(n)
i := 1
arr = append(arr, 0) // extend length by one
copy(arr[i+1:], arr[i:]) // shift elements right
arr[i] = 99
// Delete at index - O(n)
arr = append(arr[:i], arr[i+1:]...)
// Search - O(n)
for idx, v := range arr {
if v == 10 {
fmt.Println("found at", idx)
break
}
}
_ = last
}Vec<T> stores a raw pointer, length, and capacity. It owns its allocation and drops all elements when it goes out of scope. Rust's ownership model means you cannot accidentally hold a dangling pointer to a reallocated buffer. The borrow checker rejects code that holds a reference into a Vec and then calls a mutating method. This catches an entire class of C++ bugs at compile time.
fn main() {
let mut arr: Vec<i32> = Vec::new();
// Append - O(1) amortized
arr.push(10);
arr.push(20);
arr.push(30);
// Index access - O(1)
println!("{}", arr[1]); // 20
// Pop from end - O(1), returns Option<T>
let last = arr.pop();
// Insert at index - O(n)
arr.insert(1, 99);
// Delete at index - O(n), returns removed element
arr.remove(1);
// Search - O(n)
let index = arr.iter().position(|&x| x == 10);
println!("{:?} {:?}", last, index);
}Swift Array uses copy-on-write semantics. The backing buffer is shared between copies until one copy is mutated, at which point the runtime makes a private copy. This makes passing arrays into functions cheap but can cause surprising O(n) costs on the first mutation.
var arr: [Int] = []
// Append - O(1) amortized
arr.append(10)
arr.append(20)
arr.append(30)
// Index access - O(1)
print(arr[1]) // 20
// Pop from end - O(1)
let last = arr.removeLast()
// Insert at index - O(n)
arr.insert(99, at: 1)
// Delete at index - O(n)
arr.remove(at: 1)
// Search - O(n)
let index = arr.firstIndex(of: 10)On the JVM, mutableListOf<T>() returns a java.util.ArrayList. On other Kotlin targets (Kotlin/Native, Kotlin/JS), the runtime provides its own implementation, but semantics are the same.
fun main() {
val arr = mutableListOf<Int>()
// Append - O(1) amortized
arr.add(10)
arr.add(20)
arr.add(30)
// Index access - O(1)
println(arr[1]) // 20
// Pop from end - O(1) amortized
val last = arr.removeAt(arr.size - 1)
// Insert at index - O(n)
arr.add(1, 99)
// Delete at index - O(n)
arr.removeAt(1)
// Search - O(n)
val index = arr.indexOf(10)
println("$last $index")
}List<T> starts with capacity 0, allocates 4 on the first add, and doubles from there.
using System.Collections.Generic;
var arr = new List<int>();
// Append - O(1) amortized
arr.Add(10);
arr.Add(20);
arr.Add(30);
// Index access - O(1)
Console.WriteLine(arr[1]); // 20
// Pop from end - O(1)
int last = arr[^1];
arr.RemoveAt(arr.Count - 1);
// Insert at index - O(n)
arr.Insert(1, 99);
// Delete at index - O(n)
arr.RemoveAt(1);
// Search - O(n)
int index = arr.IndexOf(10);Ruby's Array is implemented in C and uses a doubling growth strategy internally.
arr = []
# Append - O(1) amortized
arr.push(10)
arr.push(20)
arr.push(30)
# Index access - O(1)
puts arr[1] # 20
# Pop from end - O(1)
last = arr.pop
# Insert at index - O(n)
arr.insert(1, 99)
# Delete at index - O(n)
arr.delete_at(1)
# Search - O(n)
index = arr.index(10)PHP's native array is not a dynamic array. It's an ordered hash table backed by a doubly-linked list of hash buckets. This surprises people. Then it explains some things. Then it's fine. Integer-indexed arrays behave like dynamic arrays from the outside, but the backing structure carries hash-table overhead. For true contiguous storage you can use SplFixedArray, which is fixed-size but stores values in a plain C array without hash overhead.
<?php
$arr = [];
// Append - O(1) amortized (hash table, not contiguous array)
$arr[] = 10;
$arr[] = 20;
$arr[] = 30;
// Index access - O(1) average (hash lookup)
echo $arr[1]; // 20
// Pop from end - O(1)
$last = array_pop($arr);
// Insert at index - O(n) for reindexing
array_splice($arr, 1, 0, [99]);
// Delete at index - O(n) for reindexing
array_splice($arr, 1, 1);
// Search - O(n)
$index = array_search(10, $arr);What Problems Does It Solve?
Dynamic arrays are the right container for most sequences. They excel at:
- Cache-friendly iteration. Elements sit adjacent in memory. The CPU prefetcher loads them sequentially into cache lines before you even ask. Iterating a dynamic array is measurably faster than iterating a linked list in practice, even though both are O(n) on paper.
- Random access by index. If you need the kth element, a single arithmetic operation gets you there.
- Append-heavy construction. Parsing tokens, collecting BFS results, building output arrays: start empty, append as you go, pay amortized O(1) per element.
- Two-pointer and sliding window algorithms. Both patterns require O(1) jumps by index. They do not work on linked lists without degrading to O(n) per step.
- Prefix sums, DP tables, auxiliary arrays. Any algorithm that needs to look up arr[i - 1] or arr[i + k] while iterating needs a flat, addressable block.
Recognizing the Pattern: When Is a Dynamic Array the Right Call?
Signal 1: The problem involves contiguous elements or subarrays
If a problem talks about subarrays, substrings, or any contiguous range of a sequence, a dynamic array is almost always the underlying structure. The word "contiguous" is a signal that random access matters.
Worked example: Maximum subarray sum (Kadane's algorithm)
Problem: find the contiguous subarray with the largest sum.
Why a dynamic array: the algorithm scans left to right, maintaining a running sum. Each element is visited once in sequence. The flat memory layout keeps the CPU cache warm the entire time. There is no tree to walk, no hash to compute, no pointer to follow.
def max_subarray(nums: list[int]) -> int:
current = best = nums[0]
for num in nums[1:]:
current = max(num, current + num)
best = max(best, current)
return bestIf nums were a linked list, nums[i] would be O(i). The whole algorithm degrades to O(n^2). The dynamic array's O(1) index access is load-bearing.
Signal 2: You need to build a result incrementally and then process it
Worked example: Two-sum on a sorted array
Problem: given a sorted array, find two indices whose values sum to a target.
Why a dynamic array: you place two pointers at opposite ends and move them inward. Every step reads arr[left] and arr[right]. O(1) each. The sorted order plus addressable memory makes this O(n) total.
def two_sum_sorted(nums: list[int], target: int) -> tuple[int, int]:
left, right = 0, len(nums) - 1
while left < right:
total = nums[left] + nums[right]
if total == target:
return left, right
if total < target:
left += 1
else:
right -= 1
return -1, -1The moment you see a sorted sequence and a pair or window query, your first thought should be: this is an array, I address it by index, I do not need to walk from the start.
Signal 3: The problem says "collect and return" or "build and then query"
Any time you are accumulating a result of unknown size, append to a dynamic array. BFS levels, merge results, filtered outputs: start with arr = [], append as you go, return at the end. The amortized O(1) append makes this the cheapest way to grow a collection in most languages.
The Short Version
- A dynamic array is a three-field header (pointer, length, capacity) wrapping a fixed heap buffer.
- When capacity is exhausted, it allocates a new buffer at
capacity * growth_factor, copies elements, and frees the old block. Growth factors range from ~1.125 (CPython) to 2.0 (C++, Rust, .NET). - Append is O(1) amortized because total copy work across all resizes sums to n (geometric series), so n appends cost O(n) total, less than 2 credits per append.
- Index access and end-pop are O(1) exact. Insert and delete at arbitrary positions are O(n) due to element shifting.
- Cache-friendly memory layout makes dynamic arrays faster in practice than linked lists for iteration, even at the same asymptotic complexity.
- Reach for it on contiguous-sequence problems, sliding windows, two-pointer patterns, prefix sums, and any "build and then query" workload.
If you want to practice explaining these tradeoffs out loud, under real interview pressure, SpaceComplexity runs voice-based mock DSA interviews that push you from "I know the answer" toward "I can explain it clearly under pressure." That gap is where offers are won or lost.
For more on recognizing array-based patterns, see Nested Loops Will Cost You the Offer. The Sliding Window Algorithm Won't.. If you're reaching for dynamic arrays to back a DP solution, Dynamic Programming Is Just Recursion With a Memory. Here's the Framework. has the pattern you need. Hash maps share the same amortized O(1) story, Hash Map Time Complexity: How O(1) Really Works shows where the similarity ends.
Further Reading
- Dynamic array on Wikipedia, canonical reference for growth factor analysis and the history of the structure.
- Amortized analysis on Wikipedia, covering all three proof methods, aggregate, accounting, and potential, used in this article.
- std::vector on cppreference, the authoritative C++ reference covering guarantees, iterator invalidation rules, and all member functions.
- Go Slices: usage and internals, the official Go blog post on slice headers, append semantics, and the subtle copy behavior.
- Rust Vec documentation, covers the (ptr, len, cap) layout, growth behavior, and unsafe operations in full detail.
