Sign in

Data structures and algorithms, from core concepts to system design

Learn how data structures organise memory, how algorithms operate on that memory, and how to select complementary pairs to design scalable systems.

MonksBit Desk

November 26, 2026 · 8 min read · 88 views

Read

A data structure is a specialised format for organising, processing, retrieving, and storing data in computer memory. An algorithm is a finite, step-by-step sequence of well-defined instructions designed to perform a specific computation or solve a given problem. While data structures represent passive arrangements of state, algorithms represent the active procedures that transform and query that state.

You will need. Basic programming syntax in Python · Understanding variables, loops, and conditional statements

How well do you know this already?

The full lesson

Level 1 · Beginner: Understanding the separation of state and procedure

Every program consists of two fundamental components: data and operations. A data structure answers the question of how information rests in memory. For instance, storing a group of user identifiers can be done in a contiguous list where elements sit next to each other, or in an associative mapping where each identifier maps directly to a location.

An algorithm answers the question of what concrete steps are required to achieve an outcome using that data. If we want to verify whether a user exists, the algorithm we execute depends entirely on how the data is structured. If the users are kept in an unsorted list, our algorithm must inspect each element one by one until it finds a match or reaches the end.

Consider a concrete example: searching for the number 7 in the sequence [2, 4, 7, 9]. The sequence itself is our data structure (an array). The procedure of checking index 0, seeing 2 is not 7, advancing to index 1, seeing 4 is not 7, and advancing to index 2 to confirm 7 is our algorithm (linear search). If the data structure changes, our algorithm must adapt.

Linear search algorithm operating on an array data structure

def contains_item(data: list[int], target: int) -> bool:    for item in data:        if item == target:            return True    return Falsenumbers = [2, 4, 7, 9]found = contains_item(numbers, 7)print(found)

Key takeaways

  • A data structure stores and arranges elements in memory.
  • An algorithm executes a finite series of steps to compute a result over data.
  • An algorithm's implementation and efficiency directly depend on the underlying data structure.

Level 2 · Intermediate: Trade-offs and pairing algorithms with appropriate structures

The choice of data structure defines the lower bound of an algorithm's complexity. A standard contiguous array provides instant access to elements by their index because the memory location of any item can be calculated directly. However, searching through an unsorted array requires scanning every entry in the worst case, producing an execution time that scales linearly with the input size.

If we change the data structure to a hash table, where a mathematical function maps keys directly to internal buckets, an algorithm can check for membership in constant time on average. Alternatively, if we maintain an array in sorted order, we can use binary search to repeatedly divide the search space in half, finding elements in logarithmic time.

Software design requires evaluating these complementary choices against workload requirements. For example, maintaining a sorted array makes lookups fast but makes insertions slow because shifting elements takes linear time. A hash set makes lookups and insertions fast on average, but consumes more memory and does not retain the sorted order of items. System designers weigh these trade-offs against expected read and write ratios.

Comparing search approaches across an ordered array and a hash set

def binary_search(sorted_arr: list[int], target: int) -> bool:    left = 0    right = len(sorted_arr) - 1    while left <= right:        mid = (left + right) // 2        if sorted_arr[mid] == target:            return True        elif sorted_arr[mid] < target:            left = mid + 1        else:            right = mid - 1    return Falsedef hash_lookup(lookup_set: set[int], target: int) -> bool:    return target in lookup_setsorted_data = [10, 20, 30, 40, 50]hash_data = {10, 20, 30, 40, 50}assert binary_search(sorted_data, 30) is Trueassert binary_search(sorted_data, 99) is Falseassert hash_lookup(hash_data, 30) is Trueassert hash_lookup(hash_data, 99) is False

Key takeaways

  • Data structures determine the memory layout and constrain algorithm choices.
  • Binary search achieves logarithmic time but requires an ordered, indexable structure.
  • Hash tables achieve constant time lookups on average by trading off memory overhead and ordering guarantees.

Level 3 · Advanced: System-level integration, caching, and database indexing

At system scale, the boundary between data structures and algorithms forms the backbone of infrastructure architecture. Production databases, distributed caches, and message queues are real-world encapsulations of specific data structures paired with retrieval and eviction algorithms.

