Arrays in memory: indexing, copying and resizing
1 Values side by side
Almost every problem hands us an array. Some things we do to it take one step, and some quietly take n steps. Knowing how an array sits in memory tells us which is which.
Memory is a long row of numbered bytes. A byte's number is its address. An array is one block of this memory, with its values side by side and each value the same size. An int takes 4 bytes.
Our running example is nums = [4, 9, 2, 7, 5], stored from address 1000:
To read nums[i], the computer does not walk along the array. It calculates the address:
That is one multiplication and one addition, whether i is 3 or 99,999. So reading or writing any index is O(1).
This is also why indexes start at 0. The index is the distance from the start. The first value is 0 steps from the start, so it sits at exactly start.
2 Reading past the end
The valid indexes are 0 to n − 1. For our five values, nums[5] would be at address 1020. That memory does not belong to the array.
A loop with <= instead of < reads it on every input:
total = 0
for i from 0 to n // one step too far
total = total + nums[i]
On [4, 9, 2, 7, 5], the last turn reads nums[5]. What happens next depends on the language:
C++
Runtime Error. The language checks every index and stops the program.
Runtime Error. The language checks every index and stops the program.
Runtime Error. The language checks every index and stops the program.
Runtime Error. The language checks every index and stops the program.
Runtime Error. The language checks every index and stops the program.
A wrong answer. nums[5] is undefined, so total becomes NaN.
Anything. nums[i] does no check. It reads whatever bytes sit at 1020. The total may come out right by luck, come out wrong, or the program may crash. So the code can pass the examples and fail later on a hidden test.
3 Inserting and deleting in the middle
Values must stay side by side, with no gaps. So putting a new value in the middle means making room for it first.
We insert 6 at index 1 of [4, 9, 2, 7, 5]. The block has room for a sixth value. Every value from index 1 onwards moves one place right, starting from the end:
| Step | Move | Array after |
|---|---|---|
| 1 | nums[5] = nums[4] | [4, 9, 2, 7, 5, 5] |
| 2 | nums[4] = nums[3] | [4, 9, 2, 7, 7, 5] |
| 3 | nums[3] = nums[2] | [4, 9, 2, 2, 7, 5] |
| 4 | nums[2] = nums[1] | [4, 9, 9, 2, 7, 5] |
| 5 | nums[1] = 6 | [4, 6, 9, 2, 7, 5] |
The table shows two things. Inserting at index 1 moved four values, so inserting near the front of n values costs about n steps: O(n). And the moves go from the end. Starting from the front, step one would write 9 over the 2 before the 2 had moved.
Deleting is the same in reverse. The values after the gap move one place left, starting from the gap. Adding or removing at the end moves nothing, so it is O(1).
4 How a dynamic array grows
A block of memory cannot simply get longer, because the bytes after it may hold something else. So a plain array has a fixed size, set when it is made.
A dynamic array, such as vector, can grow. It keeps two numbers: its size, the values it holds, and its capacity, the places in its block. When a push finds the block full, it does three things:
- It asks for a new block, about twice as big.
- It copies every value across.
- It writes the new value and frees the old block.
That push cost about n steps. But it happens rarely. Here are eight pushes into an array that starts with capacity 1:
| Push | Capacity after | Values copied |
|---|---|---|
| 1 | 1 | 0 |
| 2 | 2 | 1 |
| 3 | 4 | 2 |
| 4 | 4 | 0 |
| 5 | 8 | 4 |
| 6, 7, 8 | 8 | 0 each |
The copies add up to 1 + 2 + 4 = 7, less than the 8 pushes. This holds for any n, because each copy is twice the last, and the sum of 1, 2, 4, … up to half of n is less than n. So n pushes take around 2n steps in all, about 2 per push. One push can be slow, but pushing at the end is O(1) on average.
5 Copy or share: what b = a does
Since an array can be large, most languages do not copy it on b = a. Instead b becomes a second name for the same block. A change through b shows up through a.
C++
Shared. b is a second name for the same array, so a change through b shows up through a.
Shared. b is a second name for the same array, so a change through b shows up through a.
Shared. b is a second name for the same array, so a change through b shows up through a.
Shared. b is a second name for the same array, so a change through b shows up through a.
Shared. b is a second name for the same array, so a change through b shows up through a.
A real copy. b = a copies a vector, value by value. A reference, vector<int>& c = a, shares instead.
A move. let b = a moves the vector: b now owns it, and using a afterwards is a Compile Error.
Sharing costs one step. A real copy costs O(n) time and O(n) space, so we make one only when we need the original kept as it was.
6 Passing an array to a function
A call follows the same rule as b = a. This function doubles every value, and the caller sees the change:
C++
Shared. The function gets the caller's array. Passing it costs one step.
Shared. The function gets the caller's array. Passing it costs one step.
Shared. The function gets the caller's array. Passing it costs one step.
Shared. The function gets the caller's array. Passing it costs one step.
Shared. The function gets the caller's array. Passing it costs one step.
& shares, no & copies. With vector<int> nums, every call copies all n values, and changes stay inside the function. That is why every C++ solution here takes vector<int>& nums.
Lend it. &mut Vec<i32> lends the vector for changing, and &Vec<i32> for reading only. The caller keeps it.
7 What a slice costs
A slice takes a piece of an array, such as indexes 1 to 3 of nums. In most languages it builds a new array of the k values, so it costs O(k) time and space.
C++
A copy, O(k). vector<int>(nums.begin() + 1, nums.begin() + 4) copies the three values.
A copy, O(k). Arrays.copyOfRange(nums, 1, 4) copies the three values.
A copy, O(k). nums[1:4] copies the three values.
A copy, O(k). nums.slice(1, 4) copies the three values.
A copy, O(k). nums[1..4] copies the three values.
Shared, O(1). nums[1:4] points into the same memory, so writing to it changes nums as well.
Shared, O(1). &nums[1..4] borrows the three values without copying them.
Usually we do not need the piece at all. A loop from index 1 to 3 reads the same values with no copy.
8 Mistakes, and what these problems need
- Removing from the front in a loop. Removing the first value of a dynamic array moves all the other values. Done n times on 10⁵ values, that is around 10¹⁰ steps, and the code gets TLE.
- Changing a "copy" that shares. In Python,
b = athenb.sort()sortsaas well. On[4, 9, 2, 7, 5],abecomes[2, 4, 5, 7, 9], and any later step that needs the old order gives a Wrong Answer. - C++: a vector by value in recursion. A recursive function that takes
vector<int> numscopies the whole array on every call. With 10⁵ calls on 10⁵ values, that is around 10¹⁰ steps and TLE.
The problems in this subtopic scan an array once to find, count or move values. Every read by index is O(1), so one pass is O(n). The cost hides only in the moves from this lesson: shifting, growing, copying and slicing.
The habit to keep: for every line that touches an array, ask whether it reads one place or moves many. Only the second kind can turn O(n) into O(n²).
Practice it
- Linear searchEasy
- Largest elementEasy
- Second largest elementEasy
- Sum of array elementsEasy
- Count the odd numbers in an arrayEasy
- Reverse an arrayEasy
- Check whether an array is sortedEasy
- Max Consecutive OnesEasy
- Find All Numbers Disappeared in an ArrayEasy
- Left rotate an array by oneEasy
- Rotate ArrayMedium
- Leaders in an arrayMedium
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.