Java Graph Program · OT72
Topological Sort of a Graph in Java
Repeatedly output a vertex that has no remaining incoming edges, then remove its outgoing edges. If the graph has no cycle, every vertex is eventually output.
Problem Statement
Given a directed graph, return an ordering of all vertices such that for every edge u → v, u comes before v.
Such an order exists only for an acyclic graph; for a graph with a cycle, return an empty list. Several orders can be valid.
Input/Output Examples
0→2, 1→2, 2→3, 1→4, 4→3, 3→5Output[0, 1, 2, 4, 3, 5]Explanation: one valid order (Kahn's with the smallest ready vertex first).same graph, DFSOutput[1, 4, 0, 2, 3, 5]Explanation: also respects every edge.0→1, 1→2, 2→0Output[]Explanation: no order is possible.Visual Explanation
- Readyin-degree 001take 0
- Take 1ready242 and 4 become ready
- Take 2, 4ready33 waits for both
- Take 3, 5order012435
- Donevalid order
Choosing the smallest ready vertex with a priority queue makes Kahn's output repeatable; any choice among ready vertices would still give a valid order.
Approaches
Both approaches produce a valid order and detect cycles. Kahn's removes ready vertices; DFS uses finishing order.
Approach 1: Kahn's Algorithm (Recommended)
Idea: count in-degrees, then repeatedly output a vertex with in-degree 0 and decrease its neighbours' in-degrees.
- Compute every vertex's in-degree.
- Put the vertices with in-degree 0 in a priority queue.
- Poll a vertex, add it to the order and update its neighbours.
- If the order is shorter than
n, there is a cycle.
Time: O((V + E) log V) · Space: O(V + E). With a plain queue it is O(V + E).
Approach 2: Reverse DFS Post-Order
Idea: a vertex finishes only after all vertices it points to have finished, so reversing the finishing order gives a valid order.
- Run a DFS from every unvisited vertex.
- Add a vertex to a list when its DFS finishes.
- Reverse the list; report a cycle if a grey vertex was reached.
Time: O(V + E) · Space: O(V + E).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. The two programs print different orders, because a graph can have many valid topological orders; each program checks its own order and prints valid=true.
Approach 1: Kahn's Algorithm (Recommended)
The priority queue only fixes the order of ties; it is not needed for correctness.
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
public class TopoKahn {
static List<List<Integer>> graph(int n, int[][] edges) {
List<List<Integer>> g = new ArrayList<>();
for (int i = 0; i < n; i++) {
g.add(new ArrayList<>());
}
for (int[] e : edges) {
g.get(e[0]).add(e[1]);
}
return g;
}
// Kahn's algorithm; a min-heap makes it pick the smallest ready vertex, so the order is repeatable
static List<Integer> topoSort(int n, int[][] edges) {
List<List<Integer>> g = graph(n, edges);
int[] in = new int[n];
for (int[] e : edges) {
in[e[1]]++;
}
PriorityQueue<Integer> ready = new PriorityQueue<>();
for (int v = 0; v < n; v++) {
if (in[v] == 0) {
ready.add(v);
}
}
List<Integer> order = new ArrayList<>();
while (!ready.isEmpty()) {
int v = ready.poll();
order.add(v);
for (int w : g.get(v)) {
if (--in[w] == 0) {
ready.add(w);
}
}
}
return order.size() == n ? order : List.of(); // empty list: the graph has a cycle
}
static boolean isValidOrder(List<Integer> order, int n, int[][] edges) {
if (order.size() != n) {
return false;
}
int[] pos = new int[n];
for (int i = 0; i < n; i++) {
pos[order.get(i)] = i;
}
for (int[] e : edges) {
if (pos[e[0]] >= pos[e[1]]) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int[][] edges = {{0, 2}, {1, 2}, {2, 3}, {1, 4}, {4, 3}, {3, 5}};
List<Integer> order = topoSort(6, edges);
System.out.println("order: " + order + ", valid=" + isValidOrder(order, 6, edges));
int[][] cyclic = {{0, 1}, {1, 2}, {2, 0}};
System.out.println("cycle: " + topoSort(3, cyclic));
}
}
order: [0, 1, 2, 4, 3, 5], valid=true cycle: []
Time complexity: O((V + E) log V) · Space complexity: O(V + E).
Approach 2: Reverse DFS Post-Order
Natural when you already have a DFS; the cycle check uses the same three colours as cycle detection.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TopoDfs {
static List<List<Integer>> graph(int n, int[][] edges) {
List<List<Integer>> g = new ArrayList<>();
for (int i = 0; i < n; i++) {
g.add(new ArrayList<>());
}
for (int[] e : edges) {
g.get(e[0]).add(e[1]);
}
return g;
}
private static boolean cycle;
// Reverse post-order of a DFS: a vertex is added only after everything it points to
static List<Integer> topoSort(int n, int[][] edges) {
List<List<Integer>> g = graph(n, edges);
int[] state = new int[n];
List<Integer> post = new ArrayList<>();
cycle = false;
for (int v = 0; v < n; v++) {
if (state[v] == 0) {
dfs(v, g, state, post);
}
}
if (cycle) {
return List.of();
}
Collections.reverse(post);
return post;
}
private static void dfs(int v, List<List<Integer>> g, int[] state, List<Integer> post) {
state[v] = 1;
for (int w : g.get(v)) {
if (state[w] == 1) {
cycle = true;
} else if (state[w] == 0) {
dfs(w, g, state, post);
}
}
state[v] = 2;
post.add(v);
}
static boolean isValidOrder(List<Integer> order, int n, int[][] edges) {
if (order.size() != n) {
return false;
}
int[] pos = new int[n];
for (int i = 0; i < n; i++) {
pos[order.get(i)] = i;
}
for (int[] e : edges) {
if (pos[e[0]] >= pos[e[1]]) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int[][] edges = {{0, 2}, {1, 2}, {2, 3}, {1, 4}, {4, 3}, {3, 5}};
List<Integer> order = topoSort(6, edges);
System.out.println("order: " + order + ", valid=" + isValidOrder(order, 6, edges));
int[][] cyclic = {{0, 1}, {1, 2}, {2, 0}};
System.out.println("cycle: " + topoSort(3, cyclic));
}
}
order: [1, 4, 0, 2, 3, 5], valid=true cycle: []
Time complexity: O(V + E) · Space complexity: O(V + E).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Kahn's Algorithm | O((V + E) log V) | O(V + E) |
| Reverse DFS Post-Order | O(V + E) | O(V + E) |
Here V is the number of vertices and E the number of edges. Both approaches process every vertex and edge once.
Interview Tips and Recommended Approach
- Say that the answer is not unique. Test by checking edges, not by comparing with one fixed order.
- Detect cycles by comparing the output size with the number of vertices.
- Know the applications: build systems, course planning and spreadsheet recalculation.
- Use a priority queue when the smallest-first (lexicographic) order is required.
Recommended Approach: Kahn's Algorithm
Why: it is iterative, detects cycles for free and makes the "ready to run" idea explicit, which matches how schedulers work.