FreeLesson 11.1Beginner2 min readUpdated 30 October 2026
The pattern: graphs
Master graph representations, topological sorting, bipartite 2-coloring, Union-Find (Disjoint Set Union), and Dijkstra shortest paths.
A graph G = (V, E) is a set of vertices (nodes) and edges (connections). Graphs model networks, dependencies, social connections, and maps.
In coding interviews, graph problems generally test four dominant paradigms:
011. Graph representations
- Adjacency list (
List<List<Integer>>): The default representation. Space isO(V + E). Best for sparse graphs. - Adjacency matrix (
int[][]): Useful for dense graphs or when edge lookup must beO(1). Space isO(V^2). - In-degrees & Out-degrees (
int[] score): Many directed graph problems (like Find the Town Judge or Kahn's algorithm) boil down to counting incoming and outgoing edges per node.
022. Topological sort (DAG ordering)
Used when items have prerequisite dependencies.
- Kahn's algorithm (BFS): Track in-degrees. Enqueue all nodes with in-degree 0. As nodes are processed, decrement neighbor in-degrees; enqueue neighbors whose in-degree becomes 0.
- If
processedCount == V, the graph has a valid linear ordering and no directed cycles.
033. Bipartite graphs & 2-Coloring
A graph is bipartite if its vertices can be partitioned into two independent sets such that no two adjacent vertices share the same set.
- Use BFS or DFS to color vertices with
1and-1. - If you ever encounter an adjacent vertex that already shares the current vertex's color, the graph contains an odd-length cycle and is not bipartite.
044. Union-Find (Disjoint Set Union - DSU)
Essential for dynamically grouping connected components and cycle detection in undirected graphs:
text
class UnionFind:
int[] parent;
find(i):
if parent[i] == i: return i
return parent[i] = find(parent[i]) # path compression
union(i, j):
rootI = find(i); rootJ = find(j)
if rootI != rootJ: parent[rootI] = rootJ055. Dijkstra's algorithm (Weighted shortest paths)
When edges have non-negative weights, Dijkstra finds the shortest path from a start vertex to all others:
- Maintain a min-heap (PriorityQueue) of
(distance, vertex). - Pop the smallest tentative distance; relax outgoing edges
dist[u] + weight < dist[v].