1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Topological Sort
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
14Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Topological Sort

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
14Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Topological Sort

Overview

Topological Sort applies exclusively to Directed Acyclic Graphs (DAGs). It orders the vertices linearly such that for every directed edge pointing from U to V, vertex U appears before vertex V in the final ordering.

This is the definitive algorithm behind Dependency Resolution. Imagine you need to compile a massive Java project. Class B imports Class A, so Class B depends on Class A. You absolutely must compile Class A first. Topological Sort maps out the exact sequence to process hundreds of tasks without violating a single prerequisite.

Kahn's Algorithm is the standard, intuitive way to implement this using a BFS-like queue approach. It calculates the 'In-Degree' (number of incoming prerequisites) for every node. Nodes with an In-Degree of 0 have no prerequisites and are ready to execute! They are added to a Queue. As they are processed, they 'remove' their outbound edges, dropping the In-Degrees of their neighbors until the neighbors hit 0 and enter the queue.

Syntax

Kahn's Algorithm (BFS based)
java
import java.util.*;

public class TopologicalSort {
    // prerequisites format: [Course, RequiredPrereq]
    public List<Integer> sort(int numCourses, int[][] prerequisites) {
        Map<Integer, List<Integer>> graph = new HashMap<>();
        int[] inDegree = new int[numCourses]; // Tracks prerequisites count
        
        // 1. Build Graph and calculate In-Degrees
        for (int[] pre : prerequisites) {
            int course = pre[0];
            int required = pre[1]; // Required -> Course
            
            graph.putIfAbsent(required, new ArrayList<>());
            graph.get(required).add(course);
            inDegree[course]++; // This course has an incoming requirement
        }
        
        // 2. Add all courses with NO prerequisites (In-Degree == 0) to Queue
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < numCourses; i++) {
            if (inDegree[i] == 0) queue.offer(i);
        }
        
        List<Integer> order = new ArrayList<>();
        
        // 3. Process Queue
        while (!queue.isEmpty()) {
            int curr = queue.poll();
            order.add(curr);
            
            // We finished 'curr'. Decrease In-Degree of all courses depending on it.
            for (int neighbor : graph.getOrDefault(curr, new ArrayList<>())) {
                inDegree[neighbor]--;
                // If a neighbor now has 0 prerequisites left, it's ready!
                if (inDegree[neighbor] == 0) {
                    queue.offer(neighbor);
                }
            }
        }
        
        // If the order size != numCourses, there was a cycle! (Impossible to resolve)
        return order.size() == numCourses ? order : new ArrayList<>();
    }
}

Common Pitfalls

  • Not checking for cycles at the end. If the graph contains a cycle (A depends on B, B depends on A), those nodes will never reach an In-Degree of 0. They will never enter the queue. You must check if (order.size() == numNodes) at the end to guarantee a valid sort.
  • Parsing the directed edges backwards. If the input array is [Task, Prerequisite], the edge MUST point from Prerequisite -> Task. Getting this backwards breaks the entire logic.
  • Using it on undirected graphs. Topological sort relies entirely on one-way dependencies. It makes no mathematical sense on an undirected graph.

Interview Questions

What does an In-Degree of 0 mean in the context of Kahn's Algorithm?

It means the node has absolutely no uncompleted prerequisites. It is totally independent and is ready to be processed immediately.

Can there be multiple valid Topological Sorts for the same graph?

Yes, absolutely. If multiple nodes have an In-Degree of 0 at the same time, the order you pull them from the queue dictates the sort. Both orderings are perfectly valid dependency resolutions.

Real-World Example

Build Tools and Package Managers. When you run npm install or mvn clean install, the tool reads the package.json or pom.xml. It builds a massive dependency graph. It runs a Topological Sort to figure out exactly which libraries must be downloaded and compiled first so that later libraries have everything they need to function.

example
java
public class BuildSystem {
    public void compileProject(List<Module> modules) {
        List<Module> compilationOrder = runTopologicalSort(modules);
        
        if (compilationOrder.size() < modules.size()) {
            throw new CircularDependencyException("Cannot compile: Cycle detected!");
        }
        
        for (Module m : compilationOrder) {
            System.out.println("Compiling: " + m.getName());
            m.compile();
        }
    }
}

Check Your Knowledge

Test your understanding of Topological Sort with these quick questions.

Question 1

What happens if Topological Sort detects a cycle?

Question 2

In Kahn's algorithm, what causes a node to be added to the queue?

Question 3

