Algo-Sim › Advanced Graphs
Course Schedule II
Medium · Advanced Graphs · step through it in Java, Python and C++ on your own input
Return an order to take all courses given prerequisite pairs, or [] if a cycle makes it impossible. Kahn's topological sort.
Problem
There are numCourses courses, and a pair [a, b] means b must be taken before a. Return any order in which all courses can be taken, or an empty array if a cycle makes it impossible.
Constraints
- 1 ≤ numCourses ≤ 2000
- 0 ≤ prerequisites.length ≤ numCourses · (numCourses − 1)
- All pairs are distinct; a ≠ b
Edge cases to test
- No prerequisites: any order
- A cycle:
[] - Disconnected groups of courses
Follow-up questions
- How do you get the lexicographically smallest order?
- Use a min-heap instead of a queue in Kahn’s algorithm: O(V log V + E).
- How do you find the fewest semesters?
- Process Kahn’s queue level by level; the number of levels is the answer (LC 1136).
Solution
Java
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[] indegree = new int[numCourses];
for (int[] p : prerequisites) {
adj.get(p[1]).add(p[0]);
indegree[p[0]]++;
}
Queue<Integer> queue = new ArrayDeque<>();
for (int i = 0; i < numCourses; i++) {
if (indegree[i] == 0) queue.offer(i);
}
int[] order = new int[numCourses];
int idx = 0;
while (!queue.isEmpty()) {
int course = queue.poll();
order[idx++] = course;
for (int next : adj.get(course)) {
if (--indegree[next] == 0) queue.offer(next);
}
}
return idx == numCourses ? order : new int[0];
}Python
from collections import deque
def find_order(num_courses, prerequisites):
adj = [[] for _ in range(num_courses)]
indegree = [0] * num_courses
for course, pre in prerequisites:
adj[pre].append(course)
indegree[course] += 1
queue = deque()
for i in range(num_courses):
if indegree[i] == 0:
queue.append(i)
order = []
while queue:
course = queue.popleft()
order.append(course)
for nxt in adj[course]:
indegree[nxt] -= 1
if indegree[nxt] == 0:
queue.append(nxt)
return order if len(order) == num_courses else []C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> findOrder(int numCourses, vector<vector<int>> &prerequisites) {
vector<vector<int>> adj = {};
for (int i = 0; i < numCourses; i++)
adj.push_back({});
vector<int> indegree = vector<int>(numCourses);
for (vector<int> &p : prerequisites) {
adj[p[1]].push_back(p[0]);
indegree[p[0]]++;
}
deque<int> queue = {};
for (int i = 0; i < numCourses; i++) {
if (indegree[i] == 0)
queue.push_back(i);
}
vector<int> order = vector<int>(numCourses);
int idx = 0;
while (!queue.empty()) {
int course = queue.front();
queue.pop_front();
order[idx++] = course;
for (int next : adj[course]) {
if (--indegree[next] == 0)
queue.push_back(next);
}
}
return idx == numCourses ? order : vector<int>(0);
}
};
More Advanced Graphs problems
- Network Delay Time (Medium)
- Evaluate Division (Medium)
- Alien Dictionary (Hard)
- Redundant Connection (Medium)
- Number of Connected Components (Union-Find) (Medium)
- Accounts Merge (Medium)
- Minimum Spanning Tree (Kruskal) (Medium)
- Minimum Spanning Tree (Prim) (Medium)
- Min Cost to Connect All Points (Medium)
- Cheapest Flights Within K Stops (Medium)
- Bellman-Ford (negative weights) (Medium)
- Find the City (Floyd-Warshall) (Medium)
- Critical Connections in a Network (Hard)
- Articulation Points (Cut Vertices) (Hard)
- Strongly Connected Components (Hard)
- Reconstruct Itinerary (Hard)
- Minimum Height Trees (Medium)