Skip to main content
Intermediate ~13 min read

Graph Representations

The most general structure in CS: vertices, edges, directed/weighted variants, and adjacency list vs matrix.

Prerequisites: Big O Notation & Time Complexity

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 / caseCostNotes
SpaceO(V + E)matrix: O(V²)
Neighbors of vO(degree(v))matrix: O(V), scan the row
Edge (u,v) exists?O(degree(u))matrix: O(1), its win
Add edgeO(1)append to both lists (undirected)
Best forsparse (real-world)matrix: dense or tiny graphs

Building graphs two ways

representations.js
// 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])

Check your understanding

  1. 1.A social network with 1M users, each averaging 150 friends. Which representation and why?
  2. 2.Course prerequisites ('take A before B') are best modeled as:
  3. 3.Why does every graph traversal algorithm need a 'visited' set?

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Play it

Maze Runner

Race your own path through a maze, then watch BFS find the provably shortest route, and DFS show why 'a path' …

Keep going