What is Topological Sorting in Graphs

💡 Concept Name

Topological Sorting – A linear ordering of vertices in a directed acyclic graph (DAG) such that for every directed edge u → v, vertex u comes before v.

📘 Quick Intro

Topological sort is only possible in DAGs and is widely used in scheduling problems, task ordering, dependency resolution, and more. It ensures that each task’s prerequisites are completed first.

🧠 Analogy / Short Story

Think of a college course plan: you must take "Intro to Programming" before "Data Structures", and "Data Structures" before "Algorithms". A topological sort gives you an order that respects these prerequisites.

🔧 Technical Explanation

  • 🏗️ DAG Requirement: Only valid for Directed Acyclic Graphs.
  • 📥 Kahn’s Algorithm:
    • Uses in-degree count and queue
    • Removes nodes with in-degree 0
  • 🧭 DFS-based Method:
    • Recursive post-order traversal
    • Push nodes onto a stack after processing neighbors
  • 🕒 Time Complexity: O(V + E)

🎯 Purpose & Use Case

  • ✅ Course scheduling systems
  • ✅ Build systems and task dependency resolution
  • ✅ Compiler instruction ordering

💻 Real Code Example

// Kahn's Algorithm for Topological Sort
List<int> TopologicalSort(List<int>[] graph, int v)
{
    int[] inDegree = new int[v];
    foreach (var edges in graph)
        foreach (var node in edges)
            inDegree[node]++;

    Queue<int> q = new Queue<int>();
    for (int i = 0; i < v; i++)
        if (inDegree[i] == 0)
            q.Enqueue(i);

    List<int> result = new List<int>();
    while (q.Count > 0)
    {
        int u = q.Dequeue();
        result.Add(u);
        foreach (var neighbor in graph[u])
        {
            if (--inDegree[neighbor] == 0)
                q.Enqueue(neighbor);
        }
    }

    return result.Count == v ? result : null; // Null indicates cycle
}

❓ Interview Q&A

Q1: What is topological sorting?
A: A linear ordering of vertices in a directed acyclic graph (DAG) such that for every directed edge u → v, u comes before v.

Q2: Which types of graphs can be topologically sorted?
A: Directed acyclic graphs (DAGs) only.

Q3: What are common applications of topological sorting?
A: Task scheduling, resolving symbol dependencies, build systems, and instruction ordering.

Q4: What is the time complexity of topological sorting?
A: O(V + E), where V is vertices and E is edges.

Q5: Name two common algorithms for topological sorting.
A: Kahn's algorithm and DFS-based algorithm.

Q6: How does Kahn’s algorithm work?
A: By repeatedly removing nodes with zero in-degree and updating in-degrees of adjacent nodes.

Q7: How does DFS-based topological sorting work?
A: By performing DFS and pushing nodes onto a stack after visiting all descendants.

Q8: What happens if the graph contains a cycle?
A: Topological sorting is not possible.

Q9: Can topological sorting be used for undirected graphs?
A: No, it is only defined for directed acyclic graphs.

Q10: How can topological sorting detect cycles?
A: If a cycle exists, algorithms detect it by checking remaining nodes with non-zero in-degree or recursion stack.

📝 MCQs

Q1. What does topological sorting produce?

  • Shortest path
  • Linear ordering of vertices
  • Cycle detection
  • Graph coloring

Q2. Which graph type supports topological sorting?

  • Undirected graph
  • Directed graph with cycles
  • Directed acyclic graph
  • Complete graph

Q3. What is the time complexity of topological sort?

  • O(V^2)
  • O(E^2)
  • O(V + E)
  • O(log V)

Q4. Name a topological sort algorithm.

  • Dijkstra
  • Kahn's algorithm
  • Prim's algorithm
  • Kruskal's algorithm

Q5. How does Kahn’s algorithm work?

  • Remove nodes randomly
  • Remove nodes with zero in-degree
  • Remove leaf nodes
  • Remove nodes with highest degree

Q6. How does DFS-based topological sort work?

  • Pre-order DFS
  • Post-order DFS traversal
  • Level order traversal
  • BFS traversal

Q7. Can topological sorting detect cycles?

  • No
  • Yes
  • Sometimes
  • Depends on graph

Q8. Is topological sorting possible for graphs with cycles?

  • Yes
  • No
  • Only for some cycles
  • Depends on edges

Q9. Can topological sorting be applied to undirected graphs?

  • Yes
  • No
  • Sometimes
  • Depends

Q10. What is the key requirement for topological sorting?

  • Graph must be connected
  • Graph must be acyclic
  • Graph must be weighted
  • Graph must be complete

💡 Bonus Insight

Topological sorting is also used in task automation pipelines, where job A must finish before job B starts. It’s crucial in build tools like Make, Gradle, and compilers.

📄 PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

Learn More About Data Structures 📚

What is a Data Structure and Why is it Important? 👉 Learn More
Linear vs Non-linear Data Structures 👉 Learn More
Arrays vs Linked Lists 👉 Learn More
Advantages & Disadvantages of Arrays 👉 Learn More
Singly Linked List Explained 👉 Learn More
Singly vs Doubly Linked List 👉 Learn More
Circular Linked List & Its Use Cases 👉 Learn More
Reversing a Linked List 👉 Learn More
Stack vs Queue 👉 Learn More
Circular Queue Explained 👉 Learn More
Queue Overflow & Underflow 👉 Learn More
Applications of Stacks 👉 Learn More
Priority Queue Explained 👉 Learn More
Deque vs Queue 👉 Learn More
Implement Stack Using Queues 👉 Learn More
Implement Queue Using Stacks 👉 Learn More
Trees in Data Structures 👉 Learn More
Binary Trees Explained 👉 Learn More
Binary Search Tree vs Binary Tree 👉 Learn More
Insert & Delete in BST 👉 Learn More
Tree Traversals (Inorder, Preorder, Postorder) 👉 Learn More
Level Order Traversal 👉 Learn More
Balanced Binary Tree 👉 Learn More
AVL Trees Explained 👉 Learn More
Red-Black Trees 👉 Learn More
B-tree vs BST 👉 Learn More
Heaps in Data Structures 👉 Learn More
Min-Heap vs Max-Heap 👉 Learn More
Implementing Heap Using Arrays 👉 Learn More
Applications of Heaps 👉 Learn More
Tries & Word Searching 👉 Learn More
Graphs Explained 👉 Learn More
Adjacency Matrix vs List 👉 Learn More
BFS vs DFS 👉 Learn More
Detecting Cycle in Graph 👉 Learn More
Directed Acyclic Graph (DAG) 👉 Learn More
Topological Sorting 👉 Learn More
Dijkstra’s Algorithm 👉 Learn More
Prim’s vs Kruskal’s Algorithm 👉 Learn More
Union-Find / Disjoint Set 👉 Learn More
Hash Tables Explained 👉 Learn More
Hash Collision Handling 👉 Learn More
Open Addressing vs Chaining 👉 Learn More
Load Factor in Hashing 👉 Learn More
Static vs Dynamic Data Structures 👉 Learn More
Segment Trees 👉 Learn More
Share:

Tags:


Feedback Modal Popup