Topic 72 of 78
Topological Sort
Overview
Topological Sort is used strictly on Directed Acyclic Graphs (DAGs) to linearly order the vertices such that for every directed edge U -> V, vertex U comes before V in the ordering. Think of live class prerequisites: You must take Java 101 before taking Advanced Data Structures. Topological Sort gives you the exact valid sequence to take your classes.
Syntax
By constantly peeling off nodes that have 0 incoming edges, we guarantee that we process parents before children.
BFS based
java
public List<Integer> topoSort(int numNodes, int[][] edges) {
int[] inDegree = new int[numNodes];
Map<Integer, List<Integer>> adj = new HashMap<>();
// Build Graph and calculate In-Degrees (how many prerequisites a node has)
for (int[] edge : edges) {
adj.computeIfAbsent(edge[0], k -> new ArrayList<>()).add(edge[1]);
inDegree[edge[1]]++;
}
// Queue holds nodes with NO prerequisites
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < numNodes; i++) {
if (inDegree[i] == 0) q.offer(i);
}
List<Integer> order = new ArrayList<>();
while (!q.isEmpty()) {
int curr = q.poll();
order.add(curr);
// Fulfill prerequisite for neighbors
for (int neighbor : adj.getOrDefault(curr, new ArrayList<>())) {
inDegree[neighbor]--;
if (inDegree[neighbor] == 0) q.offer(neighbor); // Ready to process
}
}
// If order size != numNodes, the graph has a cycle (impossible to complete)
return order.size() == numNodes ? order : new ArrayList<>();
}Common Pitfalls
- Attempting a Topological Sort on an Undirected graph or a graph with cycles. It is mathematically impossible.
Interview Tips
- Whenever a problem mentions 'Prerequisites', 'Dependencies', or 'Scheduling tasks', immediately use Topological Sort.
Real-World Example
Build systems like Webpack or Maven use Topological Sort to determine the exact order to compile your code dependencies.
example
java
// Maven compiles library A before compiling your App which depends on library A.