Mental model
A row of people sits in numbered seats with no gaps, and a few seats at the end are empty. Someone arrives who must sit in seat 2. Seats cannot stretch, so the person in the last occupied seat moves one to the right, then the person before them, and so on, until seat 2 is free. When someone in seat 2 leaves, everyone after them slides one seat left so the row has no gap again.
An array works the same way. Elements must stay in a contiguous prefix 0 … size − 1 (that is what
keeps address = base + i × size meaningful, see
layout and indexing), so making or
closing a gap means moving every element after it. Reading a[i] is O(1); inserting or deleting at
i is not.
The lab's array has a fixed capacity: it never grows. When it is full, an insert is rejected. That is
what you have with a plain int[] and a size counter, with std::array, or with a buffer you allocated
once on purpose.
Insert at index i
insert(i, value):
if size == capacity: error "full" # no free slot, and the block cannot grow
if i < 0 or i > size: error "out of range" # i == size means "at the end"
for j from size - 1 down to i: # right shift, from the end backwards
a[j + 1] = a[j]
a[i] = value
size += 1
Run Insert at the front: inserting 1 at index 0 of [12, 7, 30, 5] moves 5, then 30, then 7, then 12,
each one slot right, and only then writes 1 into slot 0. The following append(40) moves nothing:
appending is inserting at index size, where there is no tail to move.
Why backwards
Suppose the loop ran forwards instead: copy a[i] to a[i+1], then a[i+1] to a[i+2]… The first
copy overwrites a[i+1] before it has been saved, so the second copy writes the same value again.
The whole tail becomes copies of a[i]. Copying from the end backwards always writes into a slot whose
old value has already been moved (or was unused). Deletion is the mirror image: a left shift must run
forwards, from the gap to the end.
Library copy routines handle this for you. Array.Copy and System.arraycopy are specified to behave
as if the source were first copied to a temporary buffer, so overlapping ranges are safe in either
direction. In C++, std::copy requires the destination to start outside the source range (fine for a
left shift), std::copy_backward is the one for a right shift, and std::memmove (not memcpy) handles
overlap for trivially copyable bytes.
Delete at index i
delete(i):
if i < 0 or i >= size: error "out of range"
removed = a[i]
for j from i to size - 2: # left shift, from the gap forwards
a[j] = a[j + 1]
a[size - 1] = default # clear the stale copy
size -= 1
return removed
Run Delete and close the gap: deleting index 1 of [12, 7, 30, 5, 18, 21] moves 30, 5, 18 and 21 one
slot left. After the shift, the last occupied slot still holds a copy of 21 that is now outside the
array's logical size. Clearing it is optional for ints but important for references: in C#, Java
and Python a stale reference keeps the object alive, so the garbage collector cannot reclaim it.
List<T>, ArrayList and CPython's list all clear that slot.
What it costs
Inserting at index i moves size − i elements; deleting at index i moves size − 1 − i. So:
| Position | Elements moved (n = size) | Time |
|---|---|---|
| at the end (append / delete last) | 0 | O(1) |
| at the front (index 0) | n (insert) or n − 1 (delete) | O(n) |
| uniformly random position | about n / 2 on average | O(n) |
| get / set at any index | 0 | O(1) |
The average follows from summing n − i over the n + 1 possible insert positions: n(n + 1)/2
moves, divided by n + 1, is n / 2. Half of n is still linear. A sequence of n inserts at the front
moves 0 + 1 + … + (n − 1) = n(n − 1)/2 elements in total: Θ(n²), which is why building a list by
repeatedly inserting at position 0 is a classic accidental quadratic algorithm.
Shifting is fast per element (a tight copy loop over contiguous memory, often vectorized), so for a few thousand elements it is usually cheaper in practice than following pointers in a linked list. The asymptotic cost is still O(n), and it shows at scale.
Space: O(1) extra. Everything happens inside the existing block.
When the array is full
A fixed array has three honest options when size == capacity:
- Reject the insert (the lab, and C++26's
std::inplace_vector, which throwsstd::bad_allocfrompush_backand offerstry_push_back). - Overwrite something, as a ring buffer does with the oldest element.
- Allocate a bigger block and copy everything: that is a dynamic array, and the dynamic arrays lesson shows why doubling keeps append amortized O(1).
The Full array preset shows option 1: append(5) on a full array of 4 is rejected; after one delete
there is room again. Note the order of the checks: the listings test "full" before the index, so
insert(9, 2) on a full array reports "full", not "out of range". Either order is defensible, but the
four languages and the fixture must agree.
Cheaper when order does not matter
If the array is a bag (order irrelevant), delete in O(1) by moving the last element into the gap:
swap_remove(i):
removed = a[i]
a[i] = a[size - 1]
a[size - 1] = default
size -= 1
return removed
One move instead of size − 1 − i. Rust calls this swap_remove; game engines and entity systems use it
constantly. It changes the order of the remaining elements, so never use it on sorted data or anything
whose positions mean something.
Removing many elements at once is another trap. Deleting every matching element one call at a time
costs O(n) per delete, O(n²) in total. A single pass with a read index and a write index compacts the
array in O(n): C#'s List<T>.RemoveAll, Java's removeIf, C++'s std::erase_if (C++20) and Python's
a[:] = [x for x in a if keep(x)] all do this. The
two pointers lesson explains
the read/write technique.
The built-ins
| Insert at i | Delete at i | Delete by value | Notes | |
|---|---|---|---|---|
C# List<T> |
Insert(i, x) |
RemoveAt(i) |
Remove(x) (first match) |
grows when full; Array.Copy does the shift |
Python list |
insert(i, x) |
pop(i), del a[i] |
remove(x) |
insert clamps an out-of-range index to the ends instead of raising |
Java ArrayList |
add(i, x) |
remove(int i) |
remove(Object o) |
remove(1) on a List<Integer> removes index 1, not the value 1 |
C++ std::vector |
insert(it, x) |
erase(it) |
std::erase(v, x) (C++20, all matches) |
iterator-based; invalidates iterators at or after the position |
All of them shift exactly as the lab does, and all are O(n − i). Python's list.insert(100, x) on a
list of 5 elements appends instead of raising, a convenience that hides bugs; pop(i) and del do raise
IndexError. Java's remove(int) versus remove(Object) overload is a well-known source of bugs with
lists of Integer. For C++, remember that insert and erase invalidate iterators and references to
elements after the position (and all of them if a reallocation happens), as the
reallocation lesson
shows.
The teaching implementation
Insert, Delete (erase in C++, since delete is a keyword there) and Append in the listings follow
the pseudocode line for line, with explicit shift loops instead of Array.Copy / System.arraycopy /
std::copy_backward, so that each moved element is visible. Errors are exceptions: an out-of-range index
throws ArgumentOutOfRangeException, IndexError, IndexOutOfBoundsException or std::out_of_range;
a full array throws InvalidOperationException, a small ArrayFullError, IllegalStateException or
std::length_error. A Shifts counter exists only so the tests can check the number of moved elements
against the shared fixture.
Common mistakes
- Shifting in the wrong direction, which duplicates one element over the whole tail.
- Allowing
i == sizefor delete or forbidding it for insert. Insert positions are0 … size; delete positions are0 … size − 1. - Forgetting to clear the vacated slot in an array of references, which leaks memory until the slot is overwritten.
- Deleting while iterating forwards by index: after deleting
a[i], the next element is now ati, andi++skips it. Iterate backwards or use a read/write compaction. - Inserting at the front in a loop, which is Θ(n²). Append and reverse once, or use a deque.
Edge cases
- Empty array: every get, set and delete is out of range; insert at 0 (or append) works.
- Capacity 1: one append fills it; the next is rejected.
- Insert at
size: no shifts (it is an append). - Delete the last element: no shifts, just clear and shrink.
- Delete the only element: size returns to 0, and the array can be refilled.
Worked practice
1. An array holds [4, 8, 15, 16, 23] with capacity 8. How many elements move for insert(1, 42), and what is the result?
Answer
size − i = 5 − 1 = 4 elements move (23, 16, 15, 8, in that order). Result: [4, 42, 8, 15, 16, 23].
2. You delete index 0 of a 1,000-element array 1,000 times in a row. How many element moves is that in total?
Answer
999 + 998 + … + 0 = 999 × 1000 / 2 = 499,500. Quadratic. Reading the elements front to back with an index (or using a queue) avoids it.
3. Write the loop of an insert using a forward copy and show what goes wrong on [1, 2, 3, _] with insert(0, 9).
Answer
Forward: a[1] = a[0] gives [1, 1, 3, _], a[2] = a[1] gives [1, 1, 1, _], a[3] = a[2] gives
[1, 1, 1, 1], then a[0] = 9: [9, 1, 1, 1]. Values 2 and 3 were overwritten before being moved.
4. Order does not matter. How do you delete index 2 of [5, 9, 7, 3, 1] with one move?
Answer
Move the last element into the gap: a[2] = a[4], clear a[4], size 4. Result [5, 9, 1, 3].
Summary
- Elements must stay in a contiguous prefix, so insert and delete shift the tail.
- Insert at i moves
size − ielements (right shift, backwards); delete at i movessize − 1 − i(left shift, forwards). O(1) at the end, O(n) at the front and on average. - A fixed array rejects inserts when full; a dynamic array reallocates instead.
- Clear the vacated slot when elements are references.
- If order does not matter, swap-with-last deletes in O(1); for bulk removal, compact in one pass.