AlgoViz

Static arrays

easy 15 min

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

Remember it

The few things worth knowing cold, and how to make them stick.

Memory hook

Know the index, jump straight there: base plus index times size.

A row of identical lockers along a corridor. To reach locker 37 you do not open the first 36; you walk 37 locker-widths from the first one. But squeezing a new locker in between number 3 and number 4 means moving every locker after it down one place.

Cheat sheet

Address
base + i × size
Access, update
O(1)
Insert at end
O(1) if a slot is free
Insert at i
O(n - i): shifts n - i right
Delete at i
O(n - i): shifts n - 1 - i left
Linear search
O(n)
Binary search
O(log n), sorted only
Valid indexes
0 to n - 1
Space
n × size, no overhead

Spot it when you see

  • The size is known in advance and does not change.
  • You need fast random access by position.
  • Keys are small dense integers, such as 0 to n - 1 or the 26 letters: use the key as the index.
  • Grids, images, boards and matrices.
  • Lookup tables, prefix sums and DP tables: precompute once, read in constant time.
  • Two pointers or a sliding window over contiguous data.

Tricks that stick

  • Index means offset: how many elements to skip from the base. That is why the first one is 0.
  • Insert walks from the back, delete walks from the front. Each loop moves towards the gap's far side.
  • The last valid index is n - 1. If you typed n, you have run off the end.
  • Positions are cheap, values are expensive: arrays answer where instantly and what slowly.
  • Order does not matter? Swap the doomed element with the last one and shrink.

Do not forget

  • Looping to n inclusive and reading one slot past the end.
  • Using arr[n] as the last element instead of arr[n - 1].
  • Inserting at the front inside a loop: O(n) each, O(n²) overall.
  • Deleting while looping forward, which skips elements.
  • Reading arr[0] of an empty array.
  • Assuming b = a copies the array; it copies the reference.