Graph Algorithms Checkpoint
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
This checkpoint mixes all five tools on plans, networks and routes. First decide which algorithm the clue points to, then write it.
Choose the algorithm from the clue
Read the problem for its key words. Rules like "A before B" mean a topological sort. Groups that merge or "are they connected" mean Union-Find. "Cheapest route" means Dijkstra when no cost is negative.
- Order with rules, or a cycle check on a directed graph: Kahn or DFS.
- Connected groups, or a loop in an undirected graph: Union-Find.
- Cheapest route from one start: BFS, Dijkstra or Bellman-Ford by weight type.
- Connect everything at the least cost: Kruskal or Prim.
Kahn with levels
Kahn's algorithm can also count rounds. A task that becomes ready after its slowest prerequisite sits one level higher. The largest level is the minimum number of rounds, if tasks in a round run in parallel.
level = [1] * nqueue = deque(i for i in range(n) if indeg[i] == 0)while queue: u = queue.popleft() for v in graph[u]: level[v] = max(level[v], level[u] + 1) indeg[v] -= 1 if indeg[v] == 0: queue.append(v)Example 1 · Minimum rounds for a plan
from collections import deque
n = 6rules = [(0, 2), (1, 2), (2, 3), (2, 4), (4, 5)]graph = [[] for _ in range(n)]indeg = [0] * nfor u, v in rules: graph[u].append(v) indeg[v] += 1level = [1] * nqueue = deque(i for i in range(n) if indeg[i] == 0)while queue: u = queue.popleft() for v in graph[u]: level[v] = max(level[v], level[u] + 1) indeg[v] -= 1 if indeg[v] == 0: queue.append(v)
print(max(level))4
What this code does
- Tasks 0 and 1 run in round 1, task 2 in round 2, tasks 3 and 4 in round 3, and task 5 in round 4.
- If Kahn stopped early, the rules would contain a cycle and no plan would exist.
This is still O(V + E). The answer is max(level).
Union-Find in weight order
Process roads from the cheapest. The moment two places become connected, the last road added is the cheapest "largest road" on any route between them. That is the bottleneck, and it needs only a sort and Union-Find.
for u, v, w in sorted(edges, key=lambda e: e[2]): ru, rv = find(parent, u), find(parent, v) if ru != rv: parent[ru] = rv if find(parent, 0) == find(parent, n - 1): print(w) breakExample 2 · Smallest road limit that connects two towns
def find(parent, x): while parent[x] != x: parent[x] = parent[parent[x]] x = parent[x] return x
n = 5edges = [(0, 1, 7), (1, 2, 3), (0, 2, 9), (2, 3, 5), (3, 4, 4), (1, 4, 12)]parent = list(range(n))for u, v, w in sorted(edges, key=lambda e: e[2]): ru, rv = find(parent, u), find(parent, v) if ru != rv: parent[ru] = rv if find(parent, 0) == find(parent, n - 1): print(w) break7
What this code does
- After roads 3, 4, 5 and 7 are added, towns 0 and 4 are connected. The largest road on that route is 7.
- The route 0 → 2 → 3 → 4 uses a road of 9, so its largest road is bigger than 7.
Example 3 · Time for a signal to reach every node
import heapq
def dijkstra(graph, start): dist = [float('inf')] * len(graph) dist[start] = 0 heap = [(0, start)] while heap: d, u = heapq.heappop(heap) if d > dist[u]: continue for v, w in graph[u]: if d + w < dist[v]: dist[v] = d + w heapq.heappush(heap, (d + w, v)) return dist
graph = [[(1, 2), (2, 4)], [(2, 1), (3, 7)], [(3, 3)], []]dist = dijkstra(graph, 0)print(max(dist) if max(dist) != float('inf') else -1)6
What this code does
- A signal travels along directed edges. The last node to receive it decides the total time.
- If any distance is infinity, some node is never reached and the answer is -1.
Sorting costs O(E log E). The loop adds almost O(E).
Module quiz
Questions from the whole module. Your first answer is your score.
Problems
Graded easy to hard, using everything from this module.
Try each one yourself first. Use the hint if you get stuck. Mark it as done when it works.
Exercise 1· Easy
Print a topological order from Kahn's algorithm for 4 nodes and edges (0,1), (0,2), (1,3), (2,3).
[0, 1, 2, 3]
Exercise 2· Easy
Print the number of connected components of 8 nodes with edges (0,1), (2,3), (3,4), (5,6) using Union-Find.
4
Exercise 3· Easy
Print the shortest distance from node 0 to node 4 for the undirected edges (0,1,2), (1,4,9), (0,2,3), (2,3,1), (3,4,2).
6
Exercise 4· Medium
Print True if the directed graph with edges (0,1), (1,2), (2,3), (3,1) has a cycle, otherwise False.
True
Exercise 5· Medium
Print the total weight of the minimum spanning tree for 5 nodes and edges (0,1,2), (0,2,3), (1,2,1), (1,3,4), (2,3,5), (3,4,2), (2,4,7).
9
Exercise 6· Medium
Print the Bellman-Ford distance from node 0 to node 3 for directed edges (0,1,5), (0,2,2), (2,1,-4), (1,3,3).
1
Exercise 7· Hard
Print the minimum number of rounds to finish 7 tasks with rules (0,3), (1,3), (3,4), (2,4), (4,5), (4,6) if tasks in a round run in parallel.
4
Exercise 8· Hard
Print the smallest possible largest road on any route from town 0 to town 5, for roads (0,1,4), (1,2,6), (2,5,3), (0,3,8), (3,5,5), (1,4,2), (4,5,9).
6
Interview questions
Questions interviewers ask on this topic.
Finish up
Mark complete & continue
Next: Must-do problems: Graph Algorithms