Graphs
- Choose a graph representation (adjacency list, matrix, edge list, implicit grid) for a given problem and size
- Apply BFS for unweighted shortest paths, DFS for exploration and cycle detection, and know their O(V + E) costs
- Produce a topological order with Kahn's algorithm and use it for dependency resolution, build systems and saga steps
- Implement union-find with path compression and union by size, and Dijkstra with
container/heap - Recognize when weights are negative and reach for Bellman-Ford (e.g. FX arbitrage detection)
TL;DR
- Most graph problems are BFS or DFS with a visited set. Both are O(V + E). BFS finds shortest paths when every edge costs the same; DFS explores, detects cycles and orders dependencies.
- Mark visited when you enqueue, not when you dequeue — otherwise the same node enters the queue many times.
- Topological sort (Kahn): repeatedly take nodes with in-degree 0. If you cannot take all nodes, there is a cycle. Processing level by level gives the steps that can run in parallel.
- Union-find answers "are these connected?" under edge additions in near-O(1) amortized time — components, redundant edges, fraud rings.
- Dijkstra = BFS with a min-heap over distance; requires non-negative weights; O((V + E) log V).
- Negative weights → Bellman-Ford (O(V·E)); a negative cycle detected with
−log(rate)weights is an FX arbitrage loop. - Grids are graphs: cells are nodes, the four directions are edges, the grid itself can be the visited set.
When to reach for it
- Entities plus relationships: accounts and transfers, users and devices, services and calls, products and "bought together".
- "Can X reach Y?", "how many groups/islands/components?" → BFS/DFS or union-find.
- "Minimum number of steps/moves/transformations" with uniform cost → BFS (often over an implicit graph of states, e.g. Word Ladder).
- "Order tasks given prerequisites", "is there a circular dependency?" → topological sort / cycle detection.
- "Cheapest / fastest / minimum total weight path" → Dijkstra (non-negative) or Bellman-Ford (negative weights, at most k edges).
- "Merge accounts that share an email", "edges arrive one by one, when does it become connected?" → union-find.
- A 2D matrix with "neighbouring cells" → grid BFS/DFS.
Core concepts
Representations
| Representation | Space | Check edge (u, v) | Iterate neighbours | Choose when |
|---|---|---|---|---|
Adjacency list [][]int | O(V + E) | O(deg u) | O(deg u) | Default; sparse graphs (most real graphs) |
Adjacency map map[string][]string | O(V + E) | O(deg u) | O(deg u) | Node IDs are strings (services, accounts) |
Adjacency matrix [][]bool | O(V²) | O(1) | O(V) | Dense graphs, small V (≤ a few thousand), Floyd–Warshall |
Edge list [][3]int | O(E) | O(E) | O(E) | Kruskal, Bellman-Ford, input format |
| Implicit (grid, state space) | O(1) to describe | computed | computed | Grids, puzzles, Word Ladder |
// buildGraph turns a directed edge list into an adjacency list.
// For an undirected graph, append both directions.
func buildGraph(n int, edges [][2]int) [][]int {
adj := make([][]int, n)
for _, e := range edges {
adj[e[0]] = append(adj[e[0]], e[1])
}
return adj
}
BFS: shortest paths in unweighted graphs
BFS visits nodes in order of distance from the source, so the first time it reaches a node is via a shortest path.
// bfsDistances returns the edge count from src to every node (-1 if unreachable).
func bfsDistances(adj [][]int, src int) []int {
dist := make([]int, len(adj))
for i := range dist {
dist[i] = -1
}
dist[src] = 0
queue := []int{src}
for len(queue) > 0 {
u := queue[0]
queue = queue[1:]
for _, v := range adj[u] {
if dist[v] == -1 { // mark when enqueuing
dist[v] = dist[u] + 1
queue = append(queue, v)
}
}
}
return dist
}
Multi-source BFS starts with several nodes in the queue at distance 0 — "distance from each cell to the nearest store", "minutes until all oranges rot" (LeetCode 994).
DFS and cycle detection
DFS goes deep first, recursively or with an explicit stack. For directed graphs, detect cycles with three colours: white (unvisited), gray (on the current path), black (done). An edge into a gray node is a back edge — a cycle. For undirected graphs, an edge to a visited node that is not your parent is a cycle (or use union-find).
// hasCycle reports whether a directed graph contains a cycle.
func hasCycle(adj [][]int) bool {
const (
white = iota // unvisited
gray // on the current DFS path
black // fully explored
)
color := make([]int, len(adj))
var visit func(u int) bool
visit = func(u int) bool {
color[u] = gray
for _, v := range adj[u] {
if color[v] == gray {
return true // back edge: v is an ancestor of u
}
if color[v] == white && visit(v) {
return true
}
}
color[u] = black
return false
}
for u := range adj {
if color[u] == white && visit(u) {
return true
}
}
return false
}
The outer loop matters: graphs can be disconnected, and starting only at node 0 misses cycles elsewhere.
Topological sort: dependency resolution
A topological order lists every node before the nodes that depend on it; it exists exactly when the graph is a DAG. Kahn's algorithm: count in-degrees, queue every node with in-degree 0, pop a node, append it to the order, decrement its successors' in-degrees, queue those that reach 0. If the order is shorter than V, the leftover nodes are on or behind a cycle.
Where you meet it as an engineer:
- Build systems compile packages after their imports (the Go toolchain rejects import cycles outright), and Bazel/Make schedule targets the same way.
- Schema migrations, Terraform resources, Kubernetes operators, CI pipelines, Airflow DAGs — all execute dependency graphs.
- Saga orchestration: steps of a checkout workflow form a DAG; processing Kahn's queue level by level yields waves of steps that can run concurrently (Distributed Transactions: 2PC, TCC, Saga).
Kahn's levels here: Validate → Reserve, Fraud, Price (parallel) → Authorize → Create order → Confirmation, Shipment (parallel). If someone adds "Authorize payment must precede Fraud check", Kahn's algorithm stops with nodes left over — report the cycle at deploy time, not at 2 a.m.
Union-find (disjoint set union)
Each set is a tree identified by its root. Find walks to the root and compresses the path; Union attaches the smaller tree under the larger. Together they give an amortized cost of O(α(n)) per operation, where α (inverse Ackermann) is at most 4 for any practical n.
type DSU struct {
parent, size []int
}
func NewDSU(n int) *DSU {
d := &DSU{parent: make([]int, n), size: make([]int, n)}
for i := range n {
d.parent[i] = i
d.size[i] = 1
}
return d
}
func (d *DSU) Find(x int) int {
for d.parent[x] != x {
d.parent[x] = d.parent[d.parent[x]] // path halving
x = d.parent[x]
}
return x
}
// Union merges the sets containing a and b; it returns false if already merged.
func (d *DSU) Union(a, b int) bool {
ra, rb := d.Find(a), d.Find(b)
if ra == rb {
return false
}
if d.size[ra] < d.size[rb] {
ra, rb = rb, ra
}
d.parent[rb] = ra // attach the smaller tree under the larger
d.size[ra] += d.size[rb]
return true
}
Fraud lens: link accounts that share a device fingerprint, card, phone or payout IBAN; each resulting set is a candidate fraud ring, and its size is a risk feature (Fraud & Risk Systems). Union-find also powers Kruskal's minimum spanning tree.
Weighted shortest paths
- Dijkstra: a min-heap of
(distance, node); pop the closest unsettled node and relax its edges. Correct only for non-negative weights, because it assumes a settled node can never get cheaper. With a binary heap and lazy deletion: O((V + E) log V). See Problem 3. - Bellman-Ford: relax every edge V − 1 times; if anything still improves, a negative cycle exists. O(V·E). Also handles "at most k edges" constraints (Cheapest Flights Within K Stops, LeetCode 787).
- Floyd–Warshall: all-pairs shortest paths in O(V³) — fine for a few hundred nodes.
- A*: Dijkstra plus an admissible heuristic (e.g. straight-line distance) — routing and maps.
- 0-1 BFS: weights are only 0 or 1 → a deque instead of a heap, O(V + E).
A bank-flavoured Bellman-Ford: currency arbitrage. If one unit of currency i buys rate[i][j] units of j, a cycle whose rate product exceeds 1 makes money. Taking weights −log(rate) turns products into sums and "product > 1" into "sum < 0" — a negative cycle.
// hasArbitrage reports whether a conversion cycle multiplies money.
// rate[i][j] is how many units of j one unit of i buys; 0 means no market.
func hasArbitrage(rate [][]float64) bool {
n := len(rate)
dist := make([]float64, n) // zeros: as if a virtual source reached every currency
for range n - 1 {
for i := range n {
for j := range n {
if rate[i][j] > 0 {
dist[j] = min(dist[j], dist[i]-math.Log(rate[i][j]))
}
}
}
}
for i := range n {
for j := range n {
if rate[i][j] > 0 && dist[i]-math.Log(rate[i][j]) < dist[j]-1e-12 {
return true // still improvable after n-1 rounds: negative cycle
}
}
}
return false
}
Real FX desks also subtract spreads and fees, and quoted opportunities vanish within milliseconds; treat this as a detection and monitoring tool (e.g. catching inconsistent rate feeds), not a trading strategy.
Grid problems
Treat each cell as a node and the four (or eight) neighbours as edges. Keep a dirs array, check bounds before indexing, and use the grid itself (overwrite visited land) or a [][]bool as the visited set. Prefer iterative BFS for big grids: a 1000 × 1000 grid can produce a million-deep recursion with DFS.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| BFS | Shortest path with uniform weights, level structure | Queue can hold a whole level (wide graphs) | Minimum steps, levels, multi-source distance |
| DFS | Low memory on wide graphs, natural for cycles and ordering | Recursion depth, no shortest-path guarantee | Exploration, cycle detection, components, backtracking |
| Topological sort (Kahn) | Detects cycles, yields parallel waves | DAGs only | Dependencies, build order, workflow steps |
| Union-find | Near-O(1) connectivity under edge additions | No deletions, no paths | Dynamic connectivity, Kruskal, grouping |
| Dijkstra | O((V+E) log V), fast in practice | Non-negative weights only | Weighted shortest paths, routing, latency graphs |
| Bellman-Ford | Negative weights, detects negative cycles, hop limits | O(V·E) | Arbitrage, k-stop constraints |
| Floyd–Warshall | All pairs, simple triple loop | O(V³) time, O(V²) space | Small dense graphs |
In practice
Problem 1 — Number of Islands (LeetCode 200)
Problem. Count connected groups of '1' cells in a grid (4-directional adjacency).
Approach. Scan every cell; each unvisited land cell starts a BFS that sinks its whole island. Sinking on enqueue keeps the queue free of duplicates. (Ask before mutating the input; otherwise copy it or use a visited matrix.)
func numIslands(grid [][]byte) int {
if len(grid) == 0 {
return 0
}
rows, cols := len(grid), len(grid[0])
dirs := [4][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
islands := 0
for r := range rows {
for c := range cols {
if grid[r][c] != '1' {
continue
}
islands++
grid[r][c] = '0' // the grid doubles as the visited set
queue := [][2]int{{r, c}}
for len(queue) > 0 {
cell := queue[0]
queue = queue[1:]
for _, d := range dirs {
nr, nc := cell[0]+d[0], cell[1]+d[1]
if nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == '1' {
grid[nr][nc] = '0'
queue = append(queue, [2]int{nr, nc})
}
}
}
}
}
return islands
}
Complexity. O(R·C) time, O(min(R, C)) to O(R·C) queue space. Union-find is the alternative when land cells are added over time (Number of Islands II, LeetCode 305).
Problem 2 — Course Schedule II (LeetCode 210)
Problem. Given n courses and pairs [course, prerequisite], return an order that completes all courses, or nothing if impossible.
Approach. Kahn's algorithm. Edges go from prerequisite to course. An order shorter than n means a cycle.
// findOrder returns a valid order, or nil if the prerequisites contain a cycle.
func findOrder(numCourses int, prerequisites [][2]int) []int {
adj := make([][]int, numCourses)
indegree := make([]int, numCourses)
for _, p := range prerequisites {
course, pre := p[0], p[1]
adj[pre] = append(adj[pre], course)
indegree[course]++
}
var queue []int
for c, d := range indegree {
if d == 0 {
queue = append(queue, c)
}
}
order := make([]int, 0, numCourses)
for len(queue) > 0 {
u := queue[0]
queue = queue[1:]
order = append(order, u)
for _, v := range adj[u] {
indegree[v]--
if indegree[v] == 0 {
queue = append(queue, v)
}
}
}
if len(order) < numCourses {
return nil // remaining nodes are on or behind a cycle
}
return order
}
Complexity. O(V + E) time and space. To get parallel waves, process the queue one level at a time (for range len(queue)), as in level-order traversal.
Problem 3 — Network Delay Time (LeetCode 743)
Problem. A signal starts at node k in a directed weighted graph of n nodes (1-indexed). Return the time until every node has received it, or −1 if some never does.
Approach. Dijkstra from k with container/heap and lazy deletion (skip popped entries whose distance is outdated). The answer is the largest shortest distance.
type edge struct{ to, w int }
type item struct{ node, dist int }
type minDist []item
func (h minDist) Len() int { return len(h) }
func (h minDist) Less(i, j int) bool { return h[i].dist < h[j].dist }
func (h minDist) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *minDist) Push(x any) { *h = append(*h, x.(item)) }
func (h *minDist) Pop() any {
old := *h
it := old[len(old)-1]
*h = old[:len(old)-1]
return it
}
// networkDelayTime: times[i] = (from, to, weight), nodes are 1..n.
func networkDelayTime(times [][3]int, n, k int) int {
adj := make([][]edge, n+1)
for _, t := range times {
adj[t[0]] = append(adj[t[0]], edge{to: t[1], w: t[2]})
}
dist := make([]int, n+1)
for i := range dist {
dist[i] = math.MaxInt
}
dist[k] = 0
h := &minDist{{node: k, dist: 0}}
for h.Len() > 0 {
cur := heap.Pop(h).(item)
if cur.dist > dist[cur.node] {
continue // stale entry
}
for _, e := range adj[cur.node] {
if nd := cur.dist + e.w; nd < dist[e.to] {
dist[e.to] = nd
heap.Push(h, item{node: e.to, dist: nd})
}
}
}
worst := 0
for _, d := range dist[1:] {
if d == math.MaxInt {
return -1
}
worst = max(worst, d)
}
return worst
}
Complexity. O((V + E) log V) time (the heap can hold O(E) entries, and log E = O(log V)), O(V + E) space.
Problem 4 — Redundant Connection (LeetCode 684)
Problem. A tree on nodes 1..n had one extra edge added. Return the edge that can be removed to restore a tree (the last such edge in input order).
Approach. Union-find over the edges in order; the first edge whose endpoints are already connected closes a cycle.
func findRedundantConnection(edges [][2]int) [2]int {
d := NewDSU(len(edges) + 1) // n nodes, n edges, 1-indexed
for _, e := range edges {
if !d.Union(e[0], e[1]) {
return e // endpoints already connected: this edge closes the cycle
}
}
return [2]int{}
}
Complexity. O(E·α(V)) ≈ O(E) time, O(V) space. Accounts Merge (LeetCode 721) is the same tool with emails mapped to integer IDs.
Practice list
- Easy: Flood Fill (733), Find if Path Exists in Graph (1971), Find the Town Judge (997)
- Medium: Number of Islands (200), Clone Graph (133), Course Schedule (207), Course Schedule II (210), Rotting Oranges (994), Pacific Atlantic Water Flow (417), Redundant Connection (684), Accounts Merge (721), Network Delay Time (743), Cheapest Flights Within K Stops (787)
- Hard: Word Ladder (127), Alien Dictionary (269), Swim in Rising Water (778)
Common pitfalls
- Marking visited on dequeue instead of enqueue: nodes enter the queue many times. Symptom: time limit exceeded on dense graphs, or memory blow-up.
- Forgetting disconnected components — starting a DFS only from node 0.
- Adding undirected edges in one direction only.
- Dijkstra with negative weights silently returns wrong answers; there is no error.
- Deep recursive DFS on large grids — a million frames. Go grows stacks, but the memory and copying cost are real; use BFS or an explicit stack.
- Off-by-one with 1-indexed nodes (allocate n + 1).
- Nondeterministic order when the graph is a
map[string][]string: topological orders change between runs. Sort neighbours if output must be reproducible (build plans, migration order). - Topological sort without a cycle check — Kahn's algorithm quietly returns a partial order.
Interview angle
- Clarify first: directed or undirected? weighted? negative weights? size of V and E? connected? can there be cycles or self-loops?
- State the representation and complexity: "adjacency list, BFS, O(V + E)".
- For grids, say whether you mutate the input and why.
- System-design tie-ins interviewers love: dependency resolution in deployments and sagas, detecting circular service dependencies, fraud-ring detection with connected components, routing and ETA (Dijkstra/A*), "customers who bought X" as a bipartite graph, and when a graph database is (and is not) warranted.
- Follow-ups: "Return the path, not just the distance" (store parents), "Graph does not fit in memory" (partition, BFS in rounds with a batch framework, or a graph store), "Edges arrive continuously" (union-find, incremental algorithms).
- Red flags: Dijkstra for negative weights, no visited set, or not knowing that BFS gives shortest paths only for uniform weights.
Self-check
1. Why does BFS give shortest paths in an unweighted graph but not in a weighted one?
BFS explores nodes in order of edge count from the source, so the first time it reaches a node it has used the fewest edges. With weights, a path with more edges can be cheaper, and BFS's order says nothing about total weight. Dijkstra fixes this by ordering exploration by accumulated distance with a priority queue.
2. How does Kahn's algorithm detect a cycle?
Nodes on a cycle never reach in-degree 0, because each has an incoming edge from another cycle node that is never removed. So the algorithm finishes with fewer than V nodes in the output; the leftovers are the cycle nodes and everything downstream of them.
3. In three-colour DFS, why does an edge to a gray node mean a cycle but an edge to a black node does not?
Gray nodes are on the current recursion path, so an edge to one points back to an ancestor — a cycle. Black nodes are fully explored and not on the current path; reaching one just means two paths converge (a DAG "diamond"), which is not a cycle.
4. Why does Dijkstra fail with negative weights?
It permanently settles the closest unsettled node, assuming no later path can be cheaper because every additional edge adds non-negative cost. A negative edge discovered later can make a settled node cheaper, but Dijkstra never revisits it. Bellman-Ford relaxes all edges repeatedly and handles negative weights (and detects negative cycles).
5. What do path compression and union by size each contribute to union-find?
Union by size keeps trees shallow (height O(log n)) by attaching the smaller tree under the larger. Path compression flattens paths during Find, so subsequent finds on those nodes are nearly direct. Together they yield amortized O(α(n)) per operation, effectively constant.
6. Scenario: a deployment tool must start 40 microservices respecting declared dependencies, as fast as possible. Design the algorithm.
Build a DAG (edge from dependency to dependent), run Kahn's algorithm level by level: all services with in-degree 0 start in parallel; when one becomes healthy, decrement its dependents and start those reaching 0. If services remain with non-zero in-degree, report the cycle (run DFS on the leftovers to print it). Add timeouts and failure propagation: if a dependency fails, mark its descendants as blocked.
7. Scenario: the fraud team wants to group 50M accounts that share devices, cards or phone numbers. Which algorithm and what are the practical issues?
Connected components via union-find: map each account and each shared attribute to integer IDs and union account with attribute. Practical issues: "super nodes" (a shared public Wi-Fi IP or a payment aggregator's card links millions of accounts — exclude or cap high-degree attributes), the data does not fit one process (run components in a batch framework such as Spark's GraphX/GraphFrames, or partitioned union-find), and incremental updates as new links arrive.
Exercise
Build a workflow package for saga orchestration:
- Input: steps with names and
dependsOnlists. Output: execution waves (Kahn by levels), with steps inside each wave sorted by name for determinism. - On a cycle, return an error that names one concrete cycle (find it with three-colour DFS on the leftover nodes, recording the gray path).
- Add
Downstream(step)returning every step that must be skipped or compensated ifstepfails (BFS on the graph). - Bonus: run each wave concurrently with
errgroupand a per-step timeout.
Done when table-driven tests cover a diamond DAG, a disconnected graph, a self-loop and a three-node cycle, and the cycle error message reads like cycle: authorize -> fraud-check -> authorize.
Further reading
- Introduction to Algorithms (CLRS) — elementary graph algorithms, minimum spanning trees, single-source shortest paths, disjoint sets
- Steven Skiena, The Algorithm Design Manual — graph traversal and weighted graph chapters (with "war stories")
- Sedgewick & Wayne, Algorithms, 4th ed. — graphs chapter
- E. W. Dijkstra, "A Note on Two Problems in Connexion with Graphs" (1959); A. B. Kahn, "Topological Sorting of Large Networks" (1962)
- Robert Tarjan, "Efficiency of a Good But Not Linear Set Union Algorithm" (1975)
Related
- Heaps & Priority Queues — the heap inside Dijkstra.
- Trees & BSTs — trees are connected acyclic graphs.
- Dynamic Programming — DP over a DAG; Bellman-Ford is DP.
- Distributed Transactions: 2PC, TCC, Saga — step dependencies and compensation.
- Fraud & Risk Systems — graph features and fraud rings.
- Microservices Patterns — avoiding cyclic service dependencies.
- Order Management & State Machines — state machines are directed graphs.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).