M05 · Arrays

Insert and Delete in a Fixed Array

Reading any element of an array is instant, but making room for a new one in the middle, or closing the gap after removing one, means moving every element after it. This lesson traces those shifts slot by slot, explains why their direction matters, counts the cost exactly, and shows the cheaper alternatives when order does not matter.

~30 minBeginnerC# · Python · Java · C++
Curriculum: M05 Arrays · 5 of 5 lessons available

You will be able to

  • Trace insert and delete in a fixed-capacity array, including every shifted element.
  • Explain why a right shift must run from the end backwards and a left shift from the gap forwards.
  • Count the elements moved by an insert or delete at index i, and derive the best, worst and average cost.
  • Handle the full-array case and out-of-range positions correctly.
  • Choose between order-preserving delete and swap-with-last delete, and use the built-in equivalents in four languages.

Helpful before this lesson

  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

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:

  1. Reject the insert (the lab, and C++26's std::inplace_vector, which throws std::bad_alloc from push_back and offers try_push_back).
  2. Overwrite something, as a ring buffer does with the oldest element.
  3. 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 == size for delete or forbidding it for insert. Insert positions are 0 … size; delete positions are 0 … 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 at i, and i++ 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 − i elements (right shift, backwards); delete at i moves size − 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.

Full implementation

The fixed-capacity array in four languages, each checked against one shared fixture of get, set, insert, append and delete sequences (empty, full, capacity one, out-of-range indices, front, middle and end positions) including the exact number of elements shifted, and 2,000 random operation sequences compared with the built-in dynamic array (List<T>, list, ArrayList, std::vector) held to the same capacity.

namespace Bekadan.Dsa.Examples.Arrays;
 
/// <summary>
/// A fixed-capacity array of ints with a separate size, the way a stack-allocated
/// buffer or a preallocated int[] is used: the buffer never grows. Indexing is O(1);
/// insert and delete shift the tail and cost O(size - index). A full array rejects
/// inserts instead of reallocating (List&lt;T&gt; would grow here).
/// </summary>
public sealed class FixedArray
{
    private readonly int[] items;
    private int size;
 
    public FixedArray(int capacity) => items = new int[capacity];
 
    public int Size => size;
    public int Capacity => items.Length;
    /// <summary>Elements moved by Insert and Delete so far (for the lab and the tests).</summary>
    public int Shifts { get; private set; }
 
    /// <summary>Byte address of element <paramref name="index"/> in a block starting at <paramref name="baseAddress"/>.</summary>
    public static long AddressOf(long baseAddress, int index, int elementSize)
    {
        return baseAddress + (long)index * elementSize;
    }
 
    private void CheckIndex(int index)
    {
        if (index < 0 || index >= size) throw new ArgumentOutOfRangeException(nameof(index), $"Index {index} is outside 0..{size - 1}.");
    }
 
    public int Get(int index)
    {
        CheckIndex(index);
        return items[index];
    }
 
    public void Set(int index, int value)
    {
        CheckIndex(index);
        items[index] = value;
    }
 
    public void Append(int value) => Insert(size, value);
 
    public void Insert(int index, int value)
    {
        if (size == items.Length) throw new InvalidOperationException("The array is full.");
        if (index < 0 || index > size) throw new ArgumentOutOfRangeException(nameof(index), $"Index {index} is outside 0..{size}.");
        for (int j = size - 1; j >= index; j--)
        {
            items[j + 1] = items[j]; // from the end backwards: nothing is overwritten before it is copied
            Shifts++;
        }
        items[index] = value;
        size++;
    }
 
    public int Delete(int index)
    {
        CheckIndex(index);
        int removed = items[index];
        for (int j = index; j < size - 1; j++)
        {
            items[j] = items[j + 1]; // from the gap forwards
            Shifts++;
        }
        items[size - 1] = 0; // clear the stale copy (matters for reference types: lets the GC collect it)
        size--;
        return removed;
    }
 
    public int[] ToArray() => items[..size];
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Arrays/FixedArray.cs

"""A fixed-capacity array with a separate size.
 
The buffer is allocated once and never grows. Indexing is O(1); insert and
delete shift the tail and cost O(size - index). A full array rejects inserts
instead of reallocating (a Python list would grow here). Python lists hold
references, so the address arithmetic below describes the list's pointer
array, or a typed buffer such as array.array('i').
"""
 
 
class ArrayFullError(Exception):
    """Raised by insert/append when size == capacity."""
 
 
def address_of(base: int, index: int, element_size: int) -> int:
    return base + index * element_size
 
 
class FixedArray:
    def __init__(self, capacity: int) -> None:
        self._items = [0] * capacity  # allocated once
        self._size = 0
        self.shifts = 0  # elements moved by insert and delete (for the lab and the tests)
 
    @property
    def size(self) -> int:
        return self._size
 
    @property
    def capacity(self) -> int:
        return len(self._items)
 
    def _check_index(self, index: int) -> None:
        if index < 0 or index >= self._size:
            raise IndexError(f"index {index} is outside 0..{self._size - 1}")
 
    def get(self, index: int) -> int:
        self._check_index(index)
        return self._items[index]
 
    def set(self, index: int, value: int) -> None:
        self._check_index(index)
        self._items[index] = value
 
    def append(self, value: int) -> None:
        self.insert(self._size, value)
 
    def insert(self, index: int, value: int) -> None:
        if self._size == len(self._items):
            raise ArrayFullError("the array is full")
        if index < 0 or index > self._size:
            raise IndexError(f"index {index} is outside 0..{self._size}")
        for j in range(self._size - 1, index - 1, -1):
            self._items[j + 1] = self._items[j]  # from the end backwards
            self.shifts += 1
        self._items[index] = value
        self._size += 1
 
    def delete(self, index: int) -> int:
        self._check_index(index)
        removed = self._items[index]
        for j in range(index, self._size - 1):
            self._items[j] = self._items[j + 1]  # from the gap forwards
            self.shifts += 1
        self._items[self._size - 1] = 0  # drop the stale reference
        self._size -= 1
        return removed
 
    def to_list(self) -> list[int]:
        return self._items[: self._size]

Tested on CPython 3.14.0 · examples/python/dsa_examples/fixed_array.py

package dev.bekadan.dsa.arrays;
 
import java.util.Arrays;
 
/**
 * A fixed-capacity array of ints with a separate size: the buffer is allocated
 * once and never grows. Indexing is O(1); insert and delete shift the tail and
 * cost O(size - index). A full array rejects inserts instead of reallocating
 * (ArrayList would grow here).
 */
public final class FixedArray {
    private final int[] items;
    private int size;
    private int shifts;
 
    public FixedArray(int capacity) {
        items = new int[capacity];
    }
 
    public int size() {
        return size;
    }
 
    public int capacity() {
        return items.length;
    }
 
    /** Elements moved by insert and delete so far (for the lab and the tests). */
    public int shifts() {
        return shifts;
    }
 
    /** Byte address of element {@code index} in a block starting at {@code base}. */
    public static long addressOf(long base, int index, int elementSize) {
        return base + (long) index * elementSize;
    }
 
    private void checkIndex(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index " + index + " out of bounds for size " + size);
        }
    }
 
    public int get(int index) {
        checkIndex(index);
        return items[index];
    }
 
    public void set(int index, int value) {
        checkIndex(index);
        items[index] = value;
    }
 
    public void append(int value) {
        insert(size, value);
    }
 
    public void insert(int index, int value) {
        if (size == items.length) {
            throw new IllegalStateException("The array is full");
        }
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("Index " + index + " out of bounds for insert at size " + size);
        }
        for (int j = size - 1; j >= index; j--) {
            items[j + 1] = items[j]; // from the end backwards (System.arraycopy handles the overlap the same way)
            shifts++;
        }
        items[index] = value;
        size++;
    }
 
    public int delete(int index) {
        checkIndex(index);
        int removed = items[index];
        for (int j = index; j < size - 1; j++) {
            items[j] = items[j + 1]; // from the gap forwards
            shifts++;
        }
        items[size - 1] = 0; // clear the stale copy (for objects: null, so the GC can collect it)
        size--;
        return removed;
    }
 
    public int[] toArray() {
        return Arrays.copyOf(items, size);
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/arrays/FixedArray.java

#pragma once
 
#include <cstddef>
#include <cstdint>
#include <stdexcept>
#include <vector>
 
namespace bekadan::dsa {
 
// A fixed-capacity array of ints with a separate size: the buffer is allocated
// once and never grows (the idea behind C++26 std::inplace_vector). Indexing is
// O(1); insert and erase shift the tail and cost O(size - index). A full array
// throws instead of reallocating (std::vector would grow here).
 
inline std::uintptr_t address_of(std::uintptr_t base, std::size_t index, std::size_t element_size) {
    return base + index * element_size;
}
 
class FixedArray {
public:
    explicit FixedArray(std::size_t capacity) : items_(capacity) {}  // allocated once, never resized
 
    std::size_t size() const { return size_; }
    std::size_t capacity() const { return items_.size(); }
    // Elements moved by insert and erase so far (for the lab and the tests).
    std::size_t shifts() const { return shifts_; }
 
    int get(std::ptrdiff_t index) const {
        check_index(index);
        return items_[static_cast<std::size_t>(index)];
    }
 
    void set(std::ptrdiff_t index, int value) {
        check_index(index);
        items_[static_cast<std::size_t>(index)] = value;
    }
 
    void append(int value) { insert(static_cast<std::ptrdiff_t>(size_), value); }
 
    void insert(std::ptrdiff_t index, int value) {
        if (size_ == items_.size()) throw std::length_error("the array is full");
        if (index < 0 || index > static_cast<std::ptrdiff_t>(size_)) throw std::out_of_range("insert index out of range");
        const auto at = static_cast<std::size_t>(index);
        for (std::size_t j = size_; j > at; --j) {
            items_[j] = items_[j - 1];  // from the end backwards (std::move_backward does the same)
            ++shifts_;
        }
        items_[at] = value;
        ++size_;
    }
 
    int erase(std::ptrdiff_t index) {
        check_index(index);
        const auto at = static_cast<std::size_t>(index);
        const int removed = items_[at];
        for (std::size_t j = at; j + 1 < size_; ++j) {
            items_[j] = items_[j + 1];  // from the gap forwards
            ++shifts_;
        }
        items_[size_ - 1] = 0;  // clear the stale copy (for class types: destroy or reset it)
        --size_;
        return removed;
    }
 
    std::vector<int> to_vector() const { return {items_.begin(), items_.begin() + static_cast<std::ptrdiff_t>(size_)}; }
 
private:
    void check_index(std::ptrdiff_t index) const {
        if (index < 0 || index >= static_cast<std::ptrdiff_t>(size_)) throw std::out_of_range("index out of range");
    }
 
    std::vector<int> items_;
    std::size_t size_ = 0;
    std::size_t shifts_ = 0;
};
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/fixed_array.hpp

References