An array is a collection of items of the same type stored at contiguous (touching, side-by-side) memory locations. Think of it like an egg carton: fixed slots, no gaps, all the same size.
A playlist of 10 songs is an array. Song 1 is at index 0, Song 5 is at index 4. To jump to any song instantly, the computer just calculates: start address + (index × size). No searching, no scanning — that's O(1) random access.
// Formula
Address = Base + (Index × Size)
1000 = 1000 + (0 × 4)
Access: Jump directly to index — 1 step! O(1)
To get the 1st item → arr[0]. To get the 4th item → arr[3]. Zero-based!
1let arr = [10, 20, 30, 40]; // JavaScript2// or3int arr[4] = {10, 20, 30, 40}; // C45arr[0] // 10 (first)6arr[2] // 30 (third)7arr[3] // 40 (fourth)8// Access = O(1) — instant!
Let's build this from scratch.
The Egg Carton Analogy
Imagine a carton that holds exactly 12 eggs. All slots are the same size. They're stuck together in one block — no gaps. You can't suddenly add a 13th slot without getting a whole new carton. That's an array.
Three Rules
1. Fixed Size: (In many languages) You declare the size upfront. Want more space? You need a new, bigger array and copy everything over.
2. Contiguous: All slots are in one block of memory, side by side. This is why the computer can instantly calculate where any element lives.
3. Same Type: Every slot holds the same kind of data. Integers with integers. Strings with strings. No mixing eggs with bowling balls.
Zero-Based Indexing
In computer science, we start counting from 0. The first element is at index 0, the fifth at index 4, the nth at index n-1. Why? Because the index represents how many steps from the start. The first item is 0 steps away.
The Magic Formula
Because arrays are contiguous, the computer can calculate any element's address instantly:
Address = Start + (Index × Size)
That's why accessing arr[1000] takes the same time as arr[0] — it's just one addition and one memory lookup. O(1) random access.
Arrays are the foundation of almost every data structure. Lists, stacks, queues, hash tables — they all use arrays under the hood. Understanding arrays is understanding how computers store and access data efficiently.
"What is the time complexity of accessing an array element by index?"
O(1) — the computer calculates the address with a simple formula and jumps directly to it.