What kind of graph is required for Topological Sort?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Topological Sort

Overview

Topological Sort applies exclusively to Directed Acyclic Graphs (DAGs). It orders the vertices linearly such that for every directed edge pointing from U to V, vertex U appears before vertex V in the final ordering.

This is the definitive algorithm behind Dependency Resolution. Imagine you need to compile a massive Java project. Class B imports Class A, so Class B depends on Class A. You absolutely must compile Class A first. Topological Sort maps out the exact sequence to process hundreds of tasks without violating a single prerequisite.

Kahn's Algorithm is the standard, intuitive way to implement this using a BFS-like queue approach. It calculates the 'In-Degree' (number of incoming prerequisites) for every node. Nodes with an In-Degree of 0 have no prerequisites and are ready to execute! They are added to a Queue. As they are processed, they 'remove' their outbound edges, dropping the In-Degrees of their neighbors until the neighbors hit 0 and enter the queue.

Syntax

Kahn's Algorithm (BFS based)
java
import java.util.*;

public class TopologicalSort {
    // prerequisites format: [Course, RequiredPrereq]
    public List<Integer> sort(int numCourses, int[][] prerequisites) {
        Map<Integer, List<Integer>> graph = new HashMap<>();
        int[] inDegree = new int[numCourses]; // Tracks prerequisites count
        
        // 1. Build Graph and calculate In-Degrees
        for (int[] pre : prerequisites) {
            int course = pre[0];
            int required = pre[1]; // Required -> Course
            
            graph.putIfAbsent(required, new ArrayList<>());
            graph.get(required).add(course);
            inDegree[course]++; // This course has an incoming requirement
        }
        
        // 2. Add all courses with NO prerequisites (In-Degree == 0) to Queue
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < numCourses; i++) {
            if (inDegree[i] == 0) queue.offer(i);
        }
        
        List<Integer> order = new ArrayList<>();
        
        // 3. Process Queue
        while (!queue.isEmpty()) {
            int curr = queue.poll();
            order.add(curr);
            
            // We finished 'curr'. Decrease In-Degree of all courses depending on it.
            for (int neighbor : graph.getOrDefault(curr, new ArrayList<>())) {
                inDegree[neighbor]--;
                // If a neighbor now has 0 prerequisites left, it's ready!
                if (inDegree[neighbor] == 0) {
                    queue.offer(neighbor);
                }
            }
        }
        
        // If the order size != numCourses, there was a cycle! (Impossible to resolve)
        return order.size() == numCourses ? order : new ArrayList<>();
    }
}

Common Pitfalls

  • Not checking for cycles at the end. If the graph contains a cycle (A depends on B, B depends on A), those nodes will never reach an In-Degree of 0. They will never enter the queue. You must check if (order.size() == numNodes) at the end to guarantee a valid sort.
  • Parsing the directed edges backwards. If the input array is [Task, Prerequisite], the edge MUST point from Prerequisite -> Task. Getting this backwards breaks the entire logic.
  • Using it on undirected graphs. Topological sort relies entirely on one-way dependencies. It makes no mathematical sense on an undirected graph.

Interview Questions

What does an In-Degree of 0 mean in the context of Kahn's Algorithm?

It means the node has absolutely no uncompleted prerequisites. It is totally independent and is ready to be processed immediately.

Can there be multiple valid Topological Sorts for the same graph?

Yes, absolutely. If multiple nodes have an In-Degree of 0 at the same time, the order you pull them from the queue dictates the sort. Both orderings are perfectly valid dependency resolutions.

Real-World Example

Build Tools and Package Managers. When you run npm install or mvn clean install, the tool reads the package.json or pom.xml. It builds a massive dependency graph. It runs a Topological Sort to figure out exactly which libraries must be downloaded and compiled first so that later libraries have everything they need to function.

example
java
public class BuildSystem {
    public void compileProject(List<Module> modules) {
        List<Module> compilationOrder = runTopologicalSort(modules);
        
        if (compilationOrder.size() < modules.size()) {
            throw new CircularDependencyException("Cannot compile: Cycle detected!");
        }
        
        for (Module m : compilationOrder) {
            System.out.println("Compiling: " + m.getName());
            m.compile();
        }
    }
}

Check Your Knowledge

Test your understanding of Topological Sort with these quick questions.

Question 1

What happens if Topological Sort detects a cycle?

Question 2

In Kahn's algorithm, what causes a node to be added to the queue?

Question 3

What kind of graph is required for Topological Sort?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A