Arrays, Memory & Dynamic Arrays

Data Structures & Algorithms · Arrays & Strings · Basics · 18 min

Understand what an array really is in memory: why a[i] is instant, why inserting in the middle is slow, and how a growing list stays fast by doubling its capacity.

A row of numbered lockers bolted side by side. You can walk straight to locker 7, but squeezing a new locker into the middle means moving every locker after it.

The idea in everyday words

Picture a cinema row with numbered seats. If you know the row starts at seat 100, seat number 7 is at 100 + 7: no searching needed. But if a friend arrives and wants to sit in the middle, everyone to their right has to shuffle one seat over. And when the row is full, the whole group must move to a bigger, empty row, carrying their popcorn with them.

Memory is one long street of numbered houses

Your computer's memory is a huge row of numbered bytes. Each number is an address.

An array stores its items side by side (contiguously) in one block. If the block starts at address 1000 and each item takes 8 bytes:

index 0 1 2 3
address 1000 1008 1016 1024

So the address of item i is just arithmetic:

address(i) = start + i × item_size

One multiplication and one addition, no matter if the array has 4 items or 4 million. That is why indexing a[i] is O(1). It is also why indexes start at 0: index 0 is "0 steps from the start".

A Python list stores references (addresses of the real objects) side by side, so every slot has the same size even if the items are different types.

Inserting or deleting in the middle means shifting

Because items must stay side by side with no gaps, putting a new item at index i forces every item from i onward to move one slot right.

Insert 99 at index 1 of [10, 20, 30, 40]:

  1. move 40 to slot 4
  2. move 30 to slot 3
  3. move 20 to slot 2
  4. write 99 into slot 1 → [10, 99, 20, 30, 40]

We shift from the end backwards so nothing gets overwritten before it moves. Deleting is the mirror image: shift everything after the gap one slot left.

Operation Cost Why
read / write a[i] O(1) address arithmetic
append at the end O(1) amortized no shifting needed
pop from the end O(1) no shifting needed
insert / delete at index i O(n - i), so O(n) shift everything after i
x in a (search) O(n) must look at each item

The end of an array is cheap; the front is expensive. That is why list.pop(0) is slow and collections.deque exists for queues.

The full-block problem and dynamic arrays

A raw array has a fixed capacity, chosen when the block is reserved. The memory right after it may belong to something else, so it cannot simply grow in place.

