Topological sort | Practice | GeeksforGeeks

Given a Directed Acyclic Graph (DAG) with V vertices and E edges, Find any Topological Sorting of that Graph.

Example 1:
Input:

Output:
1
Explanation:
The output 1 denotes that the order is
valid. So, if you have, implemented
your function correctly, then output
would be 1 for all test cases.
One possible Topological order for the
graph is 3, 2, 1, 0.

Example 2:
Input:

Output:
1
Explanation:
The output 1 denotes that the order is
valid. So, if you have, implemented
your function correctly, then output
would be 1 for all test cases.
One possible Topological order for the
graph is 5, 4, 2, 1, 3, 0.

Your Task:
You don't need to read input or print anything. Your task is to complete the function topoSort()  which takes the integer V denoting the number of vertices and adjacency list as input parameters  and returns an array consisting of a the vertices in Topological order. As there are multiple Topological orders possible, you may return any of them. If your returned topo sort is correct then console output will be 1 else 0.

Expected Time Complexity: O(V + E).
Expected Auxiliary Space: O(V).

Constraints:
2  ≤  V  ≤ 104
1  ≤  E  ≤  (N*(N-1))/2
0
thakuraditya6211 day ago
// Java Code 
 static int[] topoSort(int V, ArrayList<ArrayList<Integer>> adj) 
    {
        // add your code here
        boolean[] visited = new boolean[V];
        Stack<Integer> st = new Stack<>();
        
        for(int i  =0; i < V; i++){
            if(!visited[i]){
                DFS(adj, visited, st, i);
            }
        }
        int [] ans = new int[V];
        int i = 0;
        while(!st.isEmpty()){
            ans[i++] = st.pop();
        }
        return ans;
    }
    
    private static void DFS(ArrayList<ArrayList<Integer>> adj, boolean[] visited, Stack<Integer> st, int src){
        visited[src]  = true;
        
        for(Integer nbr : adj.get(src)){
            if(!visited[nbr]){
                DFS(adj, visited, st, nbr);
            }
        }
        st.push(src);
    }
0
harshscode1 week ago
	vector<int> topoSort(int v, vector<int> adj[]) 
	{
	 
	  vector<int> in(v,0);
	  vector<int> ans;
	  queue<int> q;
	 
	  for(int i=0;i<v;i++)
	  {
	      for(auto x:adj[i])
	      in[x]++;
	  }
	  for(int i=0;i<v;i++)
	     { if(in[i]==0)
	      q.push(i);
	     }
	  while(!q.empty())
	  {
	      int t=q.front();
	       q.pop();
	       ans.push_back(t);
	       for(auto x:adj[t])
	       {
	          
	               in[x]--;
	               if(in[x]==0)
	               q.push(x);
	  
	               
	        }
	     }
	   return ans;
	}
+1
amishasahu3282 weeks ago
void dfsTopoSort(int u, vector<int> adj[], vector<int> &visited, stack<int> &st)
	{
	    visited[u] = 1;
	    for(auto v : adj[u])
	    {
	        if(!visited[v])
	            dfsTopoSort(v, adj, visited, st);
	    }
	    st.push(u);
	}
	vector<int> topoSort(int V, vector<int> adj[]) 
	{
	    // code here
	    vector<int> visited(V, 0);
	    stack<int> st;
	    for(int i = 0; i < V; i++)
	    {
	        if(!visited[i])
	            dfsTopoSort(i, adj, visited, st);
	    }
	    
	    vector<int> topo;
	    while(!st.empty())
	    {
	        topo.push_back(st.top());
	        st.pop();
	    }
	    return topo;
	}
0
udaytyagi01232 weeks ago
//1. Add all vertices to map//2. count indegree of all nodes//3. find the nodes with indegree zero and add them to queue//4. now traverse till queue is not empty and when indegree of node becomes zero add it to your answer vectorvector<int> topoSort(int V, vector<int> adj[]) {    vector<int>ans;    unordered_map<int,int>m;    queue<int>q;   // 1. Add all vertices to map    for(int i=0;i<V;i++)    {        m[i]=0;    }   // 2. count indegree of all nodes    for(int i=0;i<V;i++)    {        for(auto p:adj[i])        {           m[p]++;//counting indegree        }    }   // 3. find the nodes with indegree zero and add them to queue    for(auto p:m)    {        if(p.second==0)        {            q.push(p.first);        }    }   // 4. now traverse till queue is not empty and when indegree of node becomes zero add it to your answer vector    while(!q.empty())    {        int temp=q.front();        q.pop();        ans.push_back(temp);        for(auto p:adj[temp])        {                m[p]--;                if(m[p]==0)                {                    q.push(p);                }        }    }    return ans;}
0
amanasati12 weeks ago
We use a temporary stack. Don’t print the vertex immediately, we first recursively call topological sorting for all its adjacent vertices, then push it to a stack. Finally, print contents of the stack.
class Solution:
    
    #Function to return list containing vertices in Topological order.
    def dfsutil(self,node,adj,vis,stack):
        vis[node]=True
        for z in adj[node]:
            if not vis[z]:
                self.dfsutil(z,adj,vis,stack)
        # Push current vertex to stack which stores result
        stack.append(node)
        
                
    def topoSort(self, V, adj):
        # Code here
        vis=[False]*V
        stack=[]
        for i in range(V):
            if not vis[i]:
                self.dfsutil(i,adj,vis,stack)
        rev=stack[::-1]
        return rev
