Sign in

What is a data structure, from memory cells to abstract types

Understand how computers organize information in memory, distinguish abstract data types from concrete implementations, and build a foundational data structure from scratch.

MonksBit Desk

November 26, 2026 · 8 min read · 30 views

Read

A data structure is a specialized format for organizing, processing, retrieving, and storing data in computer memory. It pairs an arrangement of values with a set of algorithms that enforce access rules and invariants efficiently.

You will need. Basic familiarity with variables and primitive types such as integers · Familiarity with writing simple functions and loops

How well do you know this already?

The full lesson

Level 1 · Beginner: Memory addresses, sequential storage, and the simplest container

A computer stores all data in random access memory, or RAM. You can picture RAM as an immense row of numbered mailboxes, where each number is a memory address. When a computer program assigns an integer to a variable, the operating system reserves a specific mailbox address to store that value's binary bits.

If you only store one integer, a single memory address is enough. However, software rarely operates on isolated values. When you track a sequence of numbers, such as temperature readings over a day, placing those values in arbitrary, scattered mailboxes forces you to remember dozens of disconnected addresses.

The simplest data structure is a contiguous sequence of elements, commonly known as a fixed array. By placing items directly beside each other in contiguous memory cells, the program only needs to remember the address of the very first cell. To reach the fifth item, the program calculates the start address plus the offset of four cells, jumping directly there in one mathematical step.

Below is a demonstration of how a fixed-size contiguous container holds data, accesses elements by position, and preserves values in memory without relying on dynamic sizing.

A minimal fixed-size sequence container built using plain storage slots

class FixedBuffer:    def __init__(self, capacity: int):        self.capacity = capacity        self.storage = [None] * capacity    def set(self, index: int, value: int) -> None:        if index < 0 or index >= self.capacity:            raise IndexError("Index out of bounds")        self.storage[index] = value    def get(self, index: int) -> int:        if index < 0 or index >= self.capacity:            raise IndexError("Index out of bounds")        return self.storage[index]buffer = FixedBuffer(3)buffer.set(0, 10)buffer.set(1, 20)buffer.set(2, 30)print(buffer.get(1))

Key takeaways

  • Memory consists of sequentially numbered addresses holding raw values.
  • A data structure organizes values according to structural rules to simplify access.
  • Contiguous storage enables direct calculations to find any item using an offset.

Level 2 · Intermediate: Abstract data types versus concrete data structures

Computer science separates the interface of data from its internal representation. An Abstract Data Type, or ADT, defines what operations are possible and what behavior they guarantee, but says nothing about how data sits in memory. For instance, a Dynamic Array ADT specifies operations like append, get, set, and length.

A concrete data structure is the physical implementation of an ADT in code and memory. The standard Python list is a dynamic array: internally, it allocates a contiguous buffer in memory with extra capacity. When new items exceed this allocated buffer, the structure creates a larger chunk of memory, copies existing items across, and discards the old block.

To see the difference between interface contracts and internal mechanics, we can build a DynamicArray from a fixed buffer. This implementation tracks two distinct variables: size, which is the count of valid elements visible to the user, and capacity, which is the total allocated space in the underlying storage.

When appending an item requires more capacity, the data structure doubles its allocated capacity. Doubling ensures that expensive full-buffer reallocations happen exponentially less often as the collection grows.

A complete dynamic array implementing resize growth and bounds checking

class DynamicArray:    def __init__(self):        self._capacity = 1        self._size = 0        self._storage = [None] * self._capacity    def __len__(self) -> int:        return self._size    def get(self, index: int):        self._validate_index(index)        return self._storage[index]    def set(self, index: int, value) -> None:        self._validate_index(index)        self._storage[index] = value    def append(self, value) -> None:        if self._size == self._capacity:            self._resize(self._capacity * 2)        self._storage[self._size] = value        self._size += 1    def _resize(self, new_capacity: int) -> None:        new_storage = [None] * new_capacity        for i in range(self._size):            new_storage[i] = self._storage[i]        self._storage = new_storage        self._capacity = new_capacity    def _validate_index(self, index: int) -> None:        if index < 0 or index >= self._size:            raise IndexError(f"Index {index} out of range for size {self._size}")arr = DynamicArray()for value in [100, 200, 300]:    arr.append(value)print("Size:", len(arr))print("Element at index 2:", arr.get(2))

