Sign in

Arrays, from contiguous memory layouts to dynamic resizing

Understand how arrays store data sequentially in memory, implement random access and mutations, and build a resizing dynamic array.

MonksBit Desk

November 17, 2026 · 7 min read · 69 views

Read

An array is a linear data structure that stores a collection of elements in contiguous memory locations. It allows direct access to any element in constant time using an integer index representing its offset from the start.

You will need. Basic variable assignment · Familiarity with loops and conditional statements

How well do you know this already?

The full lesson

Level 1 · Beginner: Understanding indexing and linear memory traversal

An array holds multiple values under a single identifier. Each position within an array is designated by an integer index, which starts at 0 in most programming languages. Because elements are arranged back-to-back, locating an item at index i requires only multiplying i by the size of a single element and adding that offset to the starting memory address.

Consider an array of four integers: [12, 99, 37, 45]. Index 0 stores 12, index 1 stores 99, index 2 stores 37, and index 3 stores 45. Reading or writing the element at index 2 takes a single step because the computer knows precisely where the second slot resides without reading earlier elements.

However, inspecting every element in sequence or searching for a value without knowing its index requires checking each slot one by one. This traversal begins at index 0 and advances until the target is found or the end of the array is reached.

Basic array access and linear search in Python

def find_index(items, target):    for i in range(len(items)):        if items[i] == target:            return i    return -1numbers = [12, 99, 37, 45]print(numbers[2])numbers[2] = 42print(find_index(numbers, 42))print(find_index(numbers, 100))

Key takeaways

  • Arrays store items in contiguous memory slots.
  • Access by index is direct and takes constant time.
  • Finding an unknown element requires inspecting slots sequentially.

Level 2 · Intermediate: Inserting, deleting, and building a dynamic array

While reading from an index is instantaneous, modifying the structure requires moving elements. If you want to insert a new value at index 1 in an array of five elements, every element from index 1 onward must shift one position to the right to make room. Similarly, deleting an element at index 1 requires shifting all trailing elements left to close the gap.

Fixed-capacity arrays cannot grow once allocated. High-level languages solve this using a dynamic array. A dynamic array maintains an internal fixed-size buffer, a capacity denoting the total slots in that buffer, and a size tracking the number of slots currently occupied.

When the size reaches capacity, the dynamic array allocates a new underlying buffer with twice the capacity, copies all existing items into the new buffer, and frees the old buffer. Because doublings occur less and less frequently, appending an element takes constant time on average, despite the occasional expensive copy.

A minimal dynamic array implementation

class DynamicArray:    def __init__(self):        self._capacity = 2        self._size = 0        self._data = [None] * self._capacity    def __len__(self):        return self._size    def __getitem__(self, index):        if not 0 <= index < self._size:            raise IndexError("Index out of range")        return self._data[index]    def append(self, value):        if self._size == self._capacity:            self._resize(2 * self._capacity)        self._data[self._size] = value        self._size += 1    def insert(self, index, value):        if not 0 <= index <= self._size:            raise IndexError("Index out of range")        if self._size == self._capacity:            self._resize(2 * self._capacity)        for i in range(self._size, index, -1):            self._data[i] = self._data[i - 1]        self._data[index] = value        self._size += 1    def delete_at(self, index):        if not 0 <= index < self._size:            raise IndexError("Index out of range")        removed = self._data[index]        for i in range(index, self._size - 1):            self._data[i] = self._data[i + 1]        self._data[self._size - 1] = None        self._size -= 1        return removed    def _resize(self, new_capacity):        new_data = [None] * new_capacity        for i in range(self._size):            new_data[i] = self._data[i]        self._data = new_data        self._capacity = new_capacity

Key takeaways

  • Inserting or deleting in the middle requires shifting trailing elements.
  • Dynamic arrays automatically resize by allocating a larger buffer and copying data.
  • Bounds checking ensures operations do not read or overwrite unallocated memory.

Level 3 · Advanced: Amortized analysis, cache locality, and trade-offs

The performance of resizing in dynamic arrays is governed by amortized analysis. When resizing by a constant factor, such as 2, a sequence of N appends triggers reallocations at sizes 1, 2, 4, 8, up to N. Summing these copies yields approximately 2N copy operations. Distributing these 2N operations across all N appends yields an amortized cost of O(1) time per append.

Arrays offer superior performance compared to linked structures due to hardware cache locality. Modern CPU architectures load data into fast cache lines in blocks, typically 64 bytes at a time. Because array elements reside side-by-side, iterating through an array yields sequential memory hits, dramatically outperforming pointer-chasing structures like linked lists.

Despite these advantages, arrays have trade-offs. Arbitrary insertions and deletions remain O(N) operations. If an application requires frequent middle-element insertions without random access, a linked list or tree-based structure is typically more appropriate. Furthermore, over-allocating capacity to accommodate growth introduces memory overhead that must be balanced against resize frequency.

In-place array partitioning using the two-pointer technique

def remove_duplicates_in_place(nums):    if not nums:        return 0    write_index = 1    for read_index in range(1, len(nums)):        if nums[read_index] != nums[read_index - 1]:            nums[write_index] = nums[read_index]            write_index += 1    return write_indexdata = [1, 1, 2, 3, 3, 3, 4]length = remove_duplicates_in_place(data)print(data[:length])

Key takeaways

  • Geometric buffer doubling guarantees amortized O(1) appends.
  • Contiguous memory layouts optimize hardware CPU cache line usage.
  • In-place modifications minimize auxiliary memory consumption.

Complexity

  • Time: Access: O(1). Search: O(N). Insertion: O(1) amortized at end, O(N) at arbitrary index. Deletion: O(1) at end, O(N) at arbitrary index.
  • Space: O(N) total space to store N elements, with up to O(N) unused buffer space in dynamic arrays.

Accessing any position takes constant time via memory address arithmetic. Arbitrary insertions and deletions require shifting adjacent elements proportional to the array length, taking linear time.

Common mistakes

  • Off-by-one errors when referencing the last valid index, which is length minus one in 0-indexed systems.
  • Resizing a dynamic array by adding a fixed constant rather than multiplying by a factor, which degrades append complexity to O(N).
  • Modifying or deleting elements from an array while iterating over its indices forward, leading to skipped elements.
  • Assuming linear search in an array is equivalent to hash map lookups, forgetting that array search takes O(N) time.

Practice problems

  1. Reverse an array in place (easy). Hint: Use two pointers, one at the start and one at the end, swapping elements as they move inward.
  2. Rotate array by K steps (medium). Hint: Try reversing the whole array, then reversing the first k elements and the remaining elements separately.
  3. Merge overlapping intervals (hard). Hint: Sort the intervals by their start indices first, then compare adjacent intervals to merge them in a single pass.

Summary

Arrays form the bedrock of computer memory structures by providing O(1) random access across contiguous memory addresses. Dynamic arrays build upon this foundation by geometric resizing to offer efficient appends, balancing high cache locality with the cost of linear shifts during arbitrary insertions.

Was this helpful?

Comments (0)

Sign in or create an account to join the conversation.

  • No comments yet. Be the first!