Guide

Textbook data structures come with big-O costs, and those costs are a good start. In real systems, two other factors often decide the result. One is memory layout: whether the data is contiguous or spread across the heap, and whether it fits in cache. The other is which operations dominate: lookups, inserts, ordered scans or removals from the front. Choosing well means considering both.

A structure that is O(log n) on paper can lose to an O(n) scan over a small contiguous array. The array fits in cache lines and the CPU prefetches it, while the tree chases pointers to random memory.

The big idea

Pick a structure by asking three questions:

  1. What do I do most often? Look up by key, scan in order, find the minimum, or remove the oldest?
  2. How big does it get? A few hundred items and a few million items call for different choices.
  3. Where does it live? In cache, in RAM, or on disk, which changes the cost of each jump.

Concepts in this topic

StepConceptWhat it answers
1Arrays and memory layoutWhy contiguous data is fast, and when a ring buffer wins
2Hash mapsHow do keys map to buckets, and when do they degrade?
3Heaps and top-kHow do you keep the k largest items cheaply?
4Sorted trees, skip lists and triesHow do you keep keys ordered, and search by prefix?
5LRU cachesHow do you evict the least recently used item in constant time?
6Graphs and topological sortHow do you order tasks with dependencies?

For probabilistic structures that trade exactness for size, such as Bloom filters and HyperLogLog, see probabilistic data structures.

A quick decision guide

Start with the dominant operation and the expected size. A few hundred items with simple access? Use the simplest structure, often an array, since it's fast and easy to test. Millions of keys with range queries? Use a sorted tree, or a B+tree if the data lives on disk. Repeated top-k queries? Use a heap. Repeated eviction of old items? Use an LRU. Dependencies between tasks? Use a graph with a topological sort.

Then measure. A simple array often beats a clever structure on real data, because the locality and the constant factors matter more than the asymptotic class at your size.

Common mistakes

  • Choosing a structure by big-O alone and ignoring cache behavior.
  • Using a hash map when a sorted array with binary search would give range queries for free.
  • Treating a data structure as safe under adversarial input. Hash maps and sorting can be attacked with crafted keys.

Key takeaways

  • Choose by the dominant operation, the expected size and where the data lives.
  • Contiguous structures often beat asymptotically better pointer-based ones.
  • Know the standard combinations: hash map plus list for LRU, heap for top-k, graph plus topological sort for build order.

Further learning

Start with arrays and memory layout. It explains why the same big-O can run at very different speeds.