Foundation 01
Array
A contiguous row of equal-sized slots. An index identifies a slot directly.
Mental model
What the structure guarantees
The computer stores the first address and the size of one element. To reach index i, it calculates start + i × element-size. That calculation does not depend on how far i is from zero, so indexed access is constant time.
Implementation
How that model appears in code
A fixed array cannot change length. Python lists, Java ArrayList, and C++ vector add a resizable layer over an array; when capacity runs out, they allocate a larger array and copy the elements.
Array basics
int[] values = {4, 2, 7, 1};
int x = values[2];
values[2] = 9;values = [4, 2, 7, 1]
x = values[2]
values[2] = 9vector<int> values = {4, 2, 7, 1};
int x = values[2];
values[2] = 9;Operation costs
What gets more expensive as the input grows
O(1)The address is calculated directly.O(n)Each element is visited once.O(1) amortizedMost appends use spare capacity; occasional growth copies the array.O(n)The following elements must shift.O(k)A new region receives k elements.Tradeoffs
Choose it for the operations it makes cheap
Good fit
- Direct indexed access
- Sequential scans
- Compact storage and cache-friendly traversal
Poor fit
- Insertions near the front or middle
- Growth when a fixed array has no spare capacity
Used by
Common mistakes
Errors that survive a first glance
The last index is length − 1
An array of length six has indices 0 through 5. Index 6 is outside the array.
Assignment is usually not a copy
Giving the same array to another variable normally creates another reference to the same data.
A slice may allocate
Repeated slicing inside a loop can turn a linear idea into quadratic work.