logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
ArraysBoyer-Moore Majority Vote AlgorithmKadane’s AlgorithmTriple Reverse algorithm aka Reversal Algorithm
Cycle detectionDijkstraDisjoint Set UnionGraphTopological SortTraversal algorithmsTree Traversal
Binary HeapBinomial HeapHeap
Cycle DetectionLinked ListSorting
Finding the majority elementRotate array by K steps
Finding If Number is PrimeGCD of two numbersPerforming ExponentiationPrime NumbersRandomising Data
3. Max Consecutive OnesHoare'S Partition SchemeLomuto Partition Scheme
DequesPriority QueueQueue
The Binary Search Master GuideThe Rotated Sorted Array Master Guide
Bubble SortCounting SortInsertion SortMerge SortPigeon Hole SortQuick SortSelection Sort
Monotonic StackMonotonic StackStackReversing an ArrayStackTower of Hanoi
Binary Tree TraversalCentre of gravityDiameter of TreeShortest Path
Algorithmic Pattern/graph

Topological Sort

5 min read
On this pageTopological Sort using DFS
Topological Sort using DFSTopological Sort by BFSReference 

Topological sort is a technique used in graph theory to order the vertices of a directed acyclic graph (DAG).

  • It ensures that for every directed edge from vertex A to vertex B, vertex A comes before vertex B in the ordering.
  • It orders the vertices on a line such that all directed edges go from left to right. <mark style="background-color:yellow;">Such an ordering cannot exist if the graph is not a</mark> <mark style="background-color:yellow;"></mark><mark style="background-color:yellow;">DAG</mark> <mark style="background-color:yellow;"></mark><mark style="background-color:yellow;">and contains one or more directed cycle(s), because there is no way we can keep going on the right on a line and still return to a vertex already visited (we are talking about</mark> <mark style="background-color:yellow;"></mark><mark style="background-color:yellow;">Back Edges</mark> <mark style="background-color:yellow;"></mark><mark style="background-color:yellow;">here).</mark>

\

Danger

<mark style="color:orange;">The topological sort is not necessarily unique.</mark>

  • An acyclic graph always has a topological sort

# Usecases

  • This is useful in scheduling problems, where tasks depend on the completion of other tasks.
  • Topological sort can sequence tasks while respecting all sequence constraints without any conflict.

# Topological Sort using DFS

  • DFS is a highly efficient way to compute topological sort of a graph in linear time O(E+V)\text{O}(E + V)O(E+V)

Info

Sink vertices are the only candidates for the final/last vertex position in the topological ordering.

  • We will search for the sink vertices, and as we get a sink vertex we will disconnect that vertex from the graph and will then backtrack and search for the next sink vertex along the search path, until all the vertices in the graph are visited.

  • This way we will get all the vertices in totally reverse order of that of what a topological ordering should be. So we would need to reverse the order to get the topological sort.

Info

In DFS we print the nodes as we see them, which means when we print a node, it has just been discovered but not yet processed, which means it is in the Visiting state.

  • So DFS gives the order in which the nodes enter the Visiting state and not the Visited state.
  • For topological sorting we need to have the order in which the nodes are completely processed, i.e, the order in which the nodes are marked as Visited. Because when a node is marked Visited then all of its child node have already been processed
  • At any point during the DFS traversal of a graph we can divide the nodes in 3 groups

    1. Nodes that we finished visiting, i.e. popped from the stack.
    2. Nodes that are currently on the stack.
    3. Nodes that are yet to be discovered.

    If we are on node AAA that has an outgoing edge to another node BBB. If the graph is a DAG we can be certain that BBB falls in categories 1 or 3. If BBB would be on the stack, than the arc A→BA → BA→Bwould close a cycle, and this is impossible on a DAG.

    This property actually tells us that any node is popped from the stack after all of its outgoing neighbours are popped. So in order to get a topological sorting we should just keep track of a list with the popped nodes in reverse order.

# Complexity Analysis

  • Time Complexity: O(V+E)\text{O}(V+E)O(V+E)
    The outer for loop will be executed V number of times and the inner for loop will be executed E number of times.
  • Auxiliary Space: O(V)\text{O}(V)O(V)
    The queue needs to store all the vertices of the graph. So the space required is O(V)\text{O}(V)O(V)

# Topological Sort by BFS

  • The BFS version for topological sort is known as Kahn's Algorithm.

Info

The indegree of a node represents the number of arcs coming into a node. The outdegree represents the number of arcs going from a node.

  • The first node in a topological sorting should have the indegree equal to 0.

    If the first node would have an arc coming into it, that particular arc would contradict the sorting property.

# Algorithm

  1. Find the in-degree of each node by initially calculating the number of incoming edges to each node.

    Iterate through all the edges in the graph and increment the in-degree of the destination node for each edge.

  2. Add all nodes with in-degree 0 to a queue.

  3. While the queue is not empty:

    1. Remove a node from the queue.
    2. For each outgoing edge from the removed node, decrement the in-degree of the destination node by 1.
    3. If the in-degree of a destination node becomes 0, add it to the queue.
  4. If the queue is empty and there are still nodes in the graph, the graph contains a cycle and cannot be topologically sorted.

Info

We can also use Kahn's algorithm to extract the lexicographically minimum topological sort by breaking ties lexographically. One can simply replace the queue with a priority_queue to implement this extension.

# Complexity Analysis

  • Time Complexity: O(V+E)\text{O}(V+E)O(V+E)
    The outer for loop will be executed V number of times and the inner for loop will be executed E number of times.
  • Auxiliary Space: O(V)\text{O}(V)O(V)
    The queue needs to store all the vertices of the graph. So the space required is O(V)\text{O}(V)O(V)

# Reference

  • GeekForGeeks Kahn's algorithm for Topological Sorting
  • Topological Sort : DFS, BFS and DAG
  • Topological Sorting with graph visualisation
  • Topological sort explaination from USCAO
  • Directed graphs chapter from "Competitive Programmer’s Handbook"
←PreviousGraphNext→Traversal algorithms

On this page

Topological Sort using DFSTopological Sort by BFSReference&#x20;