0
shivam1706203 weeks ago
Kahns Algorithm using BFS
 
 vector<int> topoSort(int V, vector<int> adj[]) {     // using kahns algorithm       vector<int> indegree(V , 0);      for(int i=0;i<V;i++)   {       for(int j=0;j<adj[i].size();j++)       {           indegree[adj[i][j]]++;       }   }      queue<int> q;      for(int i=0;i<V;i++)   {       if(indegree[i]==0)       {           q.push(i);       }   }      vector<int> ans;      while(!q.empty())   {       int x=q.front();       q.pop();              ans.push_back(x);              for(int i=0;i<adj[x].size();i++)       {           indegree[adj[x][i]]--;           if(indegree[adj[x][i]]==0)           {               q.push(adj[x][i]);           }       }   }      return ans;    }
0
gfgraj3 weeks ago
// { Driver Code Starts#include <bits/stdc++.h>using namespace std;
// } Driver Code Endsclass Solution{public://Function to return list containing vertices in Topological order. void toposort(int i,vector<bool>&v,stack<int>&s,vector<int>adj[]){        v[i]=1;        for(auto j:adj[i]){            if(!v[j]){                toposort(j,v,s,adj);            }                    }        s.push(i);}vector<int> topoSort(int V, vector<int> adj[]) {    stack<int>s;    vector<bool>v(V,0);      vector<int>ans;   for(int i=0;i<V;i++){       if(!v[i]){           toposort(i,v,s,adj);       }   }   while(!s.empty()){       ans.push_back(s.top());       s.pop();   }   return ans;}};
// { Driver Code Starts.
/*  Function to check if elements returned by user*   contains the elements in topological sorted form*   V: number of vertices*   *res: array containing elements in topological sorted form*   adj[]: graph input*/int check(int V, vector <int> &res, vector<int> adj[]) {      if(V!=res.size())   return 0;      vector<int> map(V, -1);   for (int i = 0; i < V; i++) {       map[res[i]] = i;   }   for (int i = 0; i < V; i++) {       for (int v : adj[i]) {           if (map[i] > map[v]) return 0;       }   }   return 1;}
int main() {   int T;   cin >> T;   while (T--) {       int N, E;       cin >> E >> N;       int u, v;
       vector<int> adj[N];
       for (int i = 0; i < E; i++) {           cin >> u >> v;           adj[u].push_back(v);       }              Solution obj;       vector <int> res = obj.topoSort(N, adj);
       cout << check(N, res, adj) << endl;   }      return 0;}  // } Driver Code Ends
0
milindprajapatmst193 weeks ago
class Solution {
	public:
	vector<int> visited, result;
	void dfs(int u, vector<int> adj[]) {
	    visited[u] = true;
	    for (int v : adj[u]) {
	        if (visited[v] == false)
	            dfs(v, adj);
	    }
	   result.push_back(u);
	}
	vector<int> topoSort(int n, vector<int> adj[]) {
	    visited.resize(n);
	    visited.assign(n, 0);
	    for (int u = 0; u < n; u++) {
	        if (visited[u] == false)
	            dfs(u, adj);
	    }
	    reverse(result.begin(), result.end());
	    return result;
	}
};
+1
pikucode154 weeks ago
class Solution{public://Function to return list containing vertices in Topological order.void dfs(int node,vector<int> adj[],vector<bool>& vis,stack<int>& topo){    vis[node]=true;    for(auto x: adj[node])        if(!vis[x])            dfs(x,adj,vis,topo);    topo.push(node);}vector<int> topoSort(int V, vector<int> adj[]) {    vector<bool> vis;    vector<int> ans;    stack<int> topo;    for(int i=0;i<V;i++)        vis.push_back(false);    for(int i=0;i<V;i++)        if(!vis[i])            dfs(i,adj,vis,topo);    while(!topo.empty())    {        ans.push_back(topo.top());        topo.pop();    }    return ans;}};
0
sunnyguta123454 weeks ago
JAVA BFS
class Solution{   //Function to return list containing vertices in Topological order.    static int[] topoSort(int V, ArrayList<ArrayList<Integer>> adj)   {      int indegree[]=new int[V];      for(ArrayList<Integer>temp:adj){          for(int i:temp){              indegree[i]++;          }      }      ArrayList<Integer>ans=new ArrayList<>();    bfs(adj,indegree,ans);      int finalans[]=new int[V];      int i=0;      for(int j:ans){          finalans[i++]=j;      }      return finalans;  } static void bfs(ArrayList<ArrayList<Integer>> adj,int in[],ArrayList<Integer>ans){          Queue<Integer>q=new LinkedList<>();     for(int i=0;i<in.length;i++){         if(in[i]==0){             q.add(i);         }     }     while(q.size()>0){         int temp=q.poll();         ans.add(temp);         for(int i:adj.get(temp)){             in[i]--;             if(in[i]==0){                 q.add(i);             }         }     }  }}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.