logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
instagramtwitterfacebookyoutubelinkedinmailgithubrss
Copyright © 2026 All rights reserved.
•
VIKI
Built with Vikramaditya Singh
Built with
VIKI - A posts created with Next.js and Tailwind.css
About
arrays
Arrays
Boyer-Moore Majority Vote Algorithm
Kadane’s Algorithm
Triple Reverse algorithm aka Reversal Algorithm
graph
Cycle detection
Graph
Topological Sort
Tree Traversal
heap
Binary Heap
Binomial Heap
Heap
linked-list
Cycle Detection
Linked List
Sorting
miscellaneous
Finding the majority element
Rotate array by K steps
numerical-algorithms
Finding If Number is Prime
GCD of two numbers
Performing Exponentiation
Prime Numbers
Randomising Data
partitioning
3. Max Consecutive Ones
Hoare'S Partition Scheme
Lomuto Partition Scheme
queue
Deques
Priority Queue
Queue
search
The Binary Search Master Guide
The Rotated Sorted Array Master Guide
sort
Bubble Sort
Counting Sort
Sorting
Insertion Sort
Merge Sort
Pigeon Hole Sort
Quick Sort
Selection Sort
stack
Monotonic Stack
Monotonic Stack
Stack
Reversing an Array
Stack
Tower of Hanoi
tree
Binary Tree Traversal
Centre of gravity
Diameter of Tree
Shortest Path
Algorithmic Pattern›graph

Topological Sort

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&#x20;
  • 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"
PreviousGraphNextTree Traversal
CONTENTS
Topological Sort using DFSTopological Sort by BFSReference&#x20;