Course Schedule
How the interviewer asks it
“There are n courses and a list of prerequisite pairs, where (a, b) means b must be taken before a. Return a valid order to take all courses, or say it is impossible.”
2 1 1 0
0 1
In the practice room your code reads the input from standard input, and Run checks it against tests like this one. Try it now in your browser, in Python or JavaScript.
Typed drills are free and unlimited: the AI scores your answer against the outline below.
What the interviewer is looking for
- You turn the pairs into a directed graph and name the problem: topological sort with cycle detection.
- A correct edge direction, from prerequisite to course.
- Kahn's algorithm with in-degrees, or DFS with three states, explained before coding.
- You detect impossibility by checking whether every course was output.
How to structure your answer
- 01
Build the graph
Adjacency list from b to a, and an in-degree count for each course.
- 02
Kahn's algorithm
Queue every course with in-degree 0. Pop one, append it to the order, and decrement its neighbours, queueing any that reach 0.
- 03
Detect a cycle
If the order has fewer than n courses, a cycle exists and there is no valid schedule.
- 04
Test
Two courses with a mutual prerequisite, a course with no prerequisites, and a chain.
- 05
Complexity
O(V + E) time and space.
Best answers from candidates
No candidate answers yet. Type yours, and if it scores 6 or more you can show it here without your name.
Answers are shared by candidates, without names, after a privacy check. Add yours
Common mistakes
- Reversing the edges and producing the order backwards.
- Using a visited set in DFS without a separate "on the current path" state, which misses or invents cycles.
- Forgetting courses that appear in no pair at all.
Follow-up questions to expect
- What is the minimum number of semesters if you can take any number of courses at once?
- Return every valid ordering.
Now answer it out loud
Max will ask you this exact question, listen to your answer, push on the weak spots with follow-ups like the ones above, and score you when you finish.
Practice with MaxFree: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.
More coding interview questions
Preparing for this round? Read how to prepare for a coding interview: a four-week DSA plan.