Graph

A set of vertices connected by edges, stored as an adjacency list or matrix: the structure behind maps, networks, dependencies and recommendations.

Description

A graph is a set of vertices (or nodes) connected by edges. It models anything with relationships: cities and roads, people and friendships, services and the calls between them, tasks and their dependencies, web pages and links.

Graphs come in a few flavors. In an undirected graph an edge goes both ways, like a friendship. In a directed graph it has a direction, like a dependency or a one-way street. A weighted graph attaches a number to each edge, such as a distance or a cost.

There are two common ways to store a graph. An adjacency list keeps, for each vertex, a list of its neighbors. It uses memory proportional to the number of edges, and iterating a vertex's neighbors is fast. An adjacency matrix is a V × V grid where cell (i, j) holds the edge between i and j. It answers "is there an edge?" in O(1), but uses V² memory even when there are few edges.

Most real graphs are sparse, with far fewer edges than V², so adjacency lists are the usual choice. Algorithms such as breadth-first search, depth-first search and Dijkstra's shortest path all work by walking these neighbor lists.

How it works

42581023ABCDEF

A weighted, undirected graph: six cities and the roads between them

  1. A — B (weight 4)
  2. A — C (weight 2)
  3. B — D (weight 5)
  4. C — D (weight 8)
  5. C — E (weight 10)
  6. D — F (weight 2)
  7. E — F (weight 3)
A weighted, undirected graph: six cities and the roads between them
AB (4)C (2)BA (4)D (5)CA (2)D (8)E (10)DB (5)C (8)F (2)EC (10)F (3)FD (2)E (3)
The same graph as an adjacency list
AA042000BB400500CC2008100DD058002EE0010003FF000230
And as an adjacency matrix

Complexity

OperationAverageWorst
Add vertexAdjacency matrix: O(V²) to grow the grid.O(1)O(1)
Add edgeO(1)O(1)
Check if an edge existsAdjacency matrix: O(1).O(degree)O(V)
Iterate a vertex's neighborsAdjacency matrix: always O(V).O(degree)O(V)
Traverse the whole graph (BFS / DFS)Adjacency matrix: O(V²).O(V + E)O(V + E)

Space: O(V + E) for an adjacency list; O(V²) for an adjacency matrix

V is the number of vertices and E the number of edges. For sparse graphs, E is close to V, so adjacency lists are far smaller and faster to traverse. Matrices pay off for dense graphs and for algorithms that check many vertex pairs.

TypeScript implementation

A weighted graph stored as an adjacency list in a Map, supporting directed and undirected edges.

graph.ts
// A weighted graph stored as an adjacency list: each vertex maps to its
// neighbors and the weight of the edge to each.

export class Graph {
  private adj = new Map<string, Map<string, number>>();
  private directed: boolean;

  constructor(directed = false) {
    this.directed = directed;
  }

  addVertex(v: string): void {
    if (!this.adj.has(v)) this.adj.set(v, new Map());
  }

  addEdge(from: string, to: string, weight = 1): void {
    this.addVertex(from);
    this.addVertex(to);
    this.adj.get(from)!.set(to, weight);
    if (!this.directed) this.adj.get(to)!.set(from, weight); // both directions
  }

  hasEdge(from: string, to: string): boolean {
    return this.adj.get(from)?.has(to) ?? false;
  }

  neighbors(v: string): [string, number][] {
    return [...(this.adj.get(v) ?? [])].sort(([a], [b]) => a.localeCompare(b));
  }

  get vertexCount(): number {
    return this.adj.size;
  }

  get edgeCount(): number {
    let n = 0;
    for (const edges of this.adj.values()) n += edges.size;
    return this.directed ? n : n / 2;
  }

  degree(v: string): number {
    return this.adj.get(v)?.size ?? 0;
  }
}

export function demo(): string[] {
  const roads = new Graph();
  for (const [a, b, km] of [["A", "B", 4], ["A", "C", 2], ["B", "D", 5], ["C", "D", 8], ["C", "E", 10], ["D", "F", 2], ["E", "F", 3]] as const) {
    roads.addEdge(a, b, km);
  }
  return [
    `${roads.vertexCount} vertices, ${roads.edgeCount} edges`,
    `C's neighbors: ${roads.neighbors("C").map(([v, w]) => `${v} (${w} km)`).join(", ")}`,
    `edge D–B exists (undirected): ${roads.hasEdge("D", "B")}`,
    `degree of A: ${roads.degree("A")}, of D: ${roads.degree("D")}`,
  ];
}

When to use it

Use it when

  • Your data is about relationships: networks, maps, dependencies, workflows, social connections.
  • You need paths, reachability, ordering by dependencies, or clusters.
  • Use an adjacency list for most graphs; use a matrix for small or dense graphs where you check edges between many pairs.

Avoid it when

  • The relationships form a strict hierarchy with one parent each: a tree is simpler.
  • You only need key lookups: a hash table is enough.
  • The graph is huge and persistent, queried by many services: consider a graph database rather than an in-memory structure.

Pitfalls

  • Forgetting the reverse edge in an undirected graph, so traversals miss half the connections.
  • Cycles in traversals without a visited set, leading to infinite loops.
  • Using a matrix for a sparse graph, wasting O(V²) memory: a million vertices would need a trillion cells.
  • Recursion depth in depth-first search on long paths, which can overflow the call stack. Use an explicit stack.
  • Mixing up directed and undirected semantics, especially when loading edges from data.

Alternatives

Union-find

Choose it when you only need to know which vertices are connected, as edges are added.

Tree

Choose it when every node has exactly one parent, such as a file system or an org chart.

Graph database

Choose it when the graph is large, persistent and queried by many users, for example with Neo4j or Amazon Neptune.