Course Schedule solution explained
Course Schedule asks whether every course can be finished when some courses must come before others, which is the same as asking whether a directed graph has a cycle. Count how many prerequisites each course still waits on, repeatedly take a course that waits on nothing, and if every course gets taken the plan works. The solution runs in O(V + E) time for V courses and E prerequisite pairs.
By Evin JohnPublished 10 min read
The problem, in plain terms
A training program has n modules, numbered 0 to n - 1. Some modules depend on others. Each dependency arrives as a pair [a, b], which means module b has to be completed before module a can start. Is there any order in which a learner can complete every module? Return true or false. You do not need the order itself, only whether one exists.
Plan A: n = 4, pairs = [[1, 0], [2, 1], [3, 2]]
0 -> 1 -> 2 -> 3 answer: true
Plan B: n = 3, pairs = [[0, 1], [1, 2], [2, 0]]
0 needs 1, 1 needs 2, 2 needs 0 answer: false
Plan C: n = 5, pairs = [[2, 0], [2, 1], [4, 3]]
two separate groups, no loop answer: truePlan A is a straight chain, so the only order is 0, 1, 2, 3. Plan B is a loop: every module is waiting on another module in the same circle, so nobody can start. Plan C has modules with no dependencies at all and two groups that never touch, which is still fine. A module with no pairs mentioning it can simply be taken whenever.
Before planning, confirm three things with the interviewer. First, which side of each pair is the prerequisite; getting it backwards is harmless for this yes or no question but fatal for the follow-up. Second, whether a pair can repeat or point a module at itself. Third, how large n and the pair list can be, because that decides whether a recursive search is safe.
Why interviewers like this problem
The prompt never says graph, cycle or topological sort. The interviewer wants to see you translate a scheduling story into nodes and directed edges on your own, then pick a traversal that detects a loop. It also exposes a classic bug: a depth-first search that only remembers whether a node was ever visited will report false loops on harmless diamond shapes. Expect questions about that distinction, and about what changes when the interviewer wants the actual order.
A slow but honest first answer
Simulate a student. Keep a set of finished modules. Sweep through every module that is not finished and check whether all of its prerequisites are in the set; if so, finish it. Keep sweeping until a full pass finishes nothing new. If the set now holds all n modules, the answer is true.
def can_finish_slow(n, pairs):
finished = set()
changed = True
while changed:
changed = False
for module in range(n):
if module in finished:
continue
if all(before in finished for after, before in pairs if after == module):
finished.add(module)
changed = True
return len(finished) == nEach sweep checks every module against the whole pair list, which is O(V × E), and a long chain can need up to V sweeps, so the worst case is about O(V² × E). The waste is obvious once you say it out loud: every sweep rechecks modules whose situation has not changed. The fix is to track, for each module, how many prerequisites it is still waiting on, and to update only the modules affected when something finishes.
Optimal approach 1: peel off ready courses (Kahn's algorithm)
Build two things from the pairs: for each module, the list of modules it unlocks, and a counter of how many prerequisites it still waits on. Put every module whose counter is zero into a queue. Repeatedly take one out, count it as completed, and decrement the counter of everything it unlocks. When a counter hits zero, that module joins the queue. If the loop completes all n modules, there is no cycle. If it stalls early, the leftovers are each waiting on someone in a loop, or on something downstream of a loop.
from collections import deque
def can_finish(n, pairs):
unlocks = [[] for _ in range(n)]
waiting_on = [0] * n
for after, before in pairs:
unlocks[before].append(after)
waiting_on[after] += 1
ready = deque(m for m in range(n) if waiting_on[m] == 0)
completed = 0
while ready:
module = ready.popleft()
completed += 1
for nxt in unlocks[module]:
waiting_on[nxt] -= 1
if waiting_on[nxt] == 0:
ready.append(nxt)
return completed == nDuplicate pairs are handled for free: a repeated pair adds one to the counter and one extra entry to the unlock list, so they cancel out. A pair that points a module at itself raises its counter to one and nothing ever lowers it, so the function correctly returns false.
Optimal approach 2: depth-first search with three states
The other standard answer walks the arrows depth first and gives each module one of three states: untouched, on the current path, or fully explored. Reaching a module that is on the current path means you have walked in a circle, so there is a cycle. Reaching a fully explored module is fine; its whole downstream was already checked and found clean. The version below keeps its own stack instead of recursing, so a chain of a hundred thousand modules does not hit a recursion limit.
function canFinish(n, pairs) {
const unlocks = Array.from({ length: n }, () => []);
for (const [after, before] of pairs) unlocks[before].push(after);
// 0 = untouched, 1 = on the current path, 2 = fully explored
const state = new Array(n).fill(0);
for (let root = 0; root < n; root++) {
if (state[root] !== 0) continue;
state[root] = 1;
const frames = [[root, 0]];
while (frames.length > 0) {
const frame = frames[frames.length - 1];
const node = frame[0];
if (frame[1] < unlocks[node].length) {
const next = unlocks[node][frame[1]];
frame[1] += 1;
if (state[next] === 1) return false;
if (state[next] === 0) {
state[next] = 1;
frames.push([next, 0]);
}
} else {
state[node] = 2;
frames.pop();
}
}
}
return true;
}Why three states and not two? Picture module 3 that needs both 1 and 2, where 1 and 2 each need 0. A search from 0 reaches 3 through 1, finishes, then reaches 3 again through 2. With a single visited flag, that second arrival looks like a loop. With three states, 3 is already marked fully explored, which correctly means no loop through it.
Complexity summary
| Approach | Time | Extra space | Notes |
|---|---|---|---|
| Repeated sweeps | O(V² × E) worst case | O(V) | Fine as a test oracle, too slow for big inputs |
| Kahn's algorithm | O(V + E) | O(V + E) | No recursion; also yields an order if you record it |
| Three-state DFS, explicit stack | O(V + E) | O(V + E) | Finds the cycle as soon as it closes |
| Three-state DFS, recursive | O(V + E) | O(V + E) plus call stack | Shortest code; risky on long chains |
Edge cases to try
- No pairs at all: every module is free, so the answer is true.
- A single module that lists itself as its own prerequisite: false.
- The same pair repeated several times: no effect on the answer.
- Two modules that each require the other: the smallest possible loop, false.
- A loop hidden in one component while other components are clean: still false.
- A diamond where two paths lead to the same module: true, and a trap for two-state searches.
- A very long chain: true, and a check that your search does not overflow the stack.
Mistakes that cost candidates the round
- Using one visited flag in the DFS and calling every revisit a cycle.
- Starting the search only from module 0, so loops in other components go unnoticed.
- Counting processed pairs instead of processed modules at the end of Kahn's algorithm.
- Sizing the lists from the largest module number seen in the pairs instead of from n, which drops modules no pair mentions.
- Forgetting to mark a module as fully explored after its last edge, so the next root's search runs into a stale on-path mark.
- Recursing on inputs the interviewer said could be large without mentioning the stack limit.
Follow-up questions to expect
- Return a valid order, or nothing if none exists. Record each module as Kahn's queue releases it. That is the whole of Course Schedule II.
- What is the fewest number of terms if any number of modules can run in parallel? Run Kahn's algorithm in rounds, releasing a whole layer at a time. The number of rounds equals the longest chain of prerequisites.
- The same, but at most k modules per term. This turns into a much harder scheduling problem; for small n people usually reach for dynamic programming over subsets, and it is fair to say so rather than force a greedy answer.
- Which modules are stuck? After Kahn's algorithm stalls, every module whose counter is still above zero is stuck, either inside a loop or downstream of one.
- Pairs arrive one at a time and you must reject the first one that creates a loop. Before adding an edge from b to a, check whether a can already reach b. For a smarter answer, mention that incremental cycle detection is its own research topic.
How to explain it out loud
Fictional example
- Candidate
- Each pair is an arrow from the prerequisite to the course it unlocks. Finishing everything is possible unless the arrows contain a loop, so this is cycle detection on a directed graph.
- Candidate
- I will keep a counter per course of prerequisites still pending. Courses at zero go in a queue. Each time I take one, I lower the counters of what it unlocks. If I manage to take all n, there is no loop.
- Candidate
- That touches each course and each pair once, so it is linear in courses plus pairs. A self-pair never reaches zero, which correctly fails, and courses nobody mentions start at zero.
- Interviewer
- Could you do it with DFS instead?
- Candidate
- Yes, with three states rather than a visited flag, so a diamond shape does not look like a loop. I would keep an explicit stack if the input can be large.
Related problems
Course Schedule II asks for the order itself and is the natural next step. Graph Valid Tree asks a similar loop question on undirected edges, where the right tool changes. Network Delay Time keeps the directed graph but adds travel times. For the broader picture of traversal questions, see the algorithm interview questions guide and the coding problems hub.
Rehearsing with Natively
Dependency problems are easy to misread under pressure, especially the direction of each pair. When you practice, Natively can take a screenshot of the prompt on your Mac or Windows machine and suggest whether in-degree counting or a three-state search fits, plus the edge cases worth testing. It also writes down what you said during a mock round, so you can check afterward whether you named the cycle idea before you started typing. More on how it works in practice is on the AI interview assistant page.
Questions people ask
How do you solve Course Schedule?
Treat each prerequisite pair as a directed edge and check for a cycle. Kahn's algorithm takes courses with no pending prerequisites one by one; if it takes all n, the schedule works. It runs in O(V + E).
Is Course Schedule a topological sort problem?
Yes. A valid order exists exactly when the graph has a topological order, which is exactly when it has no directed cycle. You only need to know whether the sort succeeds, not the order itself.
Why does DFS cycle detection need three states?
A single visited flag cannot tell a node on the current path from one finished earlier, so two paths into the same node look like a loop. Marking nodes as untouched, on the path or done fixes that.
Does the direction of the prerequisite pairs matter?
Not for the yes or no answer, because reversing every edge keeps every cycle. It does matter for Course Schedule II, where the returned order has to put prerequisites first.
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.
