Arrays
How arrays are stored in memory, what each operation costs, how dynamic arrays grow, and what interviewers ask about arrays.
On this page
An array is a sequence of items stored next to each other in memory and numbered from 0. It solves the problem of reaching the item at a known position immediately, without searching. Reach for an array whenever you have an ordered collection that you mostly read by index or add to at the end.
The price of that layout is that the items cannot have gaps. Inserting or deleting anywhere except the end forces the items after that position to move, so those operations are slow on a large array.
How an array is stored
An array keeps its items in one unbroken block of memory, and every slot has the same size. The computer only remembers the address where the block starts. The address of item i is the start address plus i times the slot size. If the block starts at 1000 and each slot takes 4 bytes, item 3 is at 1000 + 3 × 4 = 1012, whether the array has 5 items or 5 million.
Because the address is a single calculation, reading or writing arr[i] is O(1). This is also why indexes start at 0: the index is the number of slots to skip from the start.
A JavaScript array or a Python list can hold values of different types and sizes. Each slot then holds a reference, which is a fixed-size pointer to the real value, so the slots are still the same size and still sit side by side.
Inserting and deleting shift the items
To insert a new item at index 1, every item from index 1 onwards must first move one slot to the right. The shifting has to start from the end, so that no value is overwritten before it has been copied. The trace below inserts 9 at index 1 of [3, 8, 5, 2].
add one empty slot at the endfor i from last index down to index + 1: arr[i] = arr[i - 1]arr[index] = value- arr031825324
- index
- 1
- value
- 9
1To insert 9 at index 1, first add one empty slot at the end of the array.
- arr0318253242i
- index
- 1
- value
- 9
- moves
- 1
2Copy 2 from slot 3 into the empty slot 4.
- arr03182535i42
- index
- 1
- value
- 9
- moves
- 2
3Copy 5 from slot 2 into slot 3. The old 2 is safe in slot 4.
- arr031828i3542
- index
- 1
- value
- 9
- moves
- 3
4Copy 8 from slot 1 into slot 2. Slot 1 can now be overwritten safely.
- arr0319283542
- index
- 1
- value
- 9
- moves
- 3
5The loop finishes because the next value of
iwould beindex, so no more items need to move. Write 9 into slot 1. - arr0319283542
- moves
- 3
- worst case
- n
6The insert took 3 moves, one for each item after the insert position. Inserting at index 0 of an array with a million items would take a million moves.
Deleting is the reverse. Every item after the removed one moves one slot to the left to close the gap. Inserting or deleting at index i therefore costs about n − i moves, which is cheap near the end and O(n) at the front.
// What arr.splice(index, 0, value) does for you.
function insertAt(arr, index, value) {
arr.push(undefined); // make room at the end
for (let i = arr.length - 1; i > index; i--) {
arr[i] = arr[i - 1]; // shift one slot right
}
arr[index] = value;
}
const nums = [3, 8, 5, 2];
insertAt(nums, 1, 9); // nums is now [3, 9, 8, 5, 2]# What arr.insert(index, value) does for you.
def insert_at(arr, index, value):
arr.append(None) # make room at the end
for i in range(len(arr) - 1, index, -1):
arr[i] = arr[i - 1] # shift one slot right
arr[index] = value
nums = [3, 8, 5, 2]
insert_at(nums, 1, 9) # nums is now [3, 9, 8, 5, 2]You will rarely write this loop yourself, but it is what splice, unshift, insert and pop(0) do behind a single call, so their cost is O(n).
How a dynamic array grows
A block of memory has a fixed size, yet push in JavaScript and append in Python keep working. The array reserves more slots than it uses. The number of slots in use is the length and the number reserved is the capacity. An append writes into a spare slot and increases the length.
When the spare slots run out, the array allocates a new, larger block, often about twice the size, and copies every item into it. That one append costs O(n). It happens rarely, because after the block grows from 8 to 16 slots, the next 8 appends need no copying.
Growing from 1 to 16 slots by doubling copies 1 + 2 + 4 + 8 = 15 items in total, which is less than one copy per append. Appending is therefore amortized O(1): a single append is sometimes slow, but the average cost over many appends is constant. If the array grew by a fixed number of slots instead of a multiple, the copying would add up to O(n²) over n appends, which is why real implementations grow by a multiple.
| Approach | Time | Why |
|---|---|---|
| Read or write arr[i] | O(1) | The address is the start plus i times the slot size. |
| Append to the end | O(1) amortized | An occasional O(n) copy happens when the array is full. |
| Remove from the end | O(1) | No item has to move. |
| Insert or delete at index i | O(n) | Every item after i shifts by one slot. |
| Search for a value | O(n) | An unordered array has to be scanned item by item. |
Variants and alternatives
Fixed-size arrays
In languages such as C, Java and Go, an array has a fixed length chosen when it is created, and it cannot grow. A fixed array has no spare capacity and no copying, so it is the smallest and simplest layout. When you need a collection that grows, you use the dynamic version of the same idea: ArrayList in Java, a slice in Go, a list in Python and an array in JavaScript. Interview problems almost always assume the dynamic kind.
Two-dimensional arrays
A grid is usually an array of arrays, and grid[r][c] is two reads, so it is still O(1). A grid with r rows and c columns holds r × c items, and visiting all of them is O(r × c). In Python the rows must be built separately, as shown in the pitfalls below.
Sorted arrays
Keeping an array sorted makes searching fast, because binary search finds a value in O(log n). The cost is that every insert has to keep the order, which means finding the position and then shifting the items after it, so inserts are O(n). A sorted array suits data that is built once and searched many times.
When an array is the wrong choice
Do not use an array as a queue that removes items from the front. Use a queue or deque, where both ends are cheap. If you search by value often, put the values in a hash table, which finds a value in O(1) on average. If you insert and delete in the middle often and already hold a reference to the position, a linked list avoids shifting, but it gives up O(1) reading by index and is slower to scan in practice, because its nodes are scattered in memory instead of side by side.
Pitfalls
In the interview
Arrays are the input of most interview problems, so the signal is usually just that the input is a list of numbers or characters. Pay attention to the constraints in the statement. A sorted array suggests binary search or two pointers. A request to find a subarray or a pair suggests a prefix sum, a sliding window or a hash map. A requirement to use O(1) extra space or to change the array in place means you may only use a few variables and must overwrite items as you go.
Questions to expect:
- "Why is reading by index O(1)?" The items are stored in one block with equal-sized slots, so the address of item
iis the start address plusitimes the slot size. That is one multiplication and one addition, however long the array is. - "What does it cost to insert at the front, and why?" It costs O(n). Every existing item must move one slot to the right to make room, and the array has no gaps to absorb the shift. Inserting at the end avoids this, which is why append is cheap.
- "Why is append O(1) when the array sometimes has to copy everything?" The copy happens only when the array is full, and the new block is a multiple of the old size, so each copy pays for many later appends. Over n appends the total copying is less than 2n items, which averages out to constant time per append. This is called amortized O(1).
- "Why does the array double instead of growing by one slot?" Growing by one slot would copy the whole array on every append, which makes n appends cost O(n²). Growing by a constant factor keeps the total at O(n).
- "How do you remove an item from the middle in O(1)?" If the order does not matter, overwrite the item with the last item and remove the last one. This is a swap and a pop, with no shifting. If the order must be kept, the shift is unavoidable, and removal is O(n).
- "When would you choose a linked list over an array?" When you insert or delete in the middle often and already hold a reference to that node, because no items move. Otherwise an array is usually better, since it reads by index in O(1) and scans faster, because its items sit side by side in memory.
- "How do you reverse an array in place?" Keep one index at the start and one at the end, swap the two items, and move the indexes toward each other until they meet. It takes O(n) time and O(1) extra space.
An array holds 1,000,000 numbers. How much work is it to read arr[734512]?
You call arr.unshift(x) in JavaScript, or arr.insert(0, x) in Python, on a list of n items. What does it cost?
Why is appending to a growing array described as O(1) amortized rather than plain O(1)?
In Python, grid = [[0] * 3] * 3 and then grid[0][0] = 1. What is grid afterwards?
What to practise next
Read Two Pointers to see how two indexes scan an array in one pass, and Strings for arrays of characters that cannot be changed in place.