java
39 lines · 6 steps
Topological sort with Kahn's algorithm
Order a directed graph's nodes so every edge points forward, using in-degree counting and a ready queue.
Explained by
highlit
1import java.util.*;
2
3public class TopologicalSort {
4
5 public static List<Integer> sort(int numNodes, int[][] edges) {
6 List<List<Integer>> adjacency = new ArrayList<>();
7 for (int i = 0; i < numNodes; i++) {
8 adjacency.add(new ArrayList<>());
9 }
10 int[] inDegree = new int[numNodes];
11 for (int[] edge : edges) {
12 adjacency.get(edge[0]).add(edge[1]);
13 inDegree[edge[1]]++;
14 }
15
16 Queue<Integer> ready = new ArrayDeque<>();
17 for (int node = 0; node < numNodes; node++) {
18 if (inDegree[node] == 0) {
19 ready.offer(node);
20 }
21 }
22
23 List<Integer> order = new ArrayList<>();
24 while (!ready.isEmpty()) {
25 int node = ready.poll();
26 order.add(node);
27 for (int neighbor : adjacency.get(node)) {
28 if (--inDegree[neighbor] == 0) {
29 ready.offer(neighbor);
30 }
31 }
32 }
33
34 if (order.size() != numNodes) {
35 throw new IllegalArgumentException("Graph has a cycle; no topological order exists");
36 }
37 return order;
38 }
39}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Kahn's algorithm repeatedly removes nodes with no remaining prerequisites to build a valid ordering.
- 2Tracking in-degree lets you detect exactly when a node becomes ready without rescanning the graph.
- 3If fewer nodes are emitted than exist, the graph must contain a cycle and no ordering is possible.
Related explainers
java
public interface GitHubClient { @GetExchange("/users/{username}") GitHubUser getUser(@PathVariable String username);
Declarative HTTP clients in Spring
http-client
declarative-api
proxy
Intermediate
8 steps
java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
Building a trie for autocomplete in Java
trie
prefix-tree
recursion
Intermediate
8 steps
java
@RestController @RequestMapping("/api/products") public class ProductSearchController {
Binding collection query params in Spring
rest-api
query-parameters
dependency-injection
Intermediate
6 steps
java
import java.util.ArrayDeque; import java.util.Deque; import java.util.Map;
Evaluating math expressions with two stacks
stacks
parsing
operator-precedence
Intermediate
9 steps
java
@Entity @Table(name = "orders") @SQLDelete(sql = "UPDATE orders SET deleted = true, deleted_at = now() WHERE id = ?") @Where(clause = "deleted = false")
Soft deletes with Hibernate in Spring
soft-delete
jpa
hibernate
Intermediate
9 steps
java
@GetMapping("/files/{id}") public ResponseEntity<StreamingResponseBody> download( @PathVariable String id, @RequestHeader(value = HttpHeaders.RANGE, required = false) String rangeHeader) throws IOException {
HTTP range requests in Spring
http-range
streaming
file-io
Advanced
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/topological-sort-with-kahn-s-algorithm-explained-java-a508/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.