Approach Summary
Kahn's BFS. Process level by level (each level = one semester). Return number of levels if all nodes processed, else -1 (cycle).
Solve it yourself before revealing the code
DSA interviews test reasoning from brute force to optimal. Think through the constraints first.
Full Solution & Approach
To solve Parallel Courses optimally, we apply the topological sort algorithmic strategy. Kahn's BFS. Process level by level (each level = one semester). Return number of levels if all nodes processed, else -1 (cycle). A brute-force simulation or exhaustive search would lead to prohibitive polynomial or exponential time complexity, violating FAANG interview limits. Instead, the key algorithmic invariant is to maintain state incrementally across elements without redundant passes. We start by initializing our tracking structures and boundaries. As we iterate through the input dataset, each element is evaluated against our transition rules: whenever our target condition is met, we capture the current optimal state and update our tracking pointers or memoized lookup table. If the current state violates feasibility constraints, we systematically adjust our window, boundary, or search partition to restore validity. This structured progression guarantees that each state is examined in amortized O(V + E) time, utilizing O(V + E) auxiliary memory.
Time Complexity: O(V + E) — each element or state is traversed and evaluated in bounded amortized time without redundant reprocessing. Space Complexity: O(V + E) — allocated for auxiliary tracking structures, recursion call stack, or state caches.
Solution Code
Solution
import java.util.*;
class Solution {
// Time: O(V + E), Space: O(V + E)
public int[] parallelCourses(int numNodes, int[][] edges) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < numNodes; i++) adj.add(new ArrayList<>());
int[] indegree = new int[numNodes];
for (int[] edge : edges) {
adj.get(edge[0]).add(edge[1]);
indegree[edge[1]]++;
}
Queue<Integer> queue = new ArrayDeque<>();
for (int i = 0; i < numNodes; i++) {
if (indegree[i] == 0) queue.offer(i);
}
int[] order = new int[numNodes];
int idx = 0;
while (!queue.isEmpty()) {
int node = queue.poll();
order[idx++] = node;
for (int next : adj.get(node)) {
if (--indegree[next] == 0) queue.offer(next);
}
}
return idx == numNodes ? order : new int[0];
}
}#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
// Time: O(V + E), Space: O(V + E)
vector<int> parallelCourses(int numNodes, vector<vector<int>>& edges) {
vector<vector<int>> adj(numNodes);
vector<int> indegree(numNodes, 0);
for (const auto& edge : edges) {
adj[edge[0]].push_back(edge[1]);
indegree[edge[1]]++;
}
queue<int> q;
for (int i = 0; i < numNodes; ++i) {
if (indegree[i] == 0) q.push(i);
}
vector<int> order;
while (!q.empty()) {
int node = q.front(); q.pop();
order.push_back(node);
for (int next : adj[node]) {
if (--indegree[next] == 0) q.push(next);
}
}
return order.size() == numNodes ? order : vector<int>();
}
};from collections import deque, defaultdict
from typing import List
class Solution:
def parallel_courses(self, numNodes: int, edges: List[List[int]], *args) -> object:
# Time: O(V + E), Space: O(V + E)
adj = defaultdict(list)
indegree = [0] * numNodes
for u, v in edges:
adj[u].append(v)
indegree[v] += 1
queue = deque([i for i in range(numNodes) if indegree[i] == 0])
order = []
while queue:
node = queue.popleft()
order.append(node)
for neighbor in adj[node]:
indegree[neighbor] -= 1
if indegree[neighbor] == 0:
queue.append(neighbor)
return order if len(order) == numNodes else []var parallelCourses = function(numNodes, edges) {
const adj = Array.from({ length: numNodes }, () => []);
const indegree = new Array(numNodes).fill(0);
for (const [u, v] of edges) {
adj[u].push(v);
indegree[v]++;
}
const queue = [];
for (let i = 0; i < numNodes; i++) {
if (indegree[i] === 0) queue.push(i);
}
const order = [];
while (queue.length) {
const node = queue.shift();
order.push(node);
for (const next of adj[node]) {
indegree[next]--;
if (indegree[next] === 0) queue.push(next);
}
}
return order.length === numNodes ? order : [];
}; Edge Cases to Watch
- Key recognition trigger: "Minimum semesters to complete all courses given prerequisites".
- Constraint condition: Topological BFS counting levels = parallel rounds.
- Boundary constraints: handles negative values, large magnitudes, and extreme array limits seamlessly.
- Suboptimal inputs: runs strictly within the O(V + E) time budget without stack overflow or time limit exceeded.
Master the Topological Sort Pattern
Study the core invariant, step-by-step decision framework, and common interview traps for the Topological Sort pattern.
How to Recognize This Pattern
- "Minimum semesters to complete all courses given prerequisites"
- Topological BFS counting levels = parallel rounds
Complexity Analysis
Time Complexity
O(V + E)
Space Complexity
O(V + E)