Skip to content
Velloreth
Programming 7 min read

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

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
OperationCost
Access by indexO(1)
AppendO(1) amortised
Insert/remove at front or middleO(n)
Search by valueO(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.

OperationCost
InsertO(1) average
Lookup by keyO(1) average
DeleteO(1) average
Iterate in sorted orderNot 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.

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 positionArray
Look up by keyHash map
Check membershipSet
Undo the last actionStack
Process in arrival orderQueue
Model hierarchyTree
Always get the min/maxHeap
Model relationshipsGraph

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.

Frequently asked questions

What is a data structure in simple terms?
A data structure is a way of organising data in memory so that the operations you need are efficient. An array keeps items in order for fast indexing, a hash map keeps them by key for fast lookup, and a tree keeps them sorted for fast range queries.
Which data structure should I learn first?
Arrays and hash maps, because they cover the majority of everyday programming. Once those are comfortable, learn stacks and queues, then trees and heaps, then graphs.
When should I use a hash map instead of an array?
Use a hash map when you need to look things up by a key rather than by position, or when you need to check membership quickly. Use an array when order matters and you access items by index or iterate over all of them.
What is the difference between a stack and a queue?
A stack is last-in-first-out: the most recently added item is removed first, like a pile of plates. A queue is first-in-first-out: the oldest item is removed first, like a line at a checkout.
Do I need to implement data structures myself?
Almost never in production code, because every mainstream language ships them in its standard library. You should understand how they work so you can choose correctly and reason about performance, but you should use the built-in versions.
What is the most commonly used data structure in real applications?
The hash map, usually in the form of an object, dictionary, or map type. It underpins caching, counting, deduplication, grouping, and lookup tables, which is most of what application code does.