Arrays and dynamic arrays · get/set O(1); insert/delete O(n − i)
Fixed-capacity array
Get, set, insert and delete in a buffer that never grows; size vs capacity and address = base + i·size.
The full explanation, derivation and practice are in the lesson Insert and delete in a fixed array.
Implementation
The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.
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<T> 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