AlgoViz

Static arrays

easy 15 min

A static array is a fixed-size block of same-type slots stored side by side in memory.

Video lesson · Chapter 1 of 5

Five fixed sample slots

0:00 / 3:26

Static arrays — Juno’s synth rack

1:29Reel

Read caption

Juno calculates a synth memory address in one step, then shifts three presets to make room on the same rack. Index times width, plus the base.

How it works

Step through the idea, or press Play.

Step 1 of 3

Reserve one block. n slots of the same size are laid out side by side, and the size is fixed from then on

Understand it

Start here

What a static array is

A static array is a fixed-size, contiguous block of memory that stores elements of the same type. You choose the size when you create it, and it never grows or shrinks. It is the most basic data structure there is: nearly every other structure, from stacks to hash tables, is built on top of one.

  • Fixed size

    Decided once, at creation. To get more room you must make a new array and copy.

  • Contiguous

    Slots sit next to each other in memory with no gaps and no pointers between them.

  • Same type, same size

    Every slot takes the same number of bytes ss, which is what makes the address maths work.

  • O(1) by index

    Any index is one calculation away: reading arr[0] and arr[999999] cost the same.

How much memory it takes

bytes=n⋅se.g. 5 ints×4 bytes=20 bytes\text{bytes} = n \cdot s \qquad\text{e.g. } 5 \text{ ints} \times 4 \text{ bytes} = 20 \text{ bytes}
No per-element overhead: no pointers, no headers. The memory use is predictable before the program even runs.

The picture

Memory layout

Take five 4-byte integers whose block starts at address 1000. Each slot begins exactly 4 bytes after the previous one, so the addresses climb in a perfectly regular step.

IndexValueAddressWorked out
01010001000+0⋅41000 + 0 \cdot 4
12010041000+1⋅41000 + 1 \cdot 4
23010081000+2⋅41000 + 2 \cdot 4
34010121000+3⋅41000 + 3 \cdot 4
45010161000+4⋅41000 + 4 \cdot 4
5?1020past the end: out of bounds
The block covers bytes 1000 to 1019. Index 5 would land at 1020, memory that belongs to something else.

The math

Address arithmetic: why access is O(1)

The address of index i

addr(i)=base+i⋅s\text{addr}(i) = \text{base} + i \cdot s
base\text{base} is where the block starts and ss is the size of one element in bytes. One multiply and one add, whatever ii and nn are.

Worked example

addr(3)=1000+3⋅4=1012addr(999,999)=1000+999,999⋅4=4,000,996\text{addr}(3) = 1000 + 3 \cdot 4 = 1012 \qquad \text{addr}(999{,}999) = 1000 + 999{,}999 \cdot 4 = 4{,}000{,}996
Both take the same two operations. A linked list would have to walk past every node before the one it wants.

Reading arr[i]

Writing arr[i] = x follows the same path and ends with one memory write instead.

Two dimensions

Grids and matrices in one block

A 2D array, such as a matrix, an image or a game board, is still one flat block. In row-major order (C, Python, NumPy by default) row 0 is stored first, then row 1, and so on. With CC columns, cell (r,c)(r, c) sits after rr full rows plus cc cells.

Row-major address

addr(r,c)=base+(r⋅C+c)⋅s\text{addr}(r, c) = \text{base} + (r \cdot C + c) \cdot s
Still O(1)O(1). A row of an identity matrix like [1, 0, 0, 1] or a 3D point (x, y, z) are tiny fixed arrays of the same kind.

A 3 × 4 grid and its flat indexes

col 0col 1col 2col 3
row 00123
row 14567
row 2891011
Cell (2,1)(2, 1) is flat index 2⋅4+1=92 \cdot 4 + 1 = 9. With 4-byte ints and base 1000 its address is 1000+9⋅4=10361000 + 9 \cdot 4 = 1036.

The API

Operations and what they cost

OperationBestWorstExtra spaceWhy
Access arr[i]O(1)O(1)O(1)O(1)O(1)O(1)Address arithmetic
Update arr[i] = xO(1)O(1)O(1)O(1)O(1)O(1)Address arithmetic, then one write
Insert at endO(1)O(1)O(1)O(1)O(1)O(1)Only if a spare slot was reserved
Insert at index iiO(1)O(1) at the endO(n)O(n) at the frontO(1)O(1)Shifts n−in - i elements right
Delete at index iiO(1)O(1) at the endO(n)O(n) at the frontO(1)O(1)Shifts n−1−in - 1 - i elements left
Linear searchO(1)O(1) first slotO(n)O(n) last or missingO(1)O(1)Checks slots one by one
Binary search (sorted)O(1)O(1)O(log⁡n)O(\log n)O(1)O(1)Halves the range each check
Traverse (sum, max)O(n)O(n)O(n)O(n)O(1)O(1)Must see every element
The array itself takes O(n)O(n) space. Every operation above is done in place.

Under the hood

Inserting at a position

insert_at(i, x)

The loop runs from the back towards ii, moving each element one slot right.

Shifting cost of an insert

shifts(i)=n−i  ⇒  O(n−i)1n+1∑i=0n(n−i)=n2=O(n)\text{shifts}(i) = n - i \;\Rightarrow\; O(n - i) \qquad \frac{1}{n+1}\sum_{i=0}^{n} (n - i) = \frac{n}{2} = O(n)
Inserting at the end (i=ni = n) shifts nothing; at the front (i=0i = 0) it shifts all nn. Over all positions the average is n/2n/2 shifts, which is still linear.
Python
def insert_at(data, length, i, value):    if length == len(data):        raise OverflowError("array is full")    for j in range(length, i, -1):   # back to front        data[j] = data[j - 1]    data[i] = value    return length + 1data = [10, 20, 40, 50, None]   # capacity 5, length 4length = insert_at(data, 4, 2, 30)print(data, length)             # [10, 20, 30, 40, 50] 5
Insert into a fixed-capacity array by shifting right, back to front.
Edit and run it in your browser

