Problem
Return one valid order in which to take all courses, given the same prerequisite list as Course Schedule. If no such order exists, return an empty array.
Original: LeetCode 210: Course Schedule II.
Examples
Example 1
`numCourses = 2, prerequisites = [[1, 0]]``[0, 1]`Example 2
`numCourses = 4, prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]]``[0, 1, 2, 3]`[0, 2, 1, 3] is also valid; any topological order is accepted.
Example 3
`numCourses = 1, prerequisites = []``[0]`Constraints
1 <= numCourses <= 20000 <= prerequisites.length <= numCourses * (numCourses - 1)prerequisites[i].length == 20 <= ai, bi < numCoursesai != bi- All the pairs
[ai, bi]are distinct.
Hints
Hint 1
This is Course Schedule, plus the actual permutation. Several answers can be correct when the graph has more than one valid order.
Hint 2
A topological order is exactly the sequence Kahn's algorithm emits while it peels off indegree-zero nodes.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Search all permutations and test the prerequisites, which is not usable at interview sizes.
Optimal. Build the graph, queue every indegree-zero course, and append each dequeued course to the answer while reducing neighbour degrees.
Alternative. A DFS post-order, then reversed, also produces a topological order, with a cycle check on the current path.
Complexity
- Time
- O(V + E)
O(V + E) time and O(V + E) space.
- Space
- O(V + E)
Code
from collections import defaultdict, deque
def find_order(num_courses: int, prerequisites: list[list[int]]) -> list[int]:
graph = defaultdict(list)
indeg = [0] * num_courses
for a, b in prerequisites:
graph[b].append(a)
indeg[a] += 1
q = deque(i for i in range(num_courses) if indeg[i] == 0)
order: list[int] = []
while q:
u = q.popleft()
order.append(u)
for v in graph[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
return order if len(order) == num_courses else []
def valid(order, n, pre):
if len(order) != n:
return False
pos = {c: i for i, c in enumerate(order)}
return all(pos[b] < pos[a] for a, b in pre)
if __name__ == "__main__":
assert valid(find_order(2, [[1, 0]]), 2, [[1, 0]])
pre = [[1, 0], [2, 0], [3, 1], [3, 2]]
assert valid(find_order(4, pre), 4, pre)
assert find_order(1, []) == [0]
print("ok")import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
public class CourseScheduleII {
static int[] findOrder(int numCourses, int[][] prerequisites) {
List<List<Integer>> graph = new ArrayList<>();
int[] indeg = new int[numCourses];
for (int i = 0; i < numCourses; i++) graph.add(new ArrayList<>());
for (int[] p : prerequisites) {
graph.get(p[1]).add(p[0]);
indeg[p[0]]++;
}
var q = new ArrayDeque<Integer>();
for (int i = 0; i < numCourses; i++) if (indeg[i] == 0) q.add(i);
int[] order = new int[numCourses];
int taken = 0;
while (!q.isEmpty()) {
int u = q.remove();
order[taken++] = u;
for (int v : graph.get(u)) if (--indeg[v] == 0) q.add(v);
}
return taken == numCourses ? order : new int[0];
}
static boolean valid(int[] order, int n, int[][] pre) {
if (order.length != n) return false;
int[] pos = new int[n];
for (int i = 0; i < n; i++) pos[order[i]] = i;
for (int[] p : pre) if (pos[p[1]] >= pos[p[0]]) return false;
return true;
}
public static void main(String[] args) {
if (!valid(findOrder(2, new int[][] {{1, 0}}), 2, new int[][] {{1, 0}})) throw new AssertionError();
int[][] pre = {{1, 0}, {2, 0}, {3, 1}, {3, 2}};
if (!valid(findOrder(4, pre), 4, pre)) throw new AssertionError();
if (findOrder(1, new int[][] {}).length != 1) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples include two courses with [[1,0]], which yields [0,1]; four courses with [[1,0],[2,0],[3,1],[3,2]], which may yield [0,1,2,3] or [0,2,1,3]; and a single course with no prerequisites, which yields [0].
- A cycle should return an empty array.
Follow-ups
- If the interviewer wants a deterministic order, you can use a min-heap of indegree-zero courses instead of a queue.
Interview script
"I already have a cycle check from Course Schedule. I just record the order in which Kahn's algorithm takes the courses, and I return that list if every course was taken."
Source: LeetCode 210: Course Schedule II
Sources (1)
- LeetCode 210: Course Schedule IIleetcode.com