Array
An array stores a collection of same-type values in a contiguous block of memory. Each element lives at a predictable address, enabling instant access by index.
Interactive Visualization
scores = []
14
[0]
82
[1]
37
[2]
56
[3]
91
[4]
20
[5]
Click any element to inspect its index access.
Access
O(1)Search
O(n)Insert / Delete
O(n)How it Works
- Same data type: All elements share a type so each slot is the same byte-width — this makes address arithmetic exact.
- O(1) access:
base_addr + (index × item_size)— no scanning needed. - Zero-indexed: First element is always at index
0. - Fixed vs dynamic: C arrays are fixed-size. JS/Python arrays grow automatically by allocating a larger buffer and copying all elements.
Memory Layout
// 32-bit integers, base_addr = 0x1000
scores[0] = 14 → address: 0x1000
scores[1] = 82 → address: 0x1004 (0x1000 + 1×4)
scores[2] = 37 → address: 0x1008 (0x1000 + 2×4)
scores[3] = 56 → address: 0x100C (0x1000 + 3×4)
scores[4] = 91 → address: 0x1010 (0x1000 + 4×4)
scores[5] = 20 → address: 0x1014 (0x1000 + 5×4)
Insert & Delete — Full Summary
| Operation | Position | Complexity | Reason |
|---|---|---|---|
| Insert | End (has space) | O(1) | Direct write into free slot |
| Insert | End (array full) | O(n) once, O(1) amortised | Realloc: copy all n elements to new buffer |
| Insert | Middle | O(n) | Shift ~n/2 elements right on average |
| Insert | Start | O(n) — worst case | Shift all n elements right |
| Delete | End (pop) | O(1) | Decrement length, no shift needed |
| Delete | Middle | O(n) | Shift ~n/2 elements left on average |
| Delete | Start | O(n) — worst case | Shift all n elements left |
Common Use Cases
Lists of Data
Scores, prices, user IDs — ordered sequences of same-type values.
Caching & Buffers
Network I/O and file reads use fixed-size byte arrays for performance.
Matrices (2D Arrays)
Image pixels, spreadsheets, game boards — grids as arrays of arrays.
Building Blocks
Stacks, queues, heaps, and hash tables are all built on top of arrays.
When NOT to Use Arrays
- Frequent middle/start insertions or deletions — O(n) shifting. Use a Linked List (O(1) insert/delete with a pointer).
- Key-value lookups — scanning is O(n). Use a Hash Map for O(1) average lookup.
- Frequent front removal (queue behaviour) — use a Deque or Circular Buffer for O(1) front operations.
- Unknown/unbounded size with many appends — realloc cost is amortised O(1) but real. Profile before optimising.