Course Schedule II
Course Schedule II is LeetCode 210 (Medium). There are numCourses courses labelled 0 to numCourses - 1, and each pair [a, b] in prerequisites means course b must be taken before course a.
- Return an order that takes every course after all of its prerequisites. Any valid order is accepted.
- Return an empty array if no such order exists.
With up to 2,000 courses and millions of possible pairs, the solution has to be linear in courses plus pairs.
- 1 <= numCourses <= 2000
- 0 <= prerequisites.length <= numCourses * (numCourses - 1)
- prerequisites[i].length == 2
- 0 <= ai, bi < numCourses
- ai != bi
- All the pairs [ai, bi] are distinct.
Intuition
Draw each course as a node and each pair [a, b] as an arrow b → a. A valid schedule is a topological order of this graph: a line-up in which every arrow points forward.
Build the line-up from the front. A course with no incoming arrows needs nothing, so it can go first. Placing it removes its arrows, which may free another course:
- Free course: in-degree 0, so it can be placed next.
- Placing it: lowers the in-degree of every course it unlocks.
- Course on a cycle: it waits on another course on the same cycle, so its in-degree never reaches 0 and it is never placed.
If every course gets placed, that order is the answer; if some are left over, there is a cycle and no schedule exists.
"Return an order that respects every before/after rule" is a topological sort. Build steps, package installs and task pipelines ask the same thing, and a cycle in the rules means no order exists.
Approach
Before reading on, decide which course can safely go first, and what has to change once it is placed. Then decide how you will know, at the end, that a cycle blocked some courses. Aim for O(V + E).
Two ways to solve it
Keep taking a course with no unmet prerequisites and append it to the order.
- Direct: the pop order is the answer.
- Cycle check: a short order means a cycle.
- No recursion: safe on a 2,000-course chain.
The usual interview answer.
To place a course, first place every course it needs, then append it.
- States: new, on the current path, placed.
- Cycle: reaching a course that is still on the path.
- Watch out: a long chain needs a higher recursion limit in Python.
Pick it if you already think in DFS.
Both run in O(V + E); Kahn's algorithm wins because the queue order is already the answer and there is no recursion to overflow. The steps, code and live demo follow Kahn's algorithm, and the DFS code comes after the demo.
Build the arrows and in-degrees
For each pair [a, b], append a to adj[b] and add 1 to indeg[a]. adj[b] lists the courses that b unlocks, and indeg[a] counts the prerequisites a is still waiting on.
Queue every free course
Put every course with indeg == 0 into a queue. These courses need nothing first, so any of them can open the schedule. A deque in Python keeps each pop from the front O(1).
Pop a course and place it
Pop the front of the queue and append it to order. A course only enters the queue once all of its prerequisites are placed, so its position is always safe.
Release the courses it unlocks
For each course nxt in adj[c]:
- subtract 1 from
indeg[nxt], because one of its prerequisites is now placed; - if the count reaches 0, push
nxtonto the queue, because nothing blocks it any more.
Check that every course was placed
When the queue empties, return order only if it holds all numCourses courses, and [] otherwise. A short order means a cycle: the courses on it kept waiting on each other and never became free.
Code in Python, C++ and Java
[a, b] becomes an arrow b → a, from the prerequisite to the course it unlocks. The small in number over each course counts the arrows coming into it: the prerequisites it still waits on. The order array has 4 empty slots to fill.[a, b] becomes an arrow b → a, from the prerequisite to the course it unlocks. The small in number over each course counts the arrows coming into it: the prerequisites it still waits on. The order array has 5 empty slots to fill.[a, b] becomes an arrow b → a, from the prerequisite to the course it unlocks. The small in number over each course counts the arrows coming into it: the prerequisites it still waits on. The order array has 3 empty slots to fill.DFS with three states
Here the arrows point from a course to the courses it needs. Placing a course first places each of its prerequisites and then appends it, so the list is already in a valid order. Meeting a course that is still on the current path means a cycle, and the answer is [].
Common pitfalls
Returning a partial order on a cycle
return order
return order if len(order) == numCourses else []
A cycle stops some courses from ever being placed, but the courses outside it still land in order, so the list looks like an answer. Only the length check catches the missing courses.
Pointing the arrow the wrong way
for a, b in prerequisites:
adj[a].append(b)
indeg[a] += 1for a, b in prerequisites:
adj[b].append(a)
indeg[a] += 1[a, b] means b comes first, so the arrow runs b → a. If adj points the other way while indeg counts the right way, placing a course lowers the count of its own prerequisite, and valid inputs come back as [].
Reversing the queue order
return order[::-1]
return order
Some DFS versions record each course after everything it unlocks, so they must reverse at the end. Kahn's algorithm already pops prerequisites first, so reversing its order puts every course before its own prerequisites.
Edge cases
It starts at in-degree 0, so it is queued with the other free courses and still lands in order.
Most inputs have several valid orders and LeetCode accepts any of them. For [[1,0],[2,0],[3,1],[3,2]], both [0,1,2,3] and [0,2,1,3] are correct.
Complexity
numCourses and E is the number of pairs. Each course is queued and popped once, and each arrow lowers one in-degree once. The adjacency list stores E entries.Course Schedule II FAQ
What is the difference between Course Schedule and Course Schedule II?
Course Schedule (207) returns true or false: can every course be finished? Course Schedule II (210) returns the order itself. The algorithm is the same; 210 keeps the popped courses in a list and returns it, or [] when a cycle leaves some courses out.