Graph algorithms practice
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.
Synthesize shortest path, topological sorting, and spanning tree algorithms to solve complex interview graph challenges.
Choosing the right graph algorithm
Solving advanced graph problems begins with identifying the underlying algorithmic paradigm. If a problem asks for unweighted distances, apply BFS or multi-source BFS. When weights are 0 and 1, reach for 0-1 BFS with an ArrayDeque in linear time.
Example 1 · Number of Provinces Using Union-Find in Java
public class Main { static int find(int[] parent, int i) { if (parent[i] == i) return i; return parent[i] = find(parent, parent[i]); }
static int findCircleNum(int[][] isConnected) { int n = isConnected.length; int[] parent = new int[n]; for (int i = 0; i < n; i++) parent[i] = i; int provinces = n;
for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (isConnected[i][j] == 1) { int rootI = find(parent, i); int rootJ = find(parent, j); if (rootI != rootJ) { parent[rootI] = rootJ; provinces--; } } } } return provinces; }
public static void main(String[] args) { int[][] isConnected = { {1, 1, 0}, {1, 1, 0}, {0, 0, 1} }; System.out.println("Provinces count: " + findCircleNum(isConnected)); }}Provinces count: 2
What this code does
- Adjacency matrix represents symmetric connections between cities.
- Union-Find merges connected cities and decrements province count.
- Cities 0 and 1 form province 1, city 2 forms province 2.
Example 2 · Network Delay Time with Dijkstra in Java
import java.util.*;
public class Main { static int networkDelayTime(int[][] times, int n, int k) { List<List<int[]>> adj = new ArrayList<>(); for (int i = 0; i <= n; i++) adj.add(new ArrayList<>()); for (int[] t : times) { adj.get(t[0]).add(new int[]{t[1], t[2]}); }
int[] dist = new int[n + 1]; Arrays.fill(dist, Integer.MAX_VALUE); dist[k] = 0;
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0])); pq.offer(new int[]{0, k});
while (!pq.isEmpty()) { int[] curr = pq.poll(); int d = curr[0]; int u = curr[1]; if (d > dist[u]) continue;
for (int[] e : adj.get(u)) { int v = e[0]; int w = e[1]; if (dist[u] + w < dist[v]) { dist[v] = dist[u] + w; pq.offer(new int[]{dist[v], v}); } } }
int maxTime = 0; for (int i = 1; i <= n; i++) { if (dist[i] == Integer.MAX_VALUE) return -1; maxTime = Math.max(maxTime, dist[i]); } return maxTime; }
public static void main(String[] args) { int[][] times = {{1, 2, 1}, {2, 3, 2}, {1, 3, 4}}; System.out.println("Max delay: " + networkDelayTime(times, 3, 1)); }}Max delay: 3
What this code does
- Signal from node 1 reaches node 2 at time 1.
- It reaches node 3 at time 3 via node 2.
- Returns maximum time 3 required for all nodes to receive the signal.
For positive weighted shortest paths, use Dijkstra algorithm with a min-heap PriorityQueue. For dependency ordering and prerequisite scheduling, choose Kahn topological sort. When querying dynamic connectivity or cycle formation, Union-Find provides near-instant operations. To connect all vertices at lowest total cost, choose Kruskal or Prim minimum spanning tree. Recognising these classifications translates novel interview problems into optimal solutions.
Recognising implicit graph models
Many interview challenges do not explicitly provide adjacency lists or edge lists. Instead, the graph is implicit within 2D grids, string transformations, or account records. In 2D grids, each cell acts as a vertex with edges to adjacent cardinal neighbours.
Example 3 · Alien Dictionary Character Ordering in Java
import java.util.*;
public class Main { static String alienOrder(String[] words) { Map<Character, Set<Character>> adj = new HashMap<>(); Map<Character, Integer> inDegree = new HashMap<>();
for (String w : words) { for (char c : w.toCharArray()) { adj.putIfAbsent(c, new HashSet<>()); inDegree.putIfAbsent(c, 0); } }
for (int i = 0; i < words.length - 1; i++) { String w1 = words[i]; String w2 = words[i + 1]; if (w1.length() > w2.length() && w1.startsWith(w2)) return "";
int minLen = Math.min(w1.length(), w2.length()); for (int j = 0; j < minLen; j++) { char c1 = w1.charAt(j); char c2 = w2.charAt(j); if (c1 != c2) { if (!adj.get(c1).contains(c2)) { adj.get(c1).add(c2); inDegree.put(c2, inDegree.get(c2) + 1); } break; } } }
Queue<Character> q = new LinkedList<>(); for (char c : inDegree.keySet()) { if (inDegree.get(c) == 0) q.offer(c); }
StringBuilder sb = new StringBuilder(); while (!q.isEmpty()) { char u = q.poll(); sb.append(u); for (char v : adj.get(u)) { inDegree.put(v, inDegree.get(v) - 1); if (inDegree.get(v) == 0) q.offer(v); } }
return sb.length() == inDegree.size() ? sb.toString() : ""; }
public static void main(String[] args) { String[] words = {"z", "x", "z"}; System.out.println("Cycle alien order: [" + alienOrder(words) + "]"); }}Cycle alien order: []
What this code does
- Pairs z < x and x < z form a circular dependency.
- Kahn topological sort detects the cycle when the queue empties early.
- Returns empty string indicating no valid alien alphabet order exists.
In Word Ladder and Alien Dictionary, words or character prefixes form implicit nodes. Edges represent single-letter mutations or lexicographical ordering constraints. Identifying what constitutes a vertex and an edge is the critical first step. Always analyse input constraints before coding. If V is up to 100,000, aim for O(V + E) or O(E log V). If V is under 200, O(V^3) Floyd-Warshall or dense matrix representations are completely fine.
Edge cases in advanced graph problems
An edge case in a graph problem is an input shape that breaks naive code, such as an unreachable node or a cycle. Disconnected components can leave destinations unreachable with infinite distances. Directed graphs may contain cycles, causing topological sort queues to terminate prematurely.
int maxDelayOrMinusOne(int[] dist) { // disconnected graph int max = 0; for (int d : dist) { if (d == Integer.MAX_VALUE) return -1; // some node is unreachable max = Math.max(max, d); } return max;}
boolean hasCycle(List<Integer> kahnOrder, int n) { return kahnOrder.size() < n; // Kahn's queue emptied early}In 0-based versus 1-based indexing, bounds mismatches cause ArrayIndexOutOfBoundsException. In Dijkstra, failing to prune stale entries degrades performance and inflates heap memory. In Union-Find, omitting path compression degrades lookups into linear O(N) chains.
Always test extreme inputs: zero edges, isolated vertices, multiple components, and cycles. Verify that unreachable targets return appropriate sentinels such as -1 or empty arrays.
Finish up
Mark complete & continue
Next: Bellman-Ford