A graph is a set of vertices (nodes) connected by edges. That's it, and that generality is why graphs are everywhere: cities and roads, people and friendships, courses and prerequisites, web pages and links, states and moves in a puzzle. When a problem says "things and relationships between things", it's a graph problem, whether or not anyone draws it for you.
Choosing a representation is the first engineering decision. The adjacency list, for each vertex, a list of its neighbors, uses O(V + E) space and answers "who are v's neighbors?" in O(degree(v)); it's the default for sparse graphs (few edges), which is most real data. The adjacency matrix, a V×V boolean grid, uses O(V²) space but checks "are u and v connected?" in O(1) and suits tiny or dense graphs. Nothing about the algorithms changes; only the constants and memory do.
Adjacency list vs matrix (V vertices, E edges)
| Operation / case | Cost | Notes |
|---|---|---|
| Space | O(V + E) | matrix: O(V²) |
| Neighbors of v | O(degree(v)) | matrix: O(V), scan the row |
| Edge (u,v) exists? | O(degree(u)) | matrix: O(1), its win |
| Add edge | O(1) | append to both lists (undirected) |
| Best for | sparse (real-world) | matrix: dense or tiny graphs |
Building graphs two ways
// Edges as pairs, the input format you'll usually receive
const edges = [[0, 1], [0, 2], [1, 3], [2, 3]];
const n = 4;
// Adjacency list (undirected): O(V + E) space
const adj = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
adj[a].push(b);
adj[b].push(a); // remove this line for a DIRECTED graph
}
// Adjacency matrix: O(V²) space, O(1) edge checks
const matrix = Array.from({ length: n }, () => new Array(n).fill(false));
for (const [a, b] of edges) {
matrix[a][b] = true;
matrix[b][a] = true;
}
// Weighted graph? Store pairs: adj[a].push([b, weight])