The Array is the most ubiquitous data structure in computer science. Arrays store elements in contiguous (sequential) memory locations, providing lightning-fast $O(1)$ constant-time random access via direct memory offset arithmetic.
Imagine a luxury hotel with numbered rooms 100, 101, 102, 103... arranged sequentially along a straight corridor:
100 starts at memory address 0x1000 and each room is 4 meters wide, you can calculate the exact location of Room 105 instantly:$$\text{Address} = \text{Base Address} + (\text{Index} \times \text{Size}) = 0x1000 + (5 \times 4) = 0x1014$$
list, JavaScript Array, C++ std::vector, Java ArrayList): Automatically resize when capacity is reached.When you append to an array whose internal capacity is full:
While resizing copies $n$ elements and takes $O(n)$ time, resizing happens very infrequently (at powers of 2: $1, 2, 4, 8, 16, 32 \dots$).
If you append $n$ elements: $$\text{Total Copies} = 1 + 2 + 4 + 8 + \dots + n < 2n$$ Averaging $2n$ copying steps across $n$ operations yields: $$\frac{2n}{n} = 2 \text{ operations per append on average} \implies \mathbf{O(1)\text{ Amortized Time!}}$$
Modern CPUs fetch data from RAM in 64-byte Cache Lines rather than single bytes. Because array elements sit contiguously side-by-side in RAM, loading arr[0] into CPU L1 cache automatically loads arr[1], arr[2], and arr[3] simultaneously. This phenomenon is called Spatial Locality, making arrays up to 10x faster in practice than pointer-based data structures like Linked Lists.
| Operation | Array Complexity | Reason |
|---|---|---|
Lookup by Index (arr[i]) | $O(1)$ | Direct memory offset calculation |
| Append to End | $O(1)$ Amortized | Occasional resize amortized over $n$ appends |
Insert at Beginning (unshift) | $O(n)$ | Every existing element must shift 1 index to the right |
Delete from Beginning (shift) | $O(n)$ | Every existing element must shift 1 index to the left |
| Search by Value (unsorted) | $O(n)$ | Linear scan across all elements |
arr[10] on an array allocated with size 5 in languages like C or C++?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.