Under the hood

Deleting at a position

delete_at(i)

Here the loop runs from the gap towards the end, moving each later element one slot left.

Shifting cost of a delete

shifts(i)=n−1−i  ⇒  O(n−i)1n∑i=0n−1(n−1−i)=n−12=O(n)\text{shifts}(i) = n - 1 - i \;\Rightarrow\; O(n - i) \qquad \frac{1}{n}\sum_{i=0}^{n-1} (n - 1 - i) = \frac{n - 1}{2} = O(n)
Deleting the last element shifts nothing; deleting index 0 shifts n−1n - 1. Deleting index 2 of 5 elements shifts 2.

Searching

Finding a value

Linear search

Knowing an index is instant, but knowing a value means looking. Unsorted data gives no hint where to look.

Expected comparisons when the target is present

1n∑k=1nk=n+12=O(n)\frac{1}{n}\sum_{k=1}^{n} k = \frac{n + 1}{2} = O(n)
If the target is equally likely to be in any slot, you check about half the array on average, and all nn slots when it is missing.
nLinear search, worstBinary search, worst
553
1,0001,00010
1,000,0001,000,00020
Binary search needs at most ⌈log⁡2(n+1)⌉\lceil \log_2(n + 1) \rceil checks but only works on sorted data. See binary search.

Comparison

Static array vs dynamic array vs linked list

OperationStatic arrayDynamic arrayLinked list
Access by indexO(1)O(1)O(1)O(1)O(n)O(n)
Search by valueO(n)O(n)O(n)O(n)O(n)O(n)
Insert at frontO(n)O(n)O(n)O(n)O(1)O(1)
Insert at endO(1)O(1) if roomO(1)O(1) amortisedO(1)O(1) with a tail
Insert in middleO(n)O(n)O(n)O(n)O(1)O(1) once you hold the node
Delete at frontO(n)O(n)O(n)O(n)O(1)O(1)
Grows?NoYes, by copyingYes, node by node
Memory per elementJust the valueValue plus spare capacityValue plus pointer(s)
Cache behaviourExcellentExcellentPoor
Compare with the singly linked list and dynamic arrays.

Advantages

  • O(1)O(1) access and update by index.
  • Cache-friendly, because the memory is contiguous.
  • No memory overhead per element.
  • Predictable memory use, known up front.

Disadvantages

  • Fixed size: it cannot grow or shrink.
  • Insert and delete in the middle need shifting.
  • Wastes memory if you reserve more than you use.
  • The size must be known when you create it.
Growing a static array means copying it
  1. 1Allocatea new, bigger block
  2. 2Copyall n elements across, O(n)
  3. 3Switchpoint at the new block
  4. 4Freerelease the old block

A dynamic array automates exactly this, and by growing by a factor it keeps appends $O(1)$ on average.

Hardware

Why arrays are fast in practice

Big O says a linked-list scan and an array scan are both O(n)O(n). On real hardware the array usually wins by a wide margin, because of how CPUs fetch memory.

  • Cache lines

    Memory is loaded in chunks of about 64 bytes. One load brings 16 neighbouring 4-byte ints with it.

  • Prefetching

    The CPU spots a steady forward scan and loads the next chunk before you ask for it.

  • No pointer chasing

    A linked list must read a pointer before it knows where the next node is. An array already knows.

Python
import arraya = array.array("i", [10, 20, 30, 40, 50])   # C ints, one blockbase, n = a.buffer_info()                   # start address, lengths = a.itemsize                              # bytes per element (usually 4)for i in range(n):    print(i, a[i], "at base +", i * s)print("total bytes:", n * s)
Python's array module stores real machine integers side by side. Check the address rule yourself.
Edit and run it in your browser

Pattern spotting

When to reach for an array

Should I use a static array?

When you land on a static array you get O(1)O(1) access, cache-friendly scans and tight memory.
  • Lookup tables

    Precomputed values indexed by key: trig tables, Fibonacci numbers, character counts for 26 letters.

  • Buffers

    Fixed-size I/O, audio and video buffers that are filled, flushed and reused.

  • Matrices and grids

    2D arrays for images, game boards and scientific computing.

  • Caching and memoisation

    Store each result at its index so the next lookup is O(1)O(1).

Classic array problems to practise next

ProblemPattern
Two SumHash map of complements
Best Time to Buy and Sell StockOne pass, track the minimum so far
Contains DuplicateHash set, or sort then compare neighbours
Product of Array Except SelfPrefix and suffix products
Maximum SubarrayKadane's running sum

Recap

Key takeaways

Key points

  • A static array is a fixed-size, contiguous block of same-type elements.
  • addr(i)=base+i⋅s\text{addr}(i) = \text{base} + i \cdot s, so access and update are O(1)O(1) at any index.
  • Valid indexes are 00 to n−1n - 1; anything else is out of bounds.
  • Insert at ii shifts n−in - i elements and delete shifts n−1−in - 1 - i: both O(n−i)O(n - i), O(n)O(n) in the worst case.
  • Search by value is O(n)O(n), or O(log⁡n)O(\log n) with binary search if the array is sorted.
  • Contiguous memory makes scans cache-friendly; the fixed size is the price.

Sources