DSA
    intermediate

    Topological Sort

    Topological Sort (Kahn's Algorithm)

    Linear ordering of vertices such that for every directed edge u -> v, vertex u comes before v. Uses In-Degree logic.

    ⏱ O(V+E)
    💾 O(V)
    Ready
    A
    0
    B
    0
    C
    1
    D
    2
    E
    1
    F
    3
    Sorted Order

    Calculate in-degrees for all nodes.

    50%
    Live Variables
    queueSize0
    sortedCount0

    Kahn’s algorithm

    Sequence

    Order the steps of a topological sort by in-degree.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    Topological Sort is only possible for which type of graph?

    Write the code

    Runs your solution

    Course Schedule II

    Return the ordering of courses you should take to finish all courses given the prerequisites. Return an empty array if impossible.

    Example Cases

    Input:[2, [[1,0]]]
    Output:[0,1]
    Input:[4, [[1,0],[2,0],[3,1],[3,2]]]
    Output:[0,1,2,3]
    javascript

    The short version

    Think of getting dressed. You must put on socks before shoes, and underwear before pants. You can't just put things on in random order; dependencies must be respected.

    In more depth

    Order of Operations

    Topological Sorting is a linear ordering of vertices such that for every directed edge u -> v, vertex u comes before v in the ordering.

    Prerequisite: The graph must be a Directed Acyclic Graph (DAG). If there is a cycle (A -> B -> A), no linear ordering is possible.

    Kahn's Algorithm (BFS):

    1.Calculate In-Degree of all nodes.
    2.Add nodes with In-Degree 0 to a queue.
    3.Process queue: remove node, decrement neighbor In-Degrees. If neighbor becomes 0, add to queue.

    When to reach for this

    • Scheduling tasks with dependencies
    • Build systems (compiling dependencies first)
    • Detecting cycles in a directed graph

    Interview Questions

    Amazon
    Microsoft
    LinkedIn
    Meta
    Google
    Microsoft
    Amazon
    Palantir
    LinkedIn
    Netflix
    Bloomberg
    Uber

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required