Parallel Courses solution explained
Parallel Courses asks for the fewest terms needed to finish n courses when some courses must come before others and you may take any number of courses in one term. Treat courses as nodes and prerequisites as directed edges, then run Kahn's topological sort one layer at a time: each layer is one term, and if some courses are never freed the graph has a cycle and the answer is -1. It runs in O(n + E) time.
By Evin JohnPublished 8 min read
The problem in plain words
You have n courses numbered 1 to n and a list of pairs [a, b], each meaning course a must be finished before course b can start. A term is one round of study. In a term you may take as many courses as you like, as long as every prerequisite of each one was completed in an earlier term. Return the smallest number of terms that finishes all n courses, or -1 if no order can ever finish them.
| n and pairs | Answer | Why |
|---|---|---|
| n = 4, [[1,2],[2,4],[3,4]] | 3 | Term 1: courses 1 and 3. Term 2: course 2. Term 3: course 4, which waited for both 2 and 3 |
| n = 3, no pairs | 1 | Nothing depends on anything, so all three go in the first term |
| n = 4, [[1,2],[2,3],[3,2],[3,4]] | -1 | Courses 2 and 3 wait on each other and course 4 waits on 3, so only course 1 can ever be taken |
| n = 5, [[1,3],[2,3],[3,4],[3,5],[1,5]] | 3 | Terms {1, 2}, then {3}, then {4, 5}. The extra pair 1 before 5 adds no term because 5 already waits for 3 |
| n = 1, no pairs | 1 | A single course takes one term |
What the interviewer is checking
This is a topological sort problem with one twist: the question is not "give me an order" but "how many rounds". The interviewer wants to hear you model prerequisites as a directed graph, choose Kahn's algorithm, and realize that processing the queue one level at a time turns the order into a count. They also check that you detect a cycle instead of looping forever or returning a wrong number. A strong candidate adds that the answer equals the number of courses on the longest prerequisite chain.
Brute force: simulate term by term
Follow the story literally. Keep a set of finished courses. Each term, scan every unfinished course and collect the ones whose prerequisites are all in the finished set. If nothing qualifies while courses remain, you are stuck in a cycle. Otherwise mark the whole group finished at once (not one by one, or a course could ride on a prerequisite taken in the same term) and count the term. Each scan touches every course and every pair, and there can be up to n terms, so the cost is O(n × (n + E)).
def min_terms_slow(n, pairs):
needs = {c: [] for c in range(1, n + 1)}
for before, after in pairs:
needs[after].append(before)
done = set()
terms = 0
while len(done) < n:
ready = [c for c in range(1, n + 1)
if c not in done and all(p in done for p in needs[c])]
if not ready: # courses left, none can start: a cycle
return -1
done.update(ready) # the whole term finishes together
terms += 1
return termsOptimal: Kahn's algorithm, one layer per term
The simulation keeps re-checking courses that cannot possibly be ready. Kahn's algorithm tracks readiness directly. Count each course's unfinished prerequisites (its in-degree). Courses with an in-degree of zero form the first term. When a term finishes, walk the outgoing edges of each course in it and lower the in-degree of each course that depended on it. Any course that drops to zero joins the next term. Every course and every edge is handled once, so the whole run is O(n + E).
def min_terms(n, pairs):
unlocks = [[] for _ in range(n + 1)]
waiting = [0] * (n + 1) # unfinished prerequisites per course
for before, after in pairs:
unlocks[before].append(after)
waiting[after] += 1
this_term = [c for c in range(1, n + 1) if waiting[c] == 0]
taken = 0
terms = 0
while this_term:
terms += 1
taken += len(this_term)
next_term = []
for course in this_term:
for nxt in unlocks[course]:
waiting[nxt] -= 1
if waiting[nxt] == 0:
next_term.append(nxt)
this_term = next_term
return terms if taken == n else -1Using two lists, this term and the next, makes the level boundary explicit. A single queue works too if you record the queue length at the start of each term and pop exactly that many. The final check compares how many courses were taken with n. Courses inside a cycle, or downstream of one, never reach zero, so they are never taken.
function minTerms(n, pairs) {
const unlocks = Array.from({ length: n + 1 }, () => []);
const waiting = new Int32Array(n + 1);
for (const [before, after] of pairs) {
unlocks[before].push(after);
waiting[after]++;
}
let frontier = [];
for (let c = 1; c <= n; c++) if (waiting[c] === 0) frontier.push(c);
let taken = 0;
let terms = 0;
while (frontier.length > 0) {
terms++;
taken += frontier.length;
const next = [];
for (const course of frontier) {
for (const nxt of unlocks[course]) {
if (--waiting[nxt] === 0) next.push(nxt);
}
}
frontier = next;
}
return taken === n ? terms : -1;
}Why the layer count is the minimum
Layering takes every course as early as it is allowed, so no schedule can finish any course sooner. A course in layer k has a prerequisite in layer k - 1 (otherwise it would have been freed earlier), which has one in layer k - 2, and so on. That gives a chain of k courses where each must wait for the previous one, so any valid schedule needs at least k terms. The layering uses exactly that many. This is why the answer also equals the length of the longest path in the graph, counted in courses.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Term-by-term simulation | O(n × (n + E)) | O(n + E) |
| Layered Kahn's algorithm | O(n + E) | O(n + E) |
| DFS longest path with memo and cycle colors | O(n + E) | O(n + E) plus recursion depth |
The depth-first version computes, for each course, the longest chain ending there, and uses three colors (unvisited, in progress, finished) to spot a cycle. It is correct, but on a long chain the recursion can go n levels deep, which breaks Python's default limit. Kahn's version has no recursion, so it is the safer default in an interview.
Edge cases
- No pairs at all: one term, whatever n is.
- A course with no pairs touching it: it simply joins the first term.
- A cycle anywhere, even among a few courses, makes the answer -1 for the whole problem.
- A course that lists itself as a prerequisite: a one-node cycle, so -1. In-degree counting catches it naturally.
- The same pair given twice: the in-degree counts it twice and the course is freed after both edges are walked, so the answer is unchanged.
- A long chain 1 before 2 before 3 and so on: n terms, which is the worst case for the answer.
Common mistakes
- Counting nodes popped instead of levels, which returns n instead of the number of terms.
- Freeing a course and taking it in the same term, which happens when you push onto the same queue without tracking level boundaries.
- Forgetting the cycle check and returning the level count even though some courses were never taken.
- Indexing courses from 0 when they are numbered from 1, which drops course n or crashes.
- Using recursion for the longest-path idea and hitting the stack limit on a long chain.
Follow-up questions
- Return the schedule, not just the count. The layers themselves are the schedule: keep each term's list.
- Each course has its own length in months. The answer becomes the longest weighted path: carry each course's earliest finish time through Kahn's order and take the maximum.
- At most k courses per term. This version is much harder. Picking the right k courses matters, so greedy layering can fail, and the usual approach for small n is a dynamic program over subsets of finished courses. Say this out loud rather than reusing the plain solution.
- Which pairs are redundant? A pair a before c is redundant if another path from a to c exists. This leads into transitive reduction, which is a good discussion point rather than something to code.
How to explain it out loud
Fictional example
- Candidate
- Courses are nodes, and a pair a, b is an edge from a to b. I count how many prerequisites each course still waits on.
- Candidate
- Everything at zero can be taken in term one. When a term ends, I lower the count for courses that depended on it, and the ones that hit zero form the next term.
- Interviewer
- How do you know when it is impossible?
- Candidate
- If I run out of ready courses but have taken fewer than n, the rest are stuck behind a cycle, so I return minus one.
- Candidate
- Every node and edge is touched once, so it's linear. The number of terms equals the longest prerequisite chain.
Related problems
Sequence Reconstruction uses the same in-degree counting but asks whether the order is forced, which means the frontier must never hold more than one course. Redundant Connection II also works on a directed graph, finding the one edge that breaks a rooted tree. For level-by-level processing on a grid instead of a graph, Rotting Oranges counts minutes the same way this page counts terms.
Practicing it with Natively
The step worth drilling here is saying "levels, not nodes" before you write the loop. When you rehearse on a Mac or Windows PC, Natively can read a prerequisite list from a screenshot, suggest the layered Kahn's approach and the cycle check, and transcribe your explanation so you can confirm you mentioned the longest-chain argument. The LeetCode practice helper page shows how that works during a study session.
Questions people ask
How do you solve Parallel Courses?
Build a directed graph from the prerequisite pairs, count each course's in-degree, and run Kahn's algorithm one layer at a time. The number of layers is the number of terms; if fewer than n courses are taken, return -1.
Why does Parallel Courses return -1?
When prerequisites form a cycle, the courses in it, and any course that depends on them, never reach an in-degree of zero, so they can never be taken.
What is the time complexity of Parallel Courses?
O(n + E) time and space with layered Kahn's algorithm, since each course and each prerequisite pair is processed once.
Is the answer the longest path in the graph?
Yes. The minimum number of terms equals the number of courses on the longest prerequisite chain, which is exactly what the layer count measures.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
