Data Structures Every Developer Should Know
A practical tour of the data structures you actually use: arrays, hash maps, sets, stacks, queues, trees, heaps and graphs, with real trade-offs.
By Velloreth
What a data structure really is
A data structure is a way of arranging data in memory so that the operations you perform most often are cheap. That is the whole idea, and it reframes the question usefully.
There is no “best” data structure, because there is no such thing as a cheap operation in the abstract. Every structure makes some operations fast by making others slow. An array makes indexing fast and insertion in the middle slow. A hash map makes lookup by key fast and iteration in order impossible. Choosing a data structure is choosing which operations to optimise.
So the practical question is always: what does my code do most often with this data?
Arrays: the default
An array stores elements in contiguous memory, which is why indexing is O(1) — the address of element i is just the base address plus i times the element size.
const scores = [88, 92, 75, 96];
scores[2]; // 75 — O(1)
scores.push(81); // O(1) amortised
scores.unshift(60); // O(n) — shifts every element
| Operation | Cost |
|---|---|
| Access by index | O(1) |
| Append | O(1) amortised |
| Insert/remove at front or middle | O(n) |
| Search by value | O(n) |
The contiguous layout is also why arrays are fast in practice beyond their Big-O: modern CPUs read adjacent memory efficiently, so iterating an array is far quicker than the complexity analysis alone suggests.
Use arrays when order matters, you access by position, or you iterate over everything.
Hash maps: the workhorse
A hash map stores key-value pairs and computes the storage location from the key, giving O(1) average lookup.
const counts = new Map();
for (const word of ['a', 'b', 'a', 'c', 'a']) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
counts.get('a'); // 3
This is the structure that turns O(n²) algorithms into O(n) ones. Any time you find yourself scanning an array inside a loop to check whether something exists, a hash map is the fix.
| Operation | Cost |
|---|---|
| Insert | O(1) average |
| Lookup by key | O(1) average |
| Delete | O(1) average |
| Iterate in sorted order | Not supported |
The trade-off is memory and ordering. A hash map uses more memory than an array of the same elements, and it has no concept of order — iteration order is an implementation detail you should not rely on.
Use hash maps when you look up by key, count occurrences, deduplicate, group, or cache.
Sets: membership without values
A set is a hash map without values. It answers one question fast: is this thing in here?
const allowed = new Set(['read', 'write']);
allowed.has('read'); // true — O(1)
Sets are the right tool for deduplication and membership tests, and they are the standard fix for the “linear scan inside a loop” pattern.
Stacks: last in, first out
A stack supports two operations: push and pop, both O(1). The last item pushed is the first popped.
const history = [];
history.push('typed a');
history.push('typed b');
history.pop(); // 'typed b'
Stacks appear wherever you need to remember where you came from:
- Undo/redo — each action is pushed; undo pops.
- Function calls — the call stack is literally a stack.
- Parsing — matching brackets, evaluating expressions.
- Depth-first traversal — the recursive form uses the call stack; the iterative form uses an explicit one.
Queues: first in, first out
A queue adds at one end and removes from the other, both O(1) with the right implementation.
const queue = [];
queue.push('job-1');
queue.push('job-2');
queue.shift(); // 'job-1'
Note that shift() on a plain array is O(n) because it reindexes everything. For real queues, use a linked list or a deque, or in JavaScript a Map-based queue or an index pointer.
Queues appear in:
- Task scheduling — background jobs processed in order.
- Breadth-first traversal — visit all neighbours before going deeper.
- Rate limiting — a sliding window of recent requests.
- Message passing — producer/consumer pipelines.
Trees: hierarchy and ordered search
A tree is a set of nodes where each node has children and exactly one parent (except the root). A binary search tree keeps the invariant that everything left of a node is smaller and everything right is larger, which gives O(log n) search when the tree is balanced.
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
Trees model genuinely hierarchical data: file systems, the DOM, JSON documents, organisation charts, category taxonomies. They are also the basis of database indexes — a B-tree is why a WHERE id = 5 query does not scan the whole table.
The catch is balance. Insert sorted data into a naive binary search tree and it degenerates into a linked list with O(n) search. That is why production implementations use self-balancing variants like red-black trees or B-trees.
Heaps: the priority queue
A heap is a tree with one guarantee: the smallest (or largest) element is always at the root. It gives O(1) access to the extreme value and O(log n) insertion and removal.
Heaps are what you reach for when you need to repeatedly get the “next most important” item:
- Task schedulers — always run the highest-priority job.
- Dijkstra’s algorithm — always expand the nearest unvisited node.
- Top-k problems — keep a heap of size k while streaming.
- Event simulation — process events in timestamp order.
Graphs: relationships
A graph is a set of nodes connected by edges, with no hierarchy implied. Social networks, road maps, dependency trees, and state machines are all graphs.
const graph = new Map([
['A', ['B', 'C']],
['B', ['D']],
['C', ['D']],
['D', []],
]);
Graphs are usually stored as an adjacency list (a map from node to neighbours) or an adjacency matrix (a 2D grid of booleans). The list is better for sparse graphs, which is most real ones.
Traversal is either depth-first (a stack) or breadth-first (a queue), and the choice matters: BFS finds shortest paths in unweighted graphs, DFS is better for cycle detection and topological sorting.
Choosing between them
| You need to… | Use |
|---|---|
| Access by position | Array |
| Look up by key | Hash map |
| Check membership | Set |
| Undo the last action | Stack |
| Process in arrival order | Queue |
| Model hierarchy | Tree |
| Always get the min/max | Heap |
| Model relationships | Graph |
The pattern in that table is that the structure follows the operation. If you can name the operation your code performs most, the structure usually names itself.
A worked example
Suppose you are building a feature that finds the three most frequent words in a document.
The naive approach scans the word list for each candidate word, which is O(n²). The right approach uses two structures:
function topThree(words) {
const counts = new Map(); // hash map: O(n) counting
for (const w of words) counts.set(w, (counts.get(w) ?? 0) + 1);
const entries = [...counts.entries()];
entries.sort((a, b) => b[1] - a[1]); // O(k log k) where k = distinct words
return entries.slice(0, 3).map(([w]) => w);
}
A hash map for the counting, then a sort over the distinct keys. If the document were a stream too large to hold, you would swap the sort for a min-heap of size three, giving O(n log 3) — effectively O(n).
That is the whole skill: recognise the operation, pick the structure, and let the complexity fall out.
For the notation behind these costs, see Big-O notation explained, and for the memory side of the trade-off, time vs space complexity. If you are preparing for interviews, debugging strategies that work covers the reasoning that matters more than memorised answers.
Quotable summary
A data structure organises data so that the operations you need most are cheap. Arrays give O(1) indexed access and O(n) insertion in the middle. Hash maps and sets give O(1) average lookup by key or membership, at the cost of ordering and memory. Stacks are last-in-first-out and power undo, parsing, and depth-first traversal. Queues are first-in-first-out and power scheduling and breadth-first traversal. Trees model hierarchy and give O(log n) search when balanced. Heaps give O(1) access to the minimum or maximum. Graphs model arbitrary relationships. The correct choice is determined by which operations your problem performs most often, not by which structure is fastest in the abstract.