Prerequisite Tasks | Practice | GeeksforGeeks

There are a total of N tasks, labeled from 0 to N-1. Some tasks may have prerequisites, for example to do task 0 you have to first complete task 1, which is expressed as a pair: [0, 1]
Given the total number of tasks N and a list of prerequisite pairs P, find if it is possible to finish all tasks.

Example 1:
Input: 
N = 4, P = 3
prerequisites = {{1,0},{2,1},{3,2}}
Output:
Yes
Explanation:
To do task 1 you should have completed
task 0, and to do task 2 you should 
have finished task 1, and to do task 3 you 
should have finished task 2. So it is possible.

Example 2:
Input:
N = 2, P = 2
prerequisites = {{1,0},{0,1}}
Output:
No
Explanation:
To do task 1 you should have completed
task 0, and to do task 0 you should
have finished task 1. So it is impossible.


Your task:
You don’t need to read input or print anything. Your task is to complete the function isPossible() which takes the integer N denoting the number of tasks, P denoting the number of prerequisite pairs and prerequisite as input parameters and returns true if it is possible to finish all tasks otherwise returns false. 

Expected Time Complexity: O(N + P)
Expected Auxiliary Space: O(N + P)

Constraints:
1 ≤ N ≤ 104
1 ≤ P ≤ 105
0
shyamprakash8072 weeks ago
simple python solution using Khan's algorithm:
Time Taken : 2.12 / 3.58
 
