What is an array
An array stores elements in a contiguous block of memory so you can jump to any index in O(1). Think of numbered lockers in a straight line. A 2D array is the same idea as a grid — rows × columns — used for matrices and image pixels.
arr[i]. Address is base + i × sizeof(type).arr[i][j]. C stores it row-major: base + (i × cols + j) × sizeof(type).Approach
A 1D array is a fixed-size, ordered sequence of elements stored at consecutive memory addresses. Every element is the same type, so the CPU can jump to any element instantly using simple arithmetic.
Core Operations
i. The CPU computes the address as base + i × size and reads directly. No traversal needed. O(1).0 to n−1 in order, one step at a time. O(n).pos, shift every element from pos to end one step to the right, then place the new value. O(n).pos, then shift every element after it one step to the left to close the gap. O(n).Key Insight
Arrays are fast at the edges (append/pop) and fast at random reads, but expensive in the middle — insertions and deletions force a chain of shifts. The larger the array, the worse the middle operations get.
Memory Layout — arr = [10, 25, 7, 42, 18]
| idx | [0] | [1] | [2] | [3] | [4] |
| val | 10 | 25 | 7 | 42 | 18 |
| addr | 0x1000 | 0x1004 | 0x1008 | 0x100C | 0x1010 |
Highlighted cell [2] = value 7 at address 0x1008 — accessed in O(1) via base + 2×4
A 2D array is a grid of rows and columns. Internally, it is still stored as a flat block of memory — rows are laid out one after another (row-major order). You address each cell with two indices: arr[row][col].
Core Operations
(i × cols + j) × size and reads it directly. Still O(1).i, iterate over all columns j = 0 … cols−1. Reads contiguous memory → cache-friendly. O(cols).j, iterate over all rows. Reads non-contiguous memory (jumps by cols each step) → less cache-friendly. O(rows).Key Insight — Row-Major Order
Even though you think in rows and columns, the computer stores all of row 0 first, then all of row 1, then row 2 — in one long flat sequence. Traversing row by row is always faster than column by column because it reads memory in order, keeping the CPU cache hot.
Grid Visualization — 3×4 matrix · cell [1][2] selected
| col 0 | col 1 | col 2 | col 3 | |
|---|---|---|---|---|
| row 0 | 1 | 2 | 3 | 4 |
| row 1 | 5 | 6 | 7 | 8 |
| row 2 | 9 | 10 | 11 | 12 |
Flat in memory (row-major)
Cell [1][2] = value 7. Flat offset = (1×4 + 2) × 4 = 24 bytes from base.
Complexity Summary
| Operation | 1D Array | 2D Array |
|---|---|---|
| Access by index | O(1) | O(1) |
| Traverse all elements | O(n) | O(n × m) |
| Insert / Delete at end | O(1) | N/A (fixed grid) |
| Insert / Delete at middle | O(n) | N/A (fixed grid) |
Interactive Array Visualizer
Length
8
Memory
32 B
Access
O(1)
Insert
O(n)
Array Representations
Implementation
Algorithm & Pseudocode