Course Schedule II
Course Schedule II is a medium graphs problem solved with the topological sort pattern.
The best approach, kahn's algorithm, runs in O(V + E) time and O(V + E) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from dfs postorder up.
Problem
Same setup as Course Schedule, but return an order in which you can take all courses. If it is impossible, return an empty array.
Examples
Example 1
- Input
numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]- Output
[0, 1, 2, 3] or [0, 2, 1, 3]
Example 2
- Input
numCourses = 2, prerequisites = [[0,1],[1,0]]- Output
[]
Constraints
1 <= numCourses <= 2000.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| DFS postorder | O(V + E) | O(V + E) |
| Kahn's algorithm | O(V + E) | O(V + E) |
1DFS postorder
O(V + E)O(V + E)DFS with three states. Append each course after all courses that depend on it are finished, then reverse. A back edge means no order exists.
- Edges b → a. On finish, add u to the list.
- Reverse; return empty on a cycle.
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < numCourses; i++) adj.add(new ArrayList<>());
for (int[] p : prerequisites) adj.get(p[1]).add(p[0]);
int[] state = new int[numCourses];
List<Integer> post = new ArrayList<>();
for (int i = 0; i < numCourses; i++)
if (state[i] == 0 && !dfs(i, adj, state, post)) return new int[0];
int[] out = new int[numCourses];
for (int i = 0; i < numCourses; i++) out[i] = post.get(numCourses - 1 - i);
return out;
}
private boolean dfs(int u, List<List<Integer>> adj, int[] state, List<Integer> post) {
state[u] = 1;
for (int v : adj.get(u)) {
if (state[v] == 1) return false;
if (state[v] == 0 && !dfs(v, adj, state, post)) return false;
}
state[u] = 2;
post.add(u);
return true;
}
}class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
adj = [[] for _ in range(numCourses)]
for p in prerequisites:
adj[p[1]].append(p[0])
state = [0] * numCourses
post = []
for i in range(numCourses):
if state[i] == 0 and not self.dfs(i, adj, state, post):
return []
return post[::-1]
def dfs(self, u: int, adj: List[List[int]], state: List[int], post: List[int]) -> bool:
state[u] = 1
for v in adj[u]:
if state[v] == 1:
return False
if state[v] == 0 and not self.dfs(v, adj, state, post):
return False
state[u] = 2
post.append(u)
return Trueclass Solution {
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> adj(numCourses);
for (auto& p : prerequisites) adj[p[1]].push_back(p[0]);
vector<int> state(numCourses, 0);
vector<int> post;
for (int i = 0; i < numCourses; i++)
if (state[i] == 0 && !dfs(i, adj, state, post)) return {};
vector<int> out(numCourses);
for (int i = 0; i < numCourses; i++) out[i] = post[numCourses - 1 - i];
return out;
}
private:
bool dfs(int u, vector<vector<int>>& adj, vector<int>& state, vector<int>& post) {
state[u] = 1;
for (int v : adj[u]) {
if (state[v] == 1) return false;
if (state[v] == 0 && !dfs(v, adj, state, post)) return false;
}
state[u] = 2;
post.push_back(u);
return true;
}
};function findOrder(numCourses, prerequisites) {
const adj = Array.from({ length: numCourses }, () => []);
for (const p of prerequisites) adj[p[1]].push(p[0]);
const state = new Array(numCourses).fill(0);
const post = [];
function dfs(u) {
state[u] = 1;
for (const v of adj[u]) {
if (state[v] === 1) return false;
if (state[v] === 0 && !dfs(v)) return false;
}
state[u] = 2;
post.push(u);
return true;
}
for (let i = 0; i < numCourses; i++)
if (state[i] === 0 && !dfs(i)) return [];
const out = new Array(numCourses);
for (let i = 0; i < numCourses; i++) out[i] = post[numCourses - 1 - i];
return out;
}2Kahn's algorithm
O(V + E)O(V + E)Output courses in the order they reach in-degree 0. If fewer than numCourses are output, a cycle blocked the rest.
- Queue zeros; pop into the order; decrement neighbours.
- Return the order if its size is numCourses, else an empty array.
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < numCourses; i++) adj.add(new ArrayList<>());
int[] indeg = new int[numCourses];
for (int[] p : prerequisites) { adj.get(p[1]).add(p[0]); indeg[p[0]]++; }
Queue<Integer> q = new ArrayDeque<>();
for (int i = 0; i < numCourses; i++) if (indeg[i] == 0) q.add(i);
int[] order = new int[numCourses];
int k = 0;
while (!q.isEmpty()) {
int u = q.poll();
order[k++] = u;
for (int v : adj.get(u)) if (--indeg[v] == 0) q.add(v);
}
return k == numCourses ? order : new int[0];
}
}class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
adj = [[] for _ in range(numCourses)]
indeg = [0] * numCourses
for p in prerequisites:
adj[p[1]].append(p[0])
indeg[p[0]] += 1
q = deque(i for i in range(numCourses) if indeg[i] == 0)
order = []
while q:
u = q.popleft()
order.append(u)
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
return order if len(order) == numCourses else []class Solution {
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> adj(numCourses);
vector<int> indeg(numCourses, 0);
for (auto& p : prerequisites) { adj[p[1]].push_back(p[0]); indeg[p[0]]++; }
queue<int> q;
for (int i = 0; i < numCourses; i++) if (indeg[i] == 0) q.push(i);
vector<int> order(numCourses);
int k = 0;
while (!q.empty()) {
int u = q.front(); q.pop();
order[k++] = u;
for (int v : adj[u]) if (--indeg[v] == 0) q.push(v);
}
return k == numCourses ? order : vector<int>();
}
};function findOrder(numCourses, prerequisites) {
const adj = Array.from({ length: numCourses }, () => []);
const indeg = new Array(numCourses).fill(0);
for (const p of prerequisites) { adj[p[1]].push(p[0]); indeg[p[0]]++; }
const q = [];
for (let i = 0; i < numCourses; i++) if (indeg[i] === 0) q.push(i);
const order = new Array(numCourses);
let k = 0;
let head = 0;
while (head < q.length) {
const u = q[head++];
order[k++] = u;
for (const v of adj[u]) if (--indeg[v] === 0) q.push(v);
}
return k === numCourses ? order : [];
}Edge cases to test
- A cycle (return an empty array)
- No prerequisites (any order)
Hints
Hint 1
It is Course Schedule, but you return the order Kahn's algorithm produces.
FAQ
What is the best time complexity for Course Schedule II?
Kahn's algorithm runs in O(V + E) time and O(V + E) extra space.
Which pattern does Course Schedule II use?
It is a graphs problem that uses the topological sort pattern. Other problems with the same pattern: Topological sort using BFS, Course Schedule, Alien Dictionary.
Is there a brute force solution for Course Schedule II?
Yes. DFS postorder takes O(V + E) time and O(V + E) space. DFS with three states.
Which edge cases should I test for Course Schedule II?
A cycle (return an empty array); No prerequisites (any order).