from collections import dequeclass Solution:   def isPossible(self,n, p):       #code here       g = [[] for i in range(n)]       for i in p:           g[i[0]].append(i[1])       indeg = [0 for i in range(n)]       for i in range(n):           for j in g[i]:               indeg[j] += 1       q = deque()       st = []       for i in range(n):           if indeg[i] == 0:               q.append(i)       while len(q):           curr = q.popleft()           st.append(curr)           for adj in g[curr]:               indeg[adj] -= 1               if indeg[adj] == 0:                   q.append(adj)       return len(st)==n 
0
bhaskarmaheshwari81 month ago
bool isCycle(vector<int> adj[],int src,vector<int> &vis,vector<int> &temp)   {/// refer  https://www.youtube.com/watch?v=FK7VLwOU5oY       vis[src]=1;       temp[src]=1;       vector<int>::iterator itr;       for(itr=adj[src].begin();itr!=adj[src].end();itr++)       {           if(!vis[*itr])           {               if(isCycle(adj,*itr,vis,temp))               return 1;           }           else if(temp[*itr])           return 1;       }       temp[src]=0;       return 0;   }bool isPossible(int N, vector<pair<int, int> >& prerequisites) {    // Code here    vector<int> adj[N];    vector<int> vis(N,0);    vector<int> temp(N,0);    for(auto p:prerequisites)    {        adj[p.first].push_back(p.second);    }        for(int i=0;i<N;i++)    {        if(vis[i]==0)        {            if(isCycle(adj,i,vis,temp))            return 0;        }    }    return 1;        }
+1
sharmaaditya130641 month ago
Easy  C++ solution using KAHN'S ALGORITHM
 
bool isPossible(int n, vector<pair<int, int> >& preq) {    vector<vector<int>>adj(n);    vector<int>indegree(n,0);    for(auto it:preq){        adj[it.second].push_back(it.first);        indegree[it.first]++;    }    queue<int>q;    for(int i=0;i<n;i++)    {        if(indegree[i]==0){            q.push(i);        }    }    int count=0;    while(!q.empty()){        int node = q.front();        q.pop();        for(auto it:adj[node])        {            indegree[it]--;            if(indegree[it]==0){                q.push(it);            }        }        count++;            }    if(count==n)return true;    return false;}
0
tthakare732 months ago
//Java solution 
//hint :- check cycle using DFS

class Solution {
    public static boolean checkCycleDFS(ArrayList<ArrayList<Integer>> adj, int[] visited, int src) {
    	if(visited[src] == 0) {
    		return true;
    	}
    	
    	if(visited[src] == -1){
    	    visited[src] = 0;
        	for(Integer item: adj.get(src)) {
        		if(checkCycleDFS(adj, visited, item)) {
        			return true;
        		}
        	}   
    	}
    	
    	visited[src] = 1;
    	return false;
    }
    
    public static boolean isPossibless(int N, int[][] preQ) {
    	ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
    	for(int i = 0; i < N; i++) {
    		adj.add(new ArrayList<>());
    	}
    	
    	for(int i = 0; i < preQ.length; i++) {
    		int src = preQ[i][0];
    		int desc = preQ[i][1];
    		
    		adj.get(src).add(desc);
    	}
    	
    	int[] visited = new int[N];
    	Arrays.fill(visited, -1);
    	
    	for(int i = 0; i < N; i++) {
    		if(visited[i] == -1) {
    			if(checkCycleDFS(adj, visited, i)) {
    				return false;
    			}
    		}

    	}
    	
    	return true;
    }
    
    public boolean isPossible(int N, int[][] prerequisites)
    {
        // Your Code goes here
        return isPossibless(N, prerequisites);
    }
    
}
0
harshit2002162 months ago
bool isPossible(int N, vector<pair<int, int> >& prerequisites){   vector<int>adj[N];   for(int i=0;i<prerequisites.size();i++)   {       adj[prerequisites[i].second].push_back(prerequisites[i].first);   }   vector<int>indegree(N,0);   for(int i=0;i<N;i++)   {       for(int x:adj[i])       {           indegree[x]++;       }   }   queue<int>q;   for(int i=0;i<N;i++)   {       if(indegree[i]==0)       {           q.push(i);       }   }   int count=0;   while(!q.empty())   {       int curr=q.front();       q.pop();       for(int x : adj[curr])       {           if(--indegree[x]==0)               q.push(x);       }       count++;   }   return (count==N);}
0
rajatgarg212cd0162 months ago
// BFS SOLUTION USING INDEGREE
 
class Solution {public:bool isPossible(int n, vector<pair<int, int> >& prerequisites) {       vector<vector<int>> adj( n);      vector<int> indegree( n, 0);   for (auto &p: prerequisites) {       adj[p.second].push_back(p.first);       indegree[p.first]++;                                  }   queue<int> q;   for (int i = 0; i <  n; i++)       if (indegree[i] == 0)          q.push(i);   while (!q.empty()) {       int curr = q.front();        q.pop();        n--;            for (auto next: adj[curr])           {  indegree[next]--;if (indegree[next] == 0) q.push(next);}   }   return n == 0;              }};
0
shiva10902 months ago
bool isCycle(vector<int> adj[] , vector<int>& vis , int i)
    {
        if(vis[i] == 1){
            return true;
        }
        if(vis[i] == 0){
            vis[i] = 1;
            for(auto it: adj[i]){
                if(isCycle(adj , vis , it))return true;
            }
        }
        vis[i] = 2;
        return false;
    }
	bool isPossible(int N, vector<pair<int, int> >& p) {
	    // Code here
	    vector<int> adj[N];
	    for(auto it: p){
	        adj[it.second].push_back(it.first);
	    }
	    vector<int> vis(N,0);
	    for(int i = 0; i < N; i++)
	    {
	        if(vis[i] == 0){
	            if(isCycle(adj,vis,i))return false;
	        }
	    }
	    return true;
	}
0
hamidnourashraf2 months ago
class Solution:
    def dfs(self, i, adj, visited, onpath):
        if visited[i] != -1:
            return False
        visited[i] = 0
        onpath[i] = 0
        for ne in adj[i]:
            if onpath[ne] == 0:
                return True
            if self.dfs(ne, adj, visited, onpath):
                return True
        onpath[i] = -1
        return False
                
            
    def isPossible(self,N,prerequisites):
        adj = [[] for x in range(N)]
        for p in prerequisites:
            adj[p[1]].append(p[0]) 
        visited = [-1] * N
        onpath = [-1] * N
        for i in range(N):
            if visited[i] == -1:
                if self.dfs(i, adj, visited, onpath):
                    return False
        return True
+1
arthurshelby2 months ago
😉❄️🇮🇳✌️
bool iscycle(int node,vector<int>adj[],vector<int>&visited,vector<int>&order)
    {
        visited[node]=1;
        order[node]=1;
        for(auto it:adj[node])
        {
            if(visited[it]==0){
            if(iscycle(it,adj,visited,order)) return true;
            }
            else if(order[it]==1) return true;
        }
        order[node]=0;
        return false;
    }
	bool isPossible(int N, vector<pair<int, int> >& prerequisites) {
	    // Code here
	    vector<int>adj[N];
	    for(auto it:prerequisites)
	        adj[it.second].push_back(it.first);
	    vector<int>visited(N,0);
	    vector<int>order(N,0);
	    for(int i=0;i<N;i++)
	    {
	        if(visited[i]==0)
	        if(iscycle(i,adj,visited,order))
	        return false;
	    }
	    return true;
	   
	}
0
himanshukug19cs2 months ago
java sol
 
 static boolean[] vis;   static boolean[] dvis;   boolean sol(int V,ArrayList<ArrayList<Integer>> adj){       vis[V]=true;       dvis[V]=true;       for(int i:adj.get(V)){           if(vis[i]==false){               if(sol(i,adj))                  return true;           }           else if(dvis[i]==true)                return true;       }       dvis[V]=false;       return false;   }   public boolean isPossible(int N, int[][] prerequisites)   {       // Your Code goes here       vis = new boolean[N];       dvis = new boolean[N];       ArrayList<ArrayList<Integer>> adj = new ArrayList<>();       for(int i=0;i<N;i++){           adj.add(new ArrayList<>());       }       for(int i=0;i<prerequisites.length;i++){           adj.get(prerequisites[i][0]).add(prerequisites[i][1]);       }
       for(int i=0;i<N;i++){           vis[i]=false;       }       for(int i=0;i<N;i++){           dvis[i]=false;       }       //System.out.println(adj);       for(int i=0;i<N;i++){           if(vis[i]==false){           if(sol(i,adj))              return false;           }       }       return true;   }
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.