Choosing the right data structure is often the difference between code that scales and code that crawls. You do not need to implement them from scratch — modern languages provide them — but you do need to know what each is good and bad at, so you reach for the right one.
Arrays and lists
An array stores items in order, accessed by index. Reading or writing by index is instant, and iterating is fast and cache-friendly. The weak spots are inserting or removing in the middle, which shifts everything after it, and searching for a value, which means scanning. Arrays are the right default when you mostly append and iterate.
Hash maps
A hash map stores key-value pairs and is the workhorse of fast lookups. Finding, inserting and deleting by key are effectively constant time, which is why hash maps appear everywhere — caches, indexes, counting, deduplication. The trade-off is that they have no inherent order, and they use more memory than a plain array.
Stacks and queues
These are about order of access. A stack is last-in-first-out — like a stack of plates — and models things like undo history and function calls. A queue is first-in-first-out — like a line of people — and models task processing and buffering. Both are simple but express intent clearly, which matters for correctness.
Trees and graphs
When data is hierarchical or interconnected, trees and graphs fit naturally. A tree models hierarchy — file systems, the DOM, organization charts — and balanced search trees keep lookups fast while maintaining order. A graph models arbitrary relationships — social networks, maps, dependencies — and comes with algorithms for finding paths and connections.
- Arrays: fast index access and iteration; slow middle inserts and searches.
- Hash maps: near-instant key lookups; no order.
- Stacks (LIFO) and queues (FIFO) express access order clearly.
- Trees model hierarchy; graphs model arbitrary relationships.
Frequently asked questions
Do I need to memorize implementations?
Rarely. Knowing the trade-offs and choosing the right structure matters far more day to day than implementing one from scratch.
Why is a hash map lookup so fast?
It computes a hash of the key to jump close to where the value is stored, avoiding a scan. This gives near-constant-time access on average.