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

OperationPositionComplexityReason
InsertEnd (has space)O(1)Direct write into free slot
InsertEnd (array full)O(n) once, O(1) amortisedRealloc: copy all n elements to new buffer
InsertMiddleO(n)Shift ~n/2 elements right on average
InsertStartO(n) — worst caseShift all n elements right
DeleteEnd (pop)O(1)Decrement length, no shift needed
DeleteMiddleO(n)Shift ~n/2 elements left on average
DeleteStartO(n) — worst caseShift 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.