Topological sort of a directed graph is a linear ordering of its vertices such that for every directed edge (u,v) from vertex u to vertex v, u comes before v in the ordering.
When topological sort is implemented using Kahn's Algorithm (BFS with a queue), the time complexity and space complexity are as follows:
- Counting in-degrees takes π(πΈ) time because we iterate over each edge once.
- Enqueueing and dequeueing each vertex takes π(π) time.
- Processing each neighbor of each vertex (decreasing in-degrees and enqueuing zero in-degree nodes) takes π(πΈ) time as each edge is visited once.
The space complexity is also π(π+πΈ) because:
- We need space to store the graph (using an adjacency list) with π vertices and πΈ edges, which takes π(π+πΈ).
- We maintain an in-degree array of size π, taking π(π).
- The queue holds vertices with zero in-degrees, and in the worst case, all vertices could be added to the queue, so it also takes π(π) space.