Arrays
The most fundamental data structure — contiguous memory, O(1) indexing, and why it powers almost everything else.
An array stores elements of the same size in one contiguous block of memory. That single property — elements sitting side by side — is what makes arrays the fastest structure for indexed access and the building block for strings, heaps, hash tables, matrices and dynamic arrays.
Why indexing is O(1)
Because elements are contiguous and equally sized, the address of any element is a single multiplication and addition:
For an int[] starting at address 0x1000 with 4-byte ints, arr[3] lives at 0x1000 + 3 × 4 = 0x100C. The CPU computes that in one instruction, no matter how large the array.
Operations and their cost
| Operation | Time | Why |
|---|---|---|
Access arr[i] | O(1) | Address arithmetic |
Update arr[i] = x | O(1) | Address arithmetic |
| Search (unsorted) | O(n) | Must check each element |
| Search (sorted) | O(log n) | Binary search |
| Insert / delete at end | O(1)* | *Amortized for dynamic arrays |
| Insert / delete at index i | O(n) | Elements after i must shift |
Inserting in the middle is expensive because every later element moves one slot:
Static vs dynamic arrays
A static array has a fixed size chosen at creation (int[] a = new int[10] in Java, int a[10] in C). A dynamic array — Java ArrayList, Python list, JavaScript Array, C++ vector — grows automatically.
How a dynamic array grows
It keeps a backing static array with spare capacity. When it is full, it allocates a new array (typically 1.5× or 2× larger), copies everything over, and frees the old one.
size = 4, capacity = 4— the array is full.append(x)triggers a resize: allocate capacity 8.- Copy the 4 existing elements — O(n) for this one append.
- Write
xat index 4. The next 3 appends are O(1) again.
Code
import java.util.*;
int[] fixed = new int[5]; // static: zero-initialised, fixed length
int[] primes = {2, 3, 5, 7, 11};
System.out.println(primes[2]); // 5 — O(1)
List<Integer> list = new ArrayList<>(); // dynamic array
list.add(10); // amortized O(1)
list.add(0, 5); // O(n): shifts everything right
list.remove(list.size() - 1); // O(1): remove from end
Collections.sort(list); // O(n log n)
// 2D array: an array of arrays (rows can differ in length)
int[][] grid = new int[3][4];
grid[1][2] = 9;fixed = [0] * 5 # list of 5 zeros
primes = [2, 3, 5, 7, 11]
print(primes[2]) # 5 — O(1)
print(primes[-1]) # 11 — negative indices count from the end
nums = [] # Python lists are dynamic arrays
nums.append(10) # amortized O(1)
nums.insert(0, 5) # O(n)
nums.pop() # O(1) from the end
nums.pop(0) # O(n) from the front — use collections.deque instead
sub = primes[1:4] # slicing copies: O(k)
grid = [[0] * 4 for _ in range(3)] # NOT [[0]*4]*3 — that aliases the same row 3 times!
grid[1][2] = 9const fixed = new Array<number>(5).fill(0);
const primes = [2, 3, 5, 7, 11];
console.log(primes[2]); // 5 — O(1)
console.log(primes.at(-1)); // 11
const nums: number[] = [];
nums.push(10); // amortized O(1)
nums.unshift(5); // O(n): shifts every element
nums.pop(); // O(1)
nums.splice(1, 1); // remove at index 1: O(n)
// For numeric hot loops, typed arrays are truly contiguous & fixed-type
const buf = new Int32Array(1024);
const grid = Array.from({ length: 3 }, () => new Array(4).fill(0));
grid[1][2] = 9;Multidimensional arrays
A 2D array m[r][c] with R rows and C columns is usually stored in row-major order (C, Java, Python/NumPy default): row 0, then row 1, and so on.
Common techniques
Most array problems are solved with a handful of patterns — each has a full lesson in Coding Patterns:
Pitfalls
- Off-by-one errors. Valid indices are
0 … n-1. Loops usei < n, noti <= n. - Aliasing. Assigning an array copies the reference, not the data. Use
Arrays.copyOf,list.copy()/ slicing, or[...arr]/structuredClone. - Removing while iterating shifts indices under you. Iterate backwards, or build a new array.
- Front insertion in a loop is O(n²). Append then reverse, or use a deque.
- Arrays are contiguous: O(1) indexed access via
base + i × size, and excellent cache locality. - Insert/delete in the middle is O(n) because elements shift.
- Dynamic arrays grow geometrically, giving amortized O(1) append.
- 2D arrays are usually row-major; iterate rows in the outer loop.
QWhy is accessing arr[i] O(1) but finding a value O(n)?easy
Access uses the index to compute the memory address directly. Finding a value requires comparing against elements because the value gives no information about its position — unless the array is sorted, which enables O(log n) binary search.
QArrayList vs LinkedList in Java — which would you choose?medium
Almost always ArrayList. It has O(1) random access, amortized O(1) append, and far better cache locality. LinkedList only wins for frequent insertions/removals through an iterator in the middle of a huge list — and even then, the pointer-chasing cost often makes ArrayList faster in practice. For queue/deque usage, prefer ArrayDeque.
QWhat growth factor should a dynamic array use, and why not grow by a constant?medium
Growing by a constant k makes n appends cost O(n²/k) total — O(n) amortized per append. Any geometric factor (1.5×, 2×) gives amortized O(1). Smaller factors waste less memory; 1.5× also lets the allocator reuse freed blocks. Java's ArrayList uses 1.5×, CPython ~1.125× plus a constant, many C++ libraries 2×.
QRotate an array by k positions in O(1) extra space.medium
Reverse the whole array, then reverse the first k elements and the remaining n−k separately (with k %= n). Each element moves exactly twice: O(n) time, O(1) space.