A dynamic array (Python's list, Java's ArrayList, C++'s vector) hides this. It keeps:

  • n = how many items are stored
  • cap = how many slots the block has (cap ≥ n)

When you append and n == cap, it:

  1. reserves a new block twice as big,
  2. copies every item across (n copies),
  3. lets the old block go,
  4. writes the new item.
cap, n, copies = 1, 0, 0
for x in range(10):
    if n == cap:            # full: grow
        copies += n         # copy everything over
        cap *= 2
    n += 1
print("n =", n, "cap =", cap, "total copies =", copies)

Most appends are a single write. Only the occasional one is expensive.

Why doubling makes append O(1) on average

Count the copying work for 16 appends starting at capacity 1. Copies happen when the size hits 1, 2, 4 and 8:

1 + 2 + 4 + 8 = 15 copies for 16 appends.

In general the copies add up to less than 2n. Spread over n appends that is fewer than 2 extra moves per append: O(1) amortized.

Amortized means "averaged over a long sequence of operations". One append can cost O(n), but the total for any n appends is O(n). This is a guarantee, not luck: it is different from "average case", which is about typical or random inputs.

Compare with growing by just +1 slot each time: copies are 1 + 2 + 3 + ... + (n - 1) ≈ n²/2. That is O(n²) total, painfully slow. Growing by a multiple (×2, ×1.5, ×1.125) is the trick; growing by a constant is the trap. (CPython grows lists by about 1/8 extra plus a little, which is still a multiple.)

You can watch Python's list jump in size as it reserves extra room:

import sys
a = []
last = sys.getsizeof(a)
for i in range(20):
    a.append(i)
    size = sys.getsizeof(a)
    if size != last:
        print("len", len(a), "-> bytes", size)
        last = size

Using Python lists wisely

Turn the costs into habits:

  • Build with append, not insert(0, x). If you need the reverse order, append and reverse once at the end: O(n) instead of O(n²).
  • Queue from the front? Use collections.deque: popleft() is O(1).
  • Know the size up front? [0] * n reserves it in one go.
  • Many deletes in the middle? Build a new list with only the items you keep (one pass) instead of calling remove repeatedly.
  • Two pointers often beat shifting. Problems like "move zeroes" or "remove element" can overwrite in place with a write pointer instead of deleting.
nums = [0, 1, 0, 3, 12]
write = 0
for x in nums:                # keep non-zeros, packed to the front
    if x != 0:
        nums[write] = x
        write += 1
for k in range(write, len(nums)):
    nums[k] = 0
print(nums)

Step by step

  1. Start:

    Empty dynamic array: n = 0, cap = 1. One slot reserved.

  2. append 5:

    n (0) < cap (1): write 5 into slot 0. n = 1. Cost: 1 write.

  3. append 8:

    n == cap == 1: full. Reserve a block of 2, copy 5 across (1 copy), write 8. n = 2, cap = 2.

  4. append 2:

    Full again. Reserve 4 slots, copy 5 and 8 (2 copies), write 2. n = 3, cap = 4.

  5. append 7:

    Space left: write into slot 3. No copying. n = 4, cap = 4.

  6. append 1:

    Full. Reserve 8, copy 4 items, write 1. Total copies so far: 1 + 2 + 4 = 7 for 5 appends, under 2 per append.

Code example

class DynamicArray:
    def __init__(self):
        self.n, self.cap = 0, 1
        self.A = [None] * self.cap
        self.copies = 0

    def append(self, x):
        if self.n == self.cap:
            self._resize(2 * self.cap)
        self.A[self.n] = x
        self.n += 1

    def _resize(self, new_cap):
        B = [None] * new_cap
        for k in range(self.n):
            B[k] = self.A[k]
            self.copies += 1
        self.A, self.cap = B, new_cap

    def insert(self, i, x):
        if self.n == self.cap:
            self._resize(2 * self.cap)
        shifts = 0
        for k in range(self.n, i, -1):
            self.A[k] = self.A[k - 1]
            shifts += 1
        self.A[i] = x
        self.n += 1
        return shifts


d = DynamicArray()
for x in [5, 8, 2, 7, 1, 9, 4, 6, 3]:
    d.append(x)
    print("append", x, "-> n =", d.n, "cap =", d.cap, "copies so far =", d.copies)
print("insert 99 at index 1 shifted", d.insert(1, 99), "items:", d.A[:d.n])

Complexity

  • Time: Index O(1) (address arithmetic). Append O(1) amortized: total copies < 2n. Insert/delete at index i: O(n - i) shifts, O(n) worst case.
  • Space: O(n): capacity is at most about 2n, so at most half the block is ever empty.

Interview tips

  • Be ready to explain WHY a[i] is O(1): start address + i × item size.

  • If asked 'is list.append O(1)?', say 'amortized O(1): an occasional resize copies everything, but doubling keeps the total linear'. That nuance impresses.

  • When you write pop(0) or insert(0, x) in a loop, call out that it is O(n) per call and offer a deque.

  • For in-place array problems (remove element, move zeroes, duplicate zeros), think about which direction to shift and whether a read pointer and a write pointer avoid shifting altogether.

Challenge: Count the Resize Copies

A dynamic array starts empty with capacity slots (capacity is at least 1). Before each append, if it is full (size == capacity), it doubles its capacity and copies every stored item to the new block.

Return [final_capacity, total_copies] after n appends.

Example: simulate_appends(5, 1) → [8, 7] (copies of 1, 2 and 4 items).

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Arrays & Strings

Previous: Recursion · Next: Strings, Characters & Anagrams