Understanding why accessing an array element by index is constant time
An array is like a row of lockers or mailboxes. Each locker has a number (called an index) starting from 0, and you can store something in each locker.
Example:
const fruits = ['apple', 'banana', 'orange', 'grape'];
In programming, arrays store data in contiguous memory locations, meaning they're stored right next to each other in your computer's memory. This is the key to why random access is so fast!
Random access means you can directly access any element in the array by its index, without having to look through other elements first.
Like opening a specific locker when you know its number. You go directly to locker #5 - no need to check lockers 1-4 first!
Like following a chain. To get to item #5, you must go through items 1, 2, 3, and 4 first.
Code Example:
// Accessing array element by index
const arr = [10, 20, 30, 40, 50];
const value = arr[2]; // O(1) - instant access!
// No matter if array has 5 or 5 million elements,
// accessing arr[2] takes the same timeArrays are stored in consecutive memory locations. If the first element is at memory address 1000, and each element takes 4 bytes, then:
To find any element, the computer just calculates:
memory_address = base_address + (index × element_size)This is a single calculation - it doesn't matter if the array has 10 or 10 million elements!
Unlike searching through a list, you don't need to check other elements. You know exactly where to go because of the index.
| Operation | Time Complexity | Explanation |
|---|---|---|
| Array Random Access | O(1) | Direct access by index - instant! |
| Array Search (Linear) | O(n) | Must check each element until found |
| Linked List Access | O(n) | Must traverse from beginning |
| Array Binary Search | O(log n) | Fast, but requires sorted array |
Like jumping to page 50 in a book when you know the page number. You don't flip through pages 1-49 first - you go directly to page 50!
If houses on a street are numbered sequentially (1, 2, 3, 4...), finding house #100 is easy - you know exactly where it is!
Jumping to 5:30 in a video is instant - the player calculates the exact position. You don't watch from the beginning!
Accessing any element by index takes constant time, regardless of array size
Elements are stored next to each other, allowing direct address calculation
The index tells you exactly where the element is - no guessing!