[Geeks for Geeks] Prerequisite Tasks

Prerequisite Tasks

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.

  • Time : O(v + e)
  • Space : O(v + e)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
bool isPossible(int N, vector<pair<int, int>>& A) {
vector<int> ind(N);
vector<vector<int>> adj(N);

for(auto& p : A) {
int u = p.first, v = p.second;
adj[u].push_back(v);
ind[v]++;
}

queue<int> q;
for(int i = 0; i < N; i++)
if(ind[i] == 0) q.push(i);

while(!q.empty()) {
auto u = q.front(); q.pop();
for(auto& v : adj[u]) {
if(--ind[v] == 0)
q.push(v);
}
}

return accumulate(begin(ind), end(ind), 0) == 0;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/26/PS/GeeksforGeeks/prerequisite-tasks/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.