Consider a database indexing layer. A relational database typically uses a B-Tree or B+ Tree data structure on disk. B-Trees organise sorted keys into wide, balanced nodes designed to match disk block sizes, minimising slow disk I/O operations. The search algorithm navigates this tree in logarithmic time, reading only a handful of blocks to retrieve a record out of millions. In contrast, in-memory databases like Redis use skip lists and hash tables because random memory access does not carry the high latency penalty of mechanical disks or standard solid-state drives.

Another fundamental system pattern is the Least Recently Used (LRU) cache. Implementing an LRU cache efficiently requires combining two distinct data structures: a doubly linked list and a hash map. The doubly linked list preserves eviction order, allowing elements to be moved to the head or removed from the tail in constant time. The hash map stores references directly to the nodes in the linked list, allowing lookup in constant time. The algorithm for reading a key checks the hash map, moves the accessed node to the list head, and returns the value. The algorithm for writing inserts a new node at the head and, if capacity is exceeded, evicts the tail node and removes its reference from the hash map.

Recognising the interplay of data structures and algorithms allows engineers to diagnose bottlenecks in large distributed systems. Choosing the wrong pair can lead to memory exhaustion, cache thrashing, or high latency spikes under concurrent workloads.

LRU cache combining a doubly linked list with a hash map

class Node:    def __init__(self, key: int, value: int):        self.key = key        self.value = value        self.prev = None        self.next = Noneclass LRUCache:    def __init__(self, capacity: int):        self.capacity = capacity        self.cache = {}        self.head = Node(0, 0)        self.tail = Node(0, 0)        self.head.next = self.tail        self.tail.prev = self.head    def _remove(self, node: Node) -> None:        node.prev.next = node.next        node.next.prev = node.prev    def _add_to_head(self, node: Node) -> None:        node.next = self.head.next        node.prev = self.head        self.head.next.prev = node        self.head.next = node    def get(self, key: int) -> int:        if key not in self.cache:            return -1        node = self.cache[key]        self._remove(node)        self._add_to_head(node)        return node.value    def put(self, key: int, value: int) -> None:        if key in self.cache:            node = self.cache[key]            node.value = value            self._remove(node)            self._add_to_head(node)            return        if len(self.cache) >= self.capacity:            lru_node = self.tail.prev            self._remove(lru_node)            del self.cache[lru_node.key]        new_node = Node(key, value)        self.cache[key] = new_node        self._add_to_head(new_node)

Key takeaways

  • Modern storage engines choose data structures based on hardware characteristics like cache lines and disk block sizes.
  • Complex system components often combine multiple data structures to meet multiple performance criteria simultaneously.
  • An LRU cache pairs a hash map and a doubly linked list to achieve O(1) reads, writes, and evictions.

Complexity

  • Time: Lookup: O(1) average for hash map, O(log N) for binary search on sorted array, O(N) for linear search on unsorted list
  • Space: O(N) auxiliary space where N is the number of stored elements

Linear search checks up to N elements sequentially. Binary search repeatedly halves an ordered sequence of N items, yielding logarithmic time. Hash map lookups compute an array offset directly via a hash function, executing in constant time on average, but consume O(N) memory to store buckets and pointers.

Common mistakes

  • Treating data structures and algorithms as independent subjects rather than tightly coupled choices.
  • Applying an algorithm to an incompatible data structure, such as attempting binary search on a singly linked list.
  • Ignoring memory allocation and hardware overhead when selecting structures that have theoretical O(1) performance.
  • Prematurely optimising for algorithmic time complexity while neglecting cache locality and constant-factor overhead.

Practice problems

  1. Unsorted to set lookup (easy). Hint: Convert a list lookup into an operation on a set to avoid repeated linear scans over identical queries.
  2. Frequency counter with hash map (medium). Hint: Count occurrences of items in an array in a single linear pass by storing frequencies as dictionary values.
  3. Design a bounded in-memory sliding window rate limiter (hard). Hint: Combine a queue or sorted set to record timestamps with an algorithm that purges entries older than the current window.

Summary

Data structures dictate how state is laid out in memory, while algorithms define the sequence of actions that inspect and alter that state. Writing efficient software requires pairing the correct data structure with an algorithm tailored to its access characteristics. In system design, these pairings dictate the architecture of databases, caching tiers, and real-time processing pipelines.

Was this helpful?

Comments (0)

Sign in or create an account to join the conversation.

  • No comments yet. Be the first!