An array stores elements of the same size in one contiguous block of memory, so the address of any element is a single multiplication away. That is why indexing is O(1). A dynamic array (Python list, Java ArrayList, C++ std::vector, JavaScript Array) adds automatic growth with amortized O(1) appends. Arrays are the most used data structure in programming and the backing store for stacks, heaps, hash tables, matrices and strings.
Think of it like
A hallway of numbered lockers
Lockers in a hallway are identical and numbered from 0. To reach locker 37 you do not open the first 36; you walk straight to it because you know where it is. Squeezing a new locker into the middle means shifting every locker after it down by one. And when the hallway is full, you rent a hallway twice as long and move everything over, which is slow, but you rarely have to do it.
Memory layout and address calculation
An array is a contiguous run of equally sized slots. Knowing the base address (where slot 0 begins) and the element size is enough to compute the address of any slot directly, without looking at any other element.
| Index | Address (4-byte int, base 1000) | Value |
|---|---|---|
| 0 | 1000 | 17 |
| 1 | 1004 | 42 |
| 2 | 1008 | 8 |
| 3 | 1012 | 23 |
| 4 | 1016 | 4 |
[17, 42, 8, 23, 4] of 32-bit integers. Each index adds 4 bytes to the base.Static vs dynamic arrays
Static (fixed-size) array
- Size chosen at creation and never changes
- C arrays,
std::array, Javaint[], JS typed arrays - Zero overhead beyond the elements
- Appending beyond the size is impossible
Dynamic array
- Tracks a size (elements used) and a capacity (slots allocated)
- Python
list, JavaArrayList,std::vector, JSArray - Grows automatically by reallocating and copying
- Append is O(1) amortized, occasionally O(n)
| Language | Fixed size | Dynamic | Notes |
|---|---|---|---|
| C++ | int a[10], std::array<int, 10> | std::vector<int> | Elements stored inline, contiguously |
| Java | int[], String[] | ArrayList<Integer> | ArrayList stores references to boxed objects |
| Python | array.array, NumPy arrays | list | A list is an array of pointers to objects |
| JavaScript / TS | Int32Array, Float64Array | Array | Engines store dense numeric arrays compactly when they can |
How dynamic arrays grow
- 1
Room available
If
size < capacity, write the element at indexsizeand incrementsize. O(1). - 2
Full
If
size == capacity, allocate a new buffer with a larger capacity, typically 1.5× or 2×. - 3
Copy
Copy all
sizeelements into the new buffer. O(n). - 4
Release and append
Free the old buffer, then write the new element as usual.
| Append # | Capacity before | Elements copied | Capacity after |
|---|---|---|---|
| 1 | 1 | 0 | 1 |
| 2 | 1 (full) | 1 | 2 |
| 3 | 2 (full) | 2 | 4 |
| 4 | 4 | 0 | 4 |
| 5 | 4 (full) | 4 | 8 |
| 6 to 8 | 8 | 0 | 8 |
| 9 | 8 (full) | 8 | 16 |
- Pre-size when you know n.
vector.reserve(n),new ArrayList<>(n)or[0] * navoid every intermediate reallocation. - Shrink lazily. Halve the capacity when the array is a quarter full, not half full. Shrinking at half would let an alternating append/remove sequence at the boundary trigger a resize every time.
- Reallocation moves the data. In C++, pointers, references and iterators into a vector are invalidated when it grows.
Operation costs
| Operation | Time | Why |
|---|---|---|
Read or write a[i] | O(1) | Address arithmetic |
| Append at the end | O(1) amortized | Occasional O(n) resize |
| Remove from the end | O(1) | Just decrement size |
| Insert at index i | O(n − i) | Shift every later element right by one |
| Remove at index i | O(n − i) | Shift every later element left by one |
| Insert or remove at the front | O(n) | Every element shifts |
| Search, unsorted | O(n) | Linear Search |
| Search, sorted | O(log n) | Binary Search |
| Copy or slice k elements | O(k) | Each element is copied |
def insert_at(a: list[int], size: int, i: int, value: int) -> int:
"""a has spare capacity; shift a[i..size-1] right, then write. Returns the new size."""
for j in range(size, i, -1): # walk from the back so nothing is overwritten
a[j] = a[j - 1]
a[i] = value
return size + 12D arrays and row-major order
Memory is one-dimensional, so a matrix must be flattened. In row-major order (C, C++, Python's NumPy by default) each row is stored contiguously, one after another. In column-major order (Fortran, MATLAB, R, Julia) each column is contiguous.
| col 0 | col 1 | col 2 | col 3 | |
|---|---|---|---|---|
| row 0 | 0 | 1 | 2 | 3 |
| row 1 | 4 | 5 | 6 | 7 |
| row 2 | 8 | 9 | 10 | 11 |
- C and C++
int a[R][C]is a single contiguous row-major block. - Java
int[][]is an array of references to separate row arrays. Rows can differ in length (jagged arrays) and are not guaranteed to be adjacent in memory. - Python lists of lists are also arrays of pointers to row lists. NumPy arrays are true contiguous blocks.
Cache locality
CPUs do not fetch single bytes from RAM; they fetch cache lines, typically 64 bytes. Reading a[0] of an int array brings a[0] through a[15] into cache for free, and hardware prefetchers detect sequential scans and fetch ahead. Arrays are the best-case data structure for this machinery.
Cache line
64 B
16 four-byte ints per fetch
L1 cache hit
~1 ns
A few CPU cycles
Main memory
~100 ns
Roughly 100× slower than L1
Row by row (cache-friendly)
for i in rows: for j in cols: total += a[i][j]- Consecutive accesses are adjacent in memory
- Every byte of each cache line is used
Column by column (cache-hostile)
for j in cols: for i in rows: total += a[i][j]- Each access jumps
cols × 4bytes ahead - Large matrices miss cache on nearly every access; often several times slower
Common in-place techniques
Interviewers love array problems with an "O(1) extra space" constraint. A handful of techniques cover most of them, and several have their own lessons.
- Two pointers from both ends to reverse, check palindromes or find pairs in a sorted array (Two Pointers).
- Read and write pointers to filter in place: the read pointer scans everything, the write pointer marks where the next kept element goes (remove duplicates, move zeroes).
- Three reversals to rotate by k positions in O(n) time and O(1) space.
- Partitioning into regions, as in quick sort or the Dutch national flag problem (sort 0s, 1s and 2s in one pass).
- Prefix sums for O(1) range-sum queries after O(n) preprocessing (Prefix Sums & Difference Arrays).
- Sliding windows over contiguous subarrays (Sliding Window).
- Index marking: when values lie in
1..n, use the sign ofa[v − 1]to record that v was seen, with no extra array.
- 1
Reverse everything
[1, 2, 3, 4, 5, 6, 7]becomes[7, 6, 5, 4, 3, 2, 1]. - 2
Reverse the first k
With k = 3:
[5, 6, 7, 4, 3, 2, 1]. - 3
Reverse the rest
[5, 6, 7, 1, 2, 3, 4]: rotated right by 3.
Complexity
| Operation | Time | Space | Notes |
|---|---|---|---|
| Access / update by index | O(1) | O(1) | Address arithmetic |
| Append (dynamic array) | O(1) | O(1) | Amortized; a single resize is O(n) |
| Pop from the end | O(1) | O(1) | |
| Insert / delete at index i | O(n) | O(1) | Shifts n − i elements |
| Search (unsorted) | O(n) | O(1) | Linear scan |
| Search (sorted) | O(log n) | O(1) | Binary search |
| Resize | O(n) | O(n) | Allocate and copy |
A dynamic array of n elements uses O(n) space; with doubling, up to about 2n slots may be allocated.
Implementation
A growable array on top of a fixed-size buffer: doubling on append, shifting on insert and remove, and shrinking by half when only a quarter full.
from typing import Generic, Optional, TypeVar, cast
T = TypeVar("T")
class DynamicArray(Generic[T]):
"""A growable array over a fixed-size buffer, like list / ArrayList / vector."""
def __init__(self, capacity: int = 4) -> None:
self._capacity = max(1, capacity)
self._data: list[Optional[T]] = [None] * self._capacity # the fixed block
self._size = 0
def __len__(self) -> int:
return self._size
def _check(self, i: int) -> None:
if not 0 <= i < self._size:
raise IndexError("index out of range")
def get(self, i: int) -> T: # O(1)
self._check(i)
return cast(T, self._data[i])
def set(self, i: int, value: T) -> None: # O(1)
self._check(i)
self._data[i] = value
def _resize(self, new_capacity: int) -> None: # O(n)
new_data: list[Optional[T]] = [None] * new_capacity
for i in range(self._size):
new_data[i] = self._data[i]
self._data, self._capacity = new_data, new_capacity
def append(self, value: T) -> None: # amortized O(1)
if self._size == self._capacity:
self._resize(2 * self._capacity)
self._data[self._size] = value
self._size += 1
def insert(self, i: int, value: T) -> None: # O(n - i)
if not 0 <= i <= self._size:
raise IndexError("index out of range")
if self._size == self._capacity:
self._resize(2 * self._capacity)
for j in range(self._size, i, -1): # shift right, from the back
self._data[j] = self._data[j - 1]
self._data[i] = value
self._size += 1
def remove_at(self, i: int) -> T: # O(n - i)
self._check(i)
value = cast(T, self._data[i])
for j in range(i, self._size - 1): # shift left
self._data[j] = self._data[j + 1]
self._size -= 1
self._data[self._size] = None # drop the stale reference
if self._capacity > 4 and self._size <= self._capacity // 4:
self._resize(self._capacity // 2) # shrink at 1/4 full
return value
def pop(self) -> T: # amortized O(1)
return self.remove_at(self._size - 1)
arr: DynamicArray[int] = DynamicArray()
for x in range(10):
arr.append(x)
arr.insert(0, -1)
print(len(arr), arr.get(0), arr.pop(), arr.remove_at(0)) # 11 -1 9 -1Key takeaways
- Arrays are contiguous, so
address = base + i × sizegives O(1) indexing. - Dynamic arrays track size and capacity and grow geometrically, which makes append O(1) amortized even though a single resize is O(n).
- Inserting or deleting anywhere but the end shifts elements and costs O(n); watch for hidden O(n) library calls in loops.
- 2D arrays are flattened in row-major (C, NumPy) or column-major (Fortran, MATLAB) order; iterate in storage order for cache efficiency.
- Contiguity makes arrays far faster in practice than pointer-based structures with the same Big-O.
- Two pointers, read/write pointers, reversals and index marking solve most O(1)-extra-space array problems.
Common pitfalls
- Calling
pop(0),insert(0, x),shiftorremove(0)inside a loop, turning O(n) work into O(n²). - Off-by-one errors at boundaries: valid indices are 0 to n − 1, and insertion positions are 0 to n.
- Creating a Python grid with
[[0] * cols] * rows, which aliases every row to the same list. - Holding a pointer, reference or iterator into a C++ vector across a
push_backthat reallocates. - Shrinking a dynamic array at half full instead of a quarter, causing resize thrashing.
Interview tips
- Explain amortized O(1) append with the doubling argument; it is one of the most common follow-up questions.
- When asked for O(1) extra space, reach for two pointers, read/write pointers, in-place reversal or index marking.
- Mention cache locality when comparing arrays with linked lists; it shows practical understanding beyond Big-O.
Real-world applications
- The backing storage for stacks, heaps, hash tables, strings and matrices.
- Image buffers, audio samples and tensors in machine learning frameworks.
- Lookup tables and precomputed results indexed by small integers.
- Columnar databases and analytics engines that scan contiguous columns for speed.
Practice problems
Test yourself
An array of 4-byte integers starts at address 2000. Where is a[5]?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.