Arrays, hash maps, heaps, balanced trees, B-trees, LSM-trees, tries and Bloom filters: what each one is good at, and where real systems use it.
An algorithm is only as fast as the data structure underneath it. Dijkstra's algorithm is O((V + E) log V) because it uses a heap. Database lookups are fast because the data lives in a B-tree. When you choose a data structure, you're really choosing which operations will be cheap and which will be expensive.
This article covers the structures that matter in practice, what each one is good at, and where you'll find it in real systems. It follows on from Algorithms, Visually.
Before picking a structure, list the operations your code performs most often:
Then pick the structure that makes those operations cheap. Here's the cheat sheet; the rest of the article explains it.
| Structure | Access by index | Search | Insert / delete | Ordered? | Typical use |
|---|---|---|---|---|---|
| Dynamic array | O(1) |
O(n) |
O(1) at end, O(n) in middle |
By position | Default list |
| Linked list | O(n) |
O(n) |
O(1) given the node |
By position | LRU cache internals |
| Hash map | â | O(1) average |
O(1) average |
No | Lookups, de-duplication |
| Heap | â | O(n) |
O(log n) |
Min/max only | Priority queues, top-k |
| Balanced BST | â | O(log n) |
O(log n) |
Yes | Ordered maps |
| B-tree | â | O(log n) |
O(log n) |
Yes | Database and file system indexes |
| LSM-tree | â | O(log n), slower reads |
Very fast writes | Yes | Write-heavy databases |
| Trie | â | O(key length) |
O(key length) |
Yes, by prefix | Autocomplete, IP routing |
| Bloom filter | â | O(k), probabilistic |
O(k) |
No | "Definitely not present" checks |
An array is a single contiguous block of memory. Item i lives at start + i Ă item_size, so indexing is O(1). Because the items sit next to each other, iterating is also very cache-friendly. The CPU loads memory in 64-byte cache lines, so reading one item brings its neighbors along for free. (More on that in How Computers Actually Run Your Code.)
A dynamic array (Python list, Go slice, Java ArrayList, C++ std::vector) adds automatic growth. When it fills up, it allocates a bigger block and copies everything across. Growing by a constant factor rather than a constant amount makes appends O(1) amortized: the occasional expensive copy is spread across many cheap appends.
You can watch CPython over-allocate:
import sys
lst, last = [], sys.getsizeof([])
for i in range(20):
lst.append(i)
size = sys.getsizeof(lst)
if size != last: # capacity only changes now and then
print(f"len={len(lst):2} bytes={size}")
last = size
# On CPython 3.12 the capacity jumps at len 1, 5, 9 and 17, not on every append
What arrays are bad at is inserting or deleting at the front or middle, which shifts every later item. list.pop(0) is O(n). If you need a queue, use collections.deque, which is O(1) at both ends:
from collections import deque
queue = deque()
queue.append("job-1") # enqueue at the right
queue.append("job-2")
print(queue.popleft()) # job-1, O(1); list.pop(0) would be O(n)
A linked list stores each item in its own node with a pointer to the next one. Inserting or removing a node you already hold is O(1). But finding a node is O(n), and every step follows a pointer to a random memory location, which is a likely cache miss.
In practice, dynamic arrays beat linked lists for almost everything, even middle insertions on modest sizes, because shifting contiguous memory is so fast. Linked lists earn their place inside other structures: an LRU cache combines a hash map (find the entry) with a doubly linked list (move it to the front in O(1)). Python's functools.lru_cache and OrderedDict are built that way.
Covered in detail in the algorithms article. In short: a hash function picks a bucket, giving O(1) average lookup, insert and delete. Two things to remember:
dict remembers insertion order, which is not the same thing as sorted order.list as a dict key.A binary heap is a tree stored in an array where every parent is smaller than its children (for a min-heap). The smallest item is always at index 0. Push and pop are O(log n), because an item moves along at most one root-to-leaf path.
Use a heap whenever you repeatedly need "the next most important thing": task schedulers, Dijkstra, merging sorted files, or the top-k problem:
import heapq
scores = {"ana": 91, "ben": 78, "chen": 99, "dev": 85, "eli": 94}
# Top 3 in O(n log k), without sorting everything
print(heapq.nlargest(3, scores.items(), key=lambda kv: kv[1]))
# [('chen', 99), ('eli', 94), ('ana', 91)]
# Priority queue: (priority, item) tuples, smallest priority first
tasks = []
heapq.heappush(tasks, (2, "write report"))
heapq.heappush(tasks, (1, "fix prod outage"))
heapq.heappush(tasks, (3, "update docs"))
print(heapq.heappop(tasks)) # (1, 'fix prod outage')
In a binary search tree, every node's left subtree holds smaller keys and its right subtree larger ones, so search works like binary search. If keys arrive in sorted order, though, a naive BST turns into a linked list and degrades to O(n). Self-balancing trees (red-black trees, AVL trees) rotate nodes on insert to keep the height at O(log n).
You get them as ordered maps: Java's TreeMap, C++'s std::map, and the Linux kernel's scheduler and memory maps, which use red-black trees. Python has no built-in balanced tree. The usual substitutes are a sorted list with bisect (fine when reads dominate) or the sortedcontainers package.
import bisect
prices = [5, 12, 20, 33, 47, 50, 68] # kept sorted
lo = bisect.bisect_left(prices, 20)
hi = bisect.bisect_right(prices, 50)
print(prices[lo:hi]) # [20, 33, 47, 50], a range query in O(log n)
A binary tree with a million keys is about 20 levels deep. If each level is a disk read, that's 20 slow reads per lookup. A B-tree fixes this by making each node wide. A node is sized to one disk page (often 4â16 KiB) and holds hundreds of keys. With a fan-out of 500, three levels cover 125 million keys, and the top levels usually sit in memory anyway.
| Binary tree | B-tree (fan-out 500) | |
|---|---|---|
| Levels for 1 million keys | ~20 | 3 |
| Disk reads per lookup | up to 20 | ~1â3 |
B-trees, usually the B+ tree variant where values live only in the leaves and the leaves are linked for fast range scans, are the default index in PostgreSQL, MySQL/InnoDB, SQLite, and file systems such as NTFS, Btrfs and XFS. When you CREATE INDEX, you're building one.
B-trees update pages in place, which means random writes. A Log-Structured Merge-tree takes the opposite approach:
All disk writes are sequential, so ingest is very fast. The cost is on reads, which may have to check several SSTables. That's where Bloom filters come in (below). RocksDB, LevelDB, Cassandra, ScyllaDB and the storage layers of many time-series databases use LSM-trees.
Rule of thumb: B-trees suit read-heavy, update-in-place workloads. LSM-trees suit write-heavy, append-mostly workloads.
A trie (prefix tree) stores strings character by character, so all words sharing a prefix share a path. Lookup costs O(length of the key), no matter how many words are stored, and "find everything starting with X" is natural.
class Trie:
def __init__(self):
self.root = {}
def insert(self, word):
node = self.root
for ch in word:
node = node.setdefault(ch, {})
node["$"] = True # marks the end of a word
def starts_with(self, prefix):
node = self.root
for ch in prefix:
if ch not in node:
return []
node = node[ch]
out, stack = [], [(node, prefix)]
while stack:
n, word = stack.pop()
if "$" in n:
out.append(word)
stack.extend((child, word + ch) for ch, child in n.items() if ch != "$")
return sorted(out)
t = Trie()
for w in ["car", "card", "care", "cat", "dog"]:
t.insert(w)
print(t.starts_with("car")) # ['car', 'card', 'care']
Tries power autocomplete, spell checkers, and, in a compressed binary form called a radix tree, IP routing tables, where a router finds the longest matching network prefix for each packet.
A Bloom filter answers "is this item in the set?" with either "definitely not" or "probably yes", using a small fraction of the memory the set itself would need. It's a bit array plus k hash functions. Adding an item sets k bits. Checking an item tests those k bits; if any is 0, the item was never added.
import hashlib
class BloomFilter:
def __init__(self, size_bits=1024, num_hashes=4):
self.size, self.k = size_bits, num_hashes
self.bits = bytearray(size_bits // 8)
def _positions(self, item):
for i in range(self.k):
h = hashlib.sha256(f"{i}:{item}".encode()).digest()
yield int.from_bytes(h[:8], "big") % self.size
def add(self, item):
for p in self._positions(item):
self.bits[p // 8] |= 1 << (p % 8)
def might_contain(self, item):
return all(self.bits[p // 8] & (1 << (p % 8)) for p in self._positions(item))
bf = BloomFilter()
for user in ["alice", "bob", "carol"]:
bf.add(user)
print(bf.might_contain("alice")) # True, probably present
print(bf.might_contain("mallory")) # False, definitely not present (almost certainly)
False positives are possible, but false negatives never happen. With m bits, n items and k hashes, the false-positive rate is about (1 â e^(âkn/m))^k. Around 10 bits per item with 7 hashes gives roughly a 1% false-positive rate.
Real uses: LSM databases check a Bloom filter before opening each SSTable, skipping files that can't contain the key. CDNs and caches use them to avoid caching one-hit wonders. Browsers have used them to check URLs against malware lists without downloading the whole list.
A skip list is a sorted linked list with extra "express lane" pointers that skip ahead, chosen randomly so that each higher lane has about half as many nodes. Search, insert and delete are O(log n) on average, with much simpler code than a balanced tree, and they're easier to make concurrent. Redis uses a skip list for sorted sets (ZADD, ZRANGE), and Java has ConcurrentSkipListMap.
Real systems combine these structures:
When performance matters, ask which operations you perform most often. Then pick the structure that makes those operations cheap, and accept the cost of the ones you rarely need.