Skip to main content

Course Schedule II

Problem

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

  • For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.

Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.

Solution Approach

Make a directed graph from a[i]>b[i]a[i] -> b[i]. Then do a BFS to check if the graph is acyclic or not. If the graph is acyclic return then BFS traversal of the graph.

Expected Time complexity: O(n)O(n)

Click - to see solution code
#include <unordered_map>
#include <vector>
class Solution {
vector<vector<int>> G;
int N, ans = 1;
unordered_map<int, int> path;
vector<int> arr;

public:
void assign(int n) {
this->N = n;
G.resize(N);
}
void addedge(int x, int y) { G[x].push_back(y); }

void dfs(int cur, vector<int>& vis) {
if (ans == -1) return;
path[cur] = 1;
for (auto nbr : G[cur]) {
if (!vis[nbr] and path[nbr]) {
ans = -1;
return;
} else if (!vis[nbr]) {
dfs(nbr, vis);
}
}
vis[cur] = 1;
arr.push_back(cur);
}

vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
assign(numCourses);
for (auto i : prerequisites) {
addedge(i[0], i[1]);
}
vector<int> vis(N);
for (int i = 0; i < N; i++) {
vis[i] = 0;
}
for (int i = 0; i < N; i++) {
if (!vis[i]) {
path.clear();
dfs(i, vis);
if (ans == -1) {
arr.clear();
return arr;
}
}
}
return arr;
}
};