Data structure · Linear structures
Fixed-capacity array
A block of equal-sized slots that never grows: O(1) access by computed address, O(n) insert and delete by shifting, and an error when full.
The derivations, edge cases and exercises are in the lesson Contiguous storage, addresses and cache locality. Open it full width in the playground.
On this page
The idea
An array is one contiguous block, so the address of element i is base + i × element size and any element is one step away. A fixed-capacity array keeps a separate size: slots 0 … size − 1 are in use, the rest are free.
Inserting or deleting in the middle shifts the tail by one slot. When the array is full an insert fails rather than growing, which is exactly the limitation a dynamic array removes.
Representation. One contiguous block of capacity slots plus a size count; every index is checked against size.
Operations
| Operation | Time | Extra space | Notes |
|---|---|---|---|
| Get / set by index | O(1) | O(1) | Index must be below size. |
| Append | O(1) | O(1) | Fails when size = capacity. |
| Insert at index | O(n − i) | O(1) | Shifts the tail right, from the end backwards. |
| Delete at index | O(n − i) | O(1) | Shifts the tail left and clears the freed slot. |
Invariants
What stays true before and after every operation.
- 0 ≤ size ≤ capacity, and capacity never changes.
- Only slots 0 … size − 1 are readable; any other index is an error.
When to use it
Use it when
- The maximum size is known in advance: buffers, lookup tables, fixed grids.
- You want no hidden reallocations, so addresses and references stay valid.
Avoid it when
- The number of elements is unknown or grows: use a dynamic array.
- You insert or delete in the middle often.
Built-in equivalents
What the standard library of each language offers. Linked types have a full page in the collections encyclopedia with every operation’s complexity, memory effects and a tested example.
C#
T[] has a fixed length set at creation; Span<T> views part of one.
Python
No fixed-size array type; array.array and bytearray are growable but store raw values contiguously.
Java
T[] has a fixed length set at creation.
C++
std::array<T, N> has a compile-time size; a built-in T[N] too.
Step through it
The interactive lab for fixed-capacity array: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.
Implementation in four languages
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<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
Learn more
Lessons
- Contiguous storage, addresses and cache locality· M02 Memory Model
- Array layout and indexing· M05 Arrays
- Insert and delete in a fixed array· M05 Arrays