Topological sort or Kahn's algorithm

Graphs Cycles Hard
  • One interesting application of the topological sorting algorithm in real-world software development is in job scheduling
  • It helps to establish a sequence of tasks where some tasks are dependent on others being completed first
  • This algorithm helps in the correct priority-based execution of tasks for project management software and operating systems
  • Also, package managers use topological sorting to resolve dependencies between packages to ensure correct installation order

Given a Directed Acyclic Graph (DAG) with V vertices labeled from 0 to V-1.The graph is represented using an adjacency list where adj[i] lists all nodes connected to node. Find any Topological Sorting of that Graph.


In topological sorting, node u will always appear before node v if there is a directed edge from node u towards node v(u -> v).


The Output will be True if your topological sort is correct otherwise it will be False.

Examples:

Input: V = 6,adj=[ [ ], [ ], [3], [1], [0,1], [0,2] ]



Output: [5, 4, 2, 3, 1, 0]

Explanation: A graph may have multiple topological sortings. 

The result is one of them. The necessary conditions 

for the ordering are:

According to edge 5 -> 0, node 5 must appear before node 0 in the ordering.

According to edge 4 -> 0, node 4 must appear before node 0 in the ordering.

According to edge 5 -> 2, node 5 must appear before node 2 in the ordering.

According to edge 2 -> 3, node 2 must appear before node 3 in the ordering.

According to edge 3 -> 1, node 3 must appear before node 1 in the ordering.

According to edge 4 -> 1, node 4 must appear before node 1 in the ordering.


The above result satisfies all the necessary conditions. 

[4, 5, 2, 3, 1, 0] is also one such topological sorting 

that satisfies all the conditions.

Input: V = 4, adj=[ [ ], [0], [0], [0] ]



Output: [3, 2, 1, 0]

Explanation: The necessary conditions for the ordering are:

For edge 1 -> 0 node 1 must appear before node 0.

For edge 2 -> 0 node 1 must appear before node 0.

For edge 3 -> 0 node 1 must appear before node 0.

Input: V = 3, adj=[[1], [2]]

Constraints

  •  E=number of edges
  •  1 ≤ V, E ≤ 104

Hints

  • "Perform DFS on unvisited nodes. Push nodes to a stack after all their neighbors are visited (post-order traversal). The reverse of the stack gives a valid topological order."
  • "Maintain an in-degree array (count of incoming edges for each node). Start with nodes having 0 in-degree (no dependencies). Process each node and reduce the in-degree of its neighbors. Nodes whose in-degree becomes 0 are added to the queue."

Company Tags

Stripe MongoDB Bungie Activision Blizzard Chewy GE Healthcare Byju's Reddit OYO Rooms Docker Zomato Rakuten Cloudflare Databricks Bloomberg Oracle Target PwC eBay Walmart Uber Mastercard Epic Games Teladoc Health JPMorgan Chase Google Microsoft Amazon Meta Apple Netflix Adobe