Key takeaways

  • An Abstract Data Type defines the interface and mathematical contract without implementation details.
  • A concrete data structure decides exact layout in memory and algorithmic mechanics.
  • Capacity refers to reserved storage, while size refers to actual elements currently populated.

Level 3 · Advanced: Memory layouts, pointer structures, and hardware cache locality

Data structures fundamentally fall into two memory paradigms: contiguous allocations and node-based pointer chains. In a contiguous allocation like an array, elements sit immediately next to one another in physical RAM. In a node-based structure like a linked list or tree, each element is wrapped in a distinct heap object containing memory pointers to its neighbors.

Modern central processing units (CPUs) access RAM slowly compared to their clock speeds. To compensate, CPUs load memory into high-speed local caches in blocks of typically 64 bytes called cache lines. When your code reads an index in a contiguous array, the CPU fetches surrounding elements into cache automatically. This phenomenon is called spatial locality.

Node-based structures scatter allocations across non-contiguous addresses on the heap. Traversing a linked list causes frequent cache misses, forcing the CPU to stall while waiting for main memory to fetch isolated nodes. Consequently, contiguous structures routinely outperform pointer structures in production systems even when both share identical Big-O time complexity.

System architects choose data structures based on hardware trade-offs. If insertions happen exclusively at endpoints and sequential scanning dominates, contiguous arrays are optimal. If memory fragmentation prevents large allocations, or if structural splits and splices must occur without shifting contiguous bytes, pointer-based structures remain necessary despite cache penalties.

A node-based linked chain illustrating reference pointer organization

class Node:    def __init__(self, value, next_node=None):        self.value = value        self.next = next_nodeclass SinglyLinkedList:    def __init__(self):        self.head = None    def prepend(self, value) -> None:        self.head = Node(value, self.head)    def find(self, target) -> bool:        current = self.head        while current is not None:            if current.value == target:                return True            current = current.next        return Falsell = SinglyLinkedList()ll.prepend(30)ll.prepend(20)ll.prepend(10)print("Found 20:", ll.find(20))print("Found 99:", ll.find(99))

Key takeaways

  • Contiguous structures benefit from CPU cache lines through spatial locality.
  • Node-based structures offer flexible per-node allocation at the expense of pointer overhead and cache misses.
  • Hardware architecture influences real-world runtime just as heavily as asymptotic time complexity.

Complexity

  • Time: O(1) lookup by index, O(1) amortized append, O(n) worst-case resize append
  • Space: O(n) auxiliary space proportional to element count

Accessing an element at an index in a contiguous array is O(1) because the address is computed via offset arithmetic. Appending is O(1) on average because doubling the capacity occurs at exponential intervals, though a single resizing operation requires copying n elements in O(n) time.

Common mistakes

  • Confusing an Abstract Data Type with its underlying concrete implementation, such as assuming a Map must always be a Hash Table.
  • Ignoring CPU cache effects by assuming all operations with equivalent Big-O complexity run at the exact same physical speed.
  • Failing to track capacity independently from size, leading to buffer overflows or out-of-bounds reads.
  • Using node-based pointer chains for small, frequently iterated datasets where arrays would provide superior spatial locality.

Practice problems

  1. Fixed Buffer Bounds Checker (easy). Hint: Ensure negative index handling and upper boundary checks raise descriptive exceptions before accessing storage.
  2. Shrinking Dynamic Array (medium). Hint: Trigger a capacity halving when size drops to a fraction of capacity, but avoid resizing when capacity is already minimal.
  3. Cache Benchmark Simulation (hard). Hint: Measure traversal times over an array of integers compared to a singly linked list storing identical quantities of items.

Summary

A data structure is an organized layout of values in memory paired with algorithms that enforce access rules. Understanding data structures requires distinguishing high-level abstract interfaces from concrete physical memory layouts, where cache locality and pointer mechanics govern real-world performance.

Was this helpful?

Comments (0)

Sign in or create an account to join the conversation.

  • No comments yet. Be the first!