Static arrays & memory layout
Explain why array indexing is O(1) and insertion in the middle is O(n).
By Invicly Tech, , in Data Structures & Algorithms. About 10 minutes to read.
In short
An array stores elements of the same size in one contiguous block of memory. The address of element i is the base address plus i times the element size, so indexing is O(1). Inserting or deleting in the middle requires shifting everything after it, which is O(n).
Think of it like this: Numbered seats in a cinema row: you find seat 12 instantly, but adding a seat in the middle moves everyone along.
Explained simply
An array is a row of boxes, all the same size, sitting side by side in memory. Each box has a number called its index, starting at 0. Because the boxes are equal and touching, the computer can jump straight to any box without looking at the others.
Picture a street where every house is exactly 10 metres wide and house 0 starts at the corner. House 7 must be 70 metres down the road. You do not walk past each house; you just do the math. That is why reading arr[7] takes the same time as reading arr[0].
The catch is that the row cannot easily make room in the middle. To squeeze a new value into position 2, everything from position 2 onwards must slide one place right, like people in a cinema row shuffling over for a latecomer. Deleting works the same way in reverse.
A static array has a fixed size chosen when it is created. If you need more room, you must make a new, bigger array and copy everything over. Dynamic arrays, like Python lists, do this for you automatically.
Press Play on a diagram to walk through it one step at a time.
- 1Code: a[3]
You ask for index 3.
- 2Address arithmetic
base + 3 x element_size.
- 3Contiguous memory block
Elements sit side by side.
- 4CPU cache line
Neighbours load together, so scans are fast.
- 1Start
[4, 7, 2, _], size 3, capacity 4
- 2Move index 2 to 3
[4, 7, 2, 2]
- 3Move index 1 to 2
[4, 7, 7, 2]
- 4Write 9 at index 1
[4, 9, 7, 2], size 4
- 5Cost
2 moves = size - index
- Read: O(1)
- Insert (if room): O(1)
- Delete: O(1)
- Read: O(1)
- Insert: O(n) shifting
- Delete: O(n) shifting
- Read: O(1)
- Insert: O(n), moves everything
- Delete: O(n), moves everything
In depth
The address formula
Memory is one long numbered strip of bytes. An array of 4-byte integers that starts at address 1000 keeps element 0 at bytes 1000-1003, element 1 at 1004-1007, and so on.
So the address of element i is: base + i times size. For i = 5, that is 1000 + 5 x 4 = 1020. One multiply and one add, no matter if the array has ten items or ten million. This is the whole reason indexing is O(1), and it only works because every element is the same size and they sit with no gaps.
- address(i) = base + i x element_size
- Same cost for any i: O(1)
- Index 0 is the base itself, which is one reason indexes start at 0
Insert and delete mean shifting
To insert at index i in an array holding n items, move items n-1 down to i one step right, starting from the end so nothing gets overwritten. Then write the new value at i. That is n - i moves.
Deleting at i is the mirror image: move items i+1 up to n-1 one step left, starting from i+1. Inserting at the end costs nothing extra, but inserting at the front moves all n items. So the worst case is O(n). If you do not care about order, there is a trick: delete by copying the last item into the hole, which is O(1).
Why arrays are fast in real hardware
The CPU does not fetch one number at a time from main memory. It fetches a whole cache line, usually 64 bytes, and keeps it in a small, very fast cache. When you read arr[0], arr[1] up to about arr[15] (for 4-byte ints) arrive for free.
A loop that walks an array in order hits the cache almost every time. A linked list scatters nodes across memory, so each step may wait for main memory, which can be around 100 times slower. Same Big-O, very different real speed.
Grids stored as one long row
A 2D grid with R rows and C columns is usually stored row by row in one block. This is called row-major order. Cell (r, c) lives at index r x C + c.
This matters for speed: looping over rows on the outside and columns on the inside reads memory in order. Swapping the loops jumps C elements at a time and can be several times slower on large grids. In Python, a list of lists is not one block, but the habit still pays off with NumPy arrays and in languages like C and Java.
- Row-major index: r x C + c
- Recover row and column: divmod(index, C)
- Loop rows outside, columns inside
- Reads cells in memory order
- Index r x C + c steps by 1
- Each cache line fully used
- Jumps C cells each step
- Often a new cache line per read
- Can be several times slower
Learn it in 4 short steps
About 40m each. Track them with a timer in your plan.
- 1Compute element addresses from the index~40m
- 2Insert and delete by shifting elements~40m
- 3Explain cache locality benefits~40m
- 4Work with 2D arrays as row-major~40m
Key points
- Read or write by index: O(1).
- Insert or delete at position i: O(n - i) shifts, O(n) worst case.
- Contiguous layout gives excellent cache locality for sequential scans.
- 2D arrays are usually stored row-major: element (r, c) is at r x cols + c.
Key terms
Tap a card to flip it. 0/4 known
Examples
def insert_at(arr, size, i, value):
# arr has spare capacity; shift right from the end, O(n)
for j in range(size, i, -1):
arr[j] = arr[j - 1]
arr[i] = value
return size + 1
arr = [1, 2, 4, 0]
size = insert_at(arr, 3, 2, 3)
print(arr[:size]) # [1, 2, 3, 4]Delete by shifting left, traced
Delete index 1 from [5, 8, 3, 6] with size 4. Move index 2 into 1: [5, 3, 3, 6]. Move index 3 into 2: [5, 3, 6, 6]. Lower size to 3. The last slot still holds a stale 6, but it is outside size, so it does not count. Two moves were needed: size - 1 - index.
def delete_at(arr, size, i):
for j in range(i, size - 1): # shift left, front to back
arr[j] = arr[j + 1]
return size - 1
arr = [5, 8, 3, 6]
size = delete_at(arr, 4, 1)
print(arr[:size]) # [5, 3, 6]Finding a cell in a flattened grid
A 3 x 4 grid is stored as one list of 12 numbers. To read row 2, column 1, compute 2 x 4 + 1 = 9. To go back from index 9 to (row, column), use divmod(9, 4) = (2, 1). Many grid problems are easier when you flatten, for example to store visited cells in a single list.
R, C = 3, 4
flat = list(range(R * C)) # 0..11, row by row
def get(r, c):
return flat[r * C + c]
print(get(2, 1)) # 9
print(divmod(9, C)) # (2, 1)Quick reference
- address(i) = base + i x element_size, so indexing is O(1)
- Insert or delete at i shifts n - i items: O(n) worst case
- Insert: shift from the back; delete: shift from the front
- Unordered delete trick: copy the last item into the hole, O(1)
- Row-major grid: index = r x C + c; back with divmod(index, C)
- Sequential scans are cache friendly; random jumps are not
Common mistakes
- Shifting left to right during insertion, which overwrites values before moving them.
- Iterating column by column over a large row-major grid and losing cache benefits.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write move_zeros(xs) that moves every 0 to the end while keeping the order of the other numbers, in place. Example: [0, 1, 0, 3, 12] becomes [1, 3, 12, 0, 0].
- Exercise 2medium
Write rotate_grid(g) that rotates a square n x n grid 90 degrees clockwise in place. Example: [[1, 2], [3, 4]] becomes [[3, 1], [4, 2]].
- Exercise 3hard
Write spiral(g) that returns the values of an R x C grid in clockwise spiral order. Example: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] returns [1, 2, 3, 6, 9, 8, 7, 4, 5].
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Why do arrays start at index 0?
- Because the index is an offset from the start. Element 0 is zero steps from the base address, so the formula base + i x size needs no extra subtraction.
- Is a Python list a static array?
- No, it is a dynamic array. Underneath it uses a static block of pointers and swaps in a bigger block when it fills up.
- When would I use a fixed-size array on purpose?
- When the size is known up front, like 26 letter counts or a grid, or in low-level code where predictable memory matters. Python's array module and NumPy give compact fixed-type arrays.