Course Schedule II solution explained
Course Schedule II asks for an actual order that respects every prerequisite, or an empty list when none exists. Produce a topological order: either record tasks as they become free in Kahn's algorithm, or run a depth-first search and reverse the order in which tasks finish. Both run in O(V + E), and any valid order is accepted unless the interviewer asks for a specific one.
By Evin JohnPublished 9 min read
The problem, in plain terms
A release has n tasks numbered 0 to n - 1. Some tasks block others, given as pairs [a, b], where task b must be finished before task a. Return a list containing every task exactly once, arranged so that each task comes after all of its blockers. If the blockers form a loop and no such list exists, return an empty list.
n = 4 (0 = design, 1 = build, 2 = test, 3 = write docs)
pairs = [[1, 0], [2, 1], [3, 0]]
design -> build -> test
design -> write docs
Valid answers: [0, 1, 2, 3] [0, 1, 3, 2] [0, 3, 1, 2]
Invalid: [1, 0, 2, 3] (build before design)Three different lists are all correct here, because writing docs only depends on design and can slot in anywhere after it. That is the first thing to say out loud: the problem has many answers, so the code only has to produce one of them, and your tests should check the rules rather than one exact list. Add pair [0, 2] (design waits on test) and the plan becomes a loop, so the answer is an empty list.
This is the sibling of Course Schedule, which only asks whether an order exists. Here direction matters. If you build the arrows backwards, the yes or no answer stays the same but the list you return comes out reversed and wrong, so confirm which side of each pair is the blocker before writing anything.
How to check an answer
Write the checker first, both for your own testing and because it shows the interviewer you know what correct means. An order is valid when it is a permutation of 0 to n - 1 and, for every pair, the blocker's position is smaller than the dependent task's position.
def is_valid_order(n, pairs, order):
if sorted(order) != list(range(n)):
return False
slot = {task: i for i, task in enumerate(order)}
return all(slot[blocker] < slot[task] for task, blocker in pairs)The brute force: try every arrangement
The most literal answer generates every permutation of the tasks and returns the first one the checker accepts, or an empty list if none passes. It is plainly correct and plainly hopeless: n tasks have n! arrangements, so even twelve tasks means hundreds of millions of candidates. It is still worth one sentence, because it frames the real question: how do you build a valid arrangement directly instead of searching for one?
Optimal approach 1: reverse the DFS finishing order
Run a depth-first search along the arrows from blockers to the tasks they unblock. A task is declared finished only after every task reachable from it has finished. So in the list of finishing times, each task appears after everything that depends on it. Reverse that list and every blocker now comes first. The same three states used for cycle detection still apply: if the search reaches a task that is still active on the current path, the plan has a loop and the answer is empty.
def find_order(n, pairs):
followers = [[] for _ in range(n)]
for task, blocker in pairs:
followers[blocker].append(task)
NEW, ACTIVE, DONE = 0, 1, 2
color = [NEW] * n
finished = [] # tasks in the order their search completes
for start in range(n):
if color[start] != NEW:
continue
color[start] = ACTIVE
stack = [(start, iter(followers[start]))]
while stack:
task, edges = stack[-1]
nxt = next(edges, None)
if nxt is None:
color[task] = DONE
finished.append(task)
stack.pop()
elif color[nxt] == ACTIVE:
return []
elif color[nxt] == NEW:
color[nxt] = ACTIVE
stack.append((nxt, iter(followers[nxt])))
finished.reverse()
return finishedStoring a live iterator in each stack frame is what makes the iterative version easy to read: the frame remembers which follower it will try next, just as a recursive call would remember its loop position. A task that no pair mentions is started, has no followers, and finishes immediately, so it still lands in the output.
Optimal approach 2: record Kahn's queue
Count how many blockers each task still has. Put every task with zero blockers in a queue. Each time a task leaves the queue, append it to the answer and lower the count of every task it unblocks; tasks that reach zero join the queue. If the answer holds all n tasks at the end, return it. If it is short, some tasks never reached zero because they sit in a loop or behind one, so return an empty list.
#include <queue>
#include <utility>
#include <vector>
std::vector<int> findOrder(int n, const std::vector<std::pair<int, int>>& pairs) {
std::vector<std::vector<int>> unblocks(n);
std::vector<int> blockers(n, 0);
for (const auto& [task, blocker] : pairs) {
unblocks[blocker].push_back(task);
++blockers[task];
}
std::queue<int> avail;
for (int t = 0; t < n; ++t)
if (blockers[t] == 0) avail.push(t);
std::vector<int> order;
order.reserve(n);
while (!avail.empty()) {
int t = avail.front();
avail.pop();
order.push_back(t);
for (int u : unblocks[t])
if (--blockers[u] == 0) avail.push(u);
}
if (static_cast<int>(order.size()) != n) order.clear();
return order;
}The two methods usually return different lists for the same input, and both are right. Kahn's version tends to start with every task that is free from the beginning, while the reversed DFS order follows one chain of dependencies deep before it backs out. If an interviewer asks which to pick, either is fine; Kahn's is easier to extend to the follow-ups below.
Complexity summary
| Approach | Time | Extra space |
|---|---|---|
| Try every permutation | O(V! × (V + E)) | O(V + E) |
| Reversed DFS finishing order | O(V + E) | O(V + E) for the lists, colors and stack |
| Kahn's algorithm with a queue | O(V + E) | O(V + E) |
| Kahn's with a min-heap, smallest order | O(V log V + E) | O(V + E) |
Follow-ups interviewers add
- Return the alphabetically smallest valid order. Replace Kahn's queue with a min-heap so the smallest free task always goes next. Greedy is safe here because taking the smallest available task never blocks a choice you would have preferred later.
- How many rounds if independent tasks can run at the same time? Process Kahn's queue one whole layer per round. The number of rounds is the length of the longest dependency chain.
- Is the valid order unique? It is unique exactly when Kahn's queue never holds more than one task at a time.
- Which tasks are part of the loop? After Kahn's stalls, the leftovers include the loop and everything behind it. To report just the loop, run the three-state search and, when it hits an active task, read the stack back to that task.
- New blocking pairs arrive after the order is built. A pair that already agrees with the order changes nothing. Otherwise the order has to be repaired or rebuilt, and checking for a new loop comes first.
import heapq
def smallest_order(n, pairs):
unblocks = [[] for _ in range(n)]
left = [0] * n
for task, blocker in pairs:
unblocks[blocker].append(task)
left[task] += 1
free = [t for t in range(n) if left[t] == 0]
heapq.heapify(free)
order = []
while free:
t = heapq.heappop(free)
order.append(t)
for u in unblocks[t]:
left[u] -= 1
if left[u] == 0:
heapq.heappush(free, u)
return order if len(order) == n else []Edge cases to try
- No pairs: any arrangement of 0 to n - 1 is valid, including the plain sorted one.
- A task blocked by itself: return an empty list.
- One pair repeated several times: the order is unaffected.
- A loop in one corner of the plan while the rest is fine: still an empty list, not a partial order.
- Tasks that appear in no pair: they must still be in the answer.
- A long single chain: one valid answer only, and a test of stack depth.
Common mistakes
- Returning the DFS finishing order without reversing it, which puts every dependent task before its blocker.
- Appending a task to the answer when the search first enters it, which is preorder and can break the rules on branching plans.
- Returning the partial list from Kahn's algorithm when it stalls instead of an empty list.
- Writing tests that expect one specific list and then chasing a bug that is not there.
- Flipping the pair direction while building the edges, which silently produces a reversed order.
How to explain it out loud
Fictional example
- Candidate
- Edges go from a blocker to the task it unblocks. I want a topological order, and I will return an empty list if I find a loop.
- Candidate
- In a depth-first search, a task finishes only after everything downstream of it has finished. So the finishing list has every dependent before its blocker, and reversing it gives a valid order.
- Candidate
- I keep three colors so I can spot a loop: reaching a task that is still active means I walked in a circle. Total work is linear in tasks plus pairs.
- Interviewer
- Your answer differs from mine. Is yours wrong?
- Candidate
- Probably not, since several orders are valid. Let me run it through the checker: every task appears once and each blocker sits earlier than its task, so both are correct.
Related problems
Start with Course Schedule if the cycle check is new to you. Graph Valid Tree moves to undirected edges and asks whether the graph is one connected piece without loops, and Number of Connected Components counts the pieces. The data structure interview questions guide covers adjacency lists, queues and heaps in more depth.
Using Natively while you practice
Ordering problems reward a clear explanation of why the answer is correct, not just code that compiles. Natively runs on Mac and Windows and, during a practice session, can read a dependency problem from a screenshot and sketch an approach in the overlay, for example Kahn's queue versus a reversed DFS, along with a checker you can test against. Afterward the transcript of your mock round shows whether you explained why many orders are valid. The page on an AI interview assistant has the details.
Questions people ask
How do you solve Course Schedule II?
Build edges from each prerequisite to the course it unlocks, then produce a topological order. Kahn's algorithm records courses as their pending count reaches zero; a DFS records finishing order and reverses it. Return an empty list if a cycle stops either one.
Why is the DFS finishing order reversed?
A node finishes only after everything reachable from it has finished, so dependents appear before their prerequisites in finishing order. Reversing the list puts every prerequisite first.
Can Course Schedule II have more than one correct answer?
Yes. Whenever two courses do not depend on each other, either can go first. Test with a checker that confirms each course appears once and every prerequisite comes earlier.
How do you get the lexicographically smallest course order?
Use Kahn's algorithm with a min-heap instead of a queue, so the smallest available course is always taken next. That costs O(V log V + E).
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.
