logo
SEE ALGORITHMS
    Bubble Sort
    Insertion Sort
    Selection Sort
    Heap Sort
    Radix Sort
    Merge Sort
    Quick Sort

Topological Sorting

Topological Sorting is an ordering of nodes in a directed acyclic graph (DAG) where each node appears before all the nodes it points to. It is like creating a list of tasks, ensuring that each task comes after any tasks it depends on. The sorting can be achieved using Kahn's algorithm or DFS with a stack. Kahn's algorithm works by repeatedly removing nodes with no incoming edges (zero in-degree) and adding them to the order.

Pseudocode

indeg = indegree()
stack = new Stack()
for each vertex v:
    if indeg[v] == 0: stack.push(v)
while stack is not empty:
    u = stack.pop()
    add u to sorted list
    for each neighbor v of u:
        indeg[v] = indeg[v] - 1
        if indeg[v] == 0: stack.push(v)
function indegree():
    indeg = map vertex -> 0
    for each vertex u:
        for each neighbor v of u:
            indeg[v] = indeg[v] + 1
    return indeg
Draw Graph

Curious to Learn More?

Hand-picked resources to deepen your understanding

Beginner Friendly
Coding Interview Bootcamp: Algorithms + Data Structures

Learn essential data structures and algorithms step-by-step with practical JavaScript examples.

Practical Guide
JavaScript Algorithms & Data Structures Masterclass

Master DSA fundamentals, problem-solving techniques, and advanced structures using JavaScript.

Deep Dive
Master the Coding Interview: Data Structures + Algorithms

Prepare for top tech interviews with advanced DSA concepts and real-world coding challenges.

As an Udemy Associate, I earn from qualifying purchases. This helps support the site at no extra cost to you.

© 2025 SEE Algorithms. Code licensed under MIT, content under CC BY-NC 4.0.