Graphs

Vertices and edges — the most general structure. Terminology, representations, and how to choose between them.

Intermediate 4 min readLesson 12 of 16 Interview Q&A

A graph G = (V, E) is a set of vertices (nodes) and edges connecting pairs of them. Trees and linked lists are special cases. Road maps, social networks, the web, package dependencies, network routers, state machines and course prerequisites are all graphs.

ABCDE
An undirected graph with 5 vertices and 6 edges.

Vocabulary

TermMeaning
Directed / undirectedEdges have a direction (A → B) or not (A — B)
WeightedEdges carry a cost: distance, latency, capacity
DegreeNumber of edges at a vertex (in-degree / out-degree if directed)
PathA sequence of vertices joined by edges
CycleA path that returns to its start
ConnectedEvery vertex reachable from every other (undirected)
Strongly connectedEvery vertex reachable from every other along directions
DAGDirected acyclic graph — dependencies, schedules, build systems
Sparse / denseE ≈ V vs E ≈ V²
42158SABT
A weighted directed graph. Shortest S→T is S→B→A→T with cost 8.

Representations

Adjacency list

For each vertex, a list of its neighbours. The default choice — most real graphs are sparse.

Adjacency matrix

A V × V grid where m[u][v] = 1 (or the weight) if there's an edge. O(1) edge lookup, but O(V²) memory.

Edge list

Just a list of (u, v, w) tuples. Natural for Kruskal's MST and Bellman-Ford.

Adjacency listAdjacency matrixEdge list
MemoryO(V + E)O(V²)O(E)
Is (u, v) an edge?O(deg u)O(1)O(E)
Iterate neighbours of uO(deg u)O(V)O(E)
Iterate all edgesO(V + E)O(V²)O(E)
Best forSparse graphs (most)Dense graphs, Floyd-WarshallSorting edges
// Build an adjacency list from an edge list
int n = 5;
int[][] edges = {{0,1},{0,2},{1,2},{1,3},{2,4},{3,4}};
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
for (int[] e : edges) {
    adj.get(e[0]).add(e[1]);
    adj.get(e[1]).add(e[0]);      // omit for directed graphs
}

// Weighted: store pairs (neighbour, weight)
List<List<int[]>> wadj = new ArrayList<>();

// Adjacency matrix
boolean[][] m = new boolean[n][n];
for (int[] e : edges) m[e[0]][e[1]] = m[e[1]][e[0]] = true;

Traversal

The two fundamental ways to explore a graph — breadth-first (queue) and depth-first (stack/recursion) — both run in O(V + E). Always keep a visited set: unlike trees, graphs have cycles.

InteractiveBreadth-first search
ABCDEFGH
queue (front → back)
A
visited order
A
currentin queuevisited / final
Enqueue start A, mark visited
1/17

The algorithm map

ProblemAlgorithmLesson
Reachability, connected componentsBFS / DFSGraph traversal
Shortest path, unweightedBFSGraph traversal
Shortest path, non-negative weightsDijkstraShortest paths
Shortest path, negative weightsBellman-FordShortest paths
All-pairs shortest pathsFloyd-WarshallShortest paths
Cheapest way to connect all nodesKruskal / PrimMST
Order tasks with dependenciesTopological sortTopological sort & SCC
Dynamic connectivityUnion-FindUnion-Find
Max flow / bipartite matchingFord-Fulkerson, Edmonds-KarpNetwork flow
Key takeaways
  • Graphs model relationships: V vertices, E edges, optionally directed and weighted.
  • Use adjacency lists by default: O(V + E) memory and fast neighbour iteration.
  • Traversal is O(V + E) and needs a visited set.
  • Recognise implicit graphs: grids, word ladders, state spaces.
Interview questions
QHow do you detect a cycle in a directed vs an undirected graph?medium

Undirected: DFS and report a cycle if you reach a visited vertex that isn't your parent (or use Union-Find: an edge joining two vertices already in the same set). Directed: DFS with three colours — white (unvisited), grey (on the current recursion stack), black (done); reaching a grey vertex means a back edge, i.e. a cycle. Kahn's topological sort also detects it: if not all vertices are output, there's a cycle.

QNumber of islands in a grid.medium

Treat land cells as vertices connected to their 4 land neighbours. For every unvisited land cell, increment the count and flood-fill (BFS/DFS) to mark its whole island. O(rows × cols).

QIs a graph bipartite?medium

Try to 2-colour it with BFS/DFS: colour the start 0, neighbours 1, and so on. If an edge ever joins two vertices of the same colour, it's not bipartite (equivalently, it has an odd cycle).