LeetCode #210 Medium

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.

Constraints
  • 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.
graphstopological-sortbfs
Open on LeetCode ↗
02

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.

How to spot this pattern

"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.

03

Approach

Try it first

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).

1

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.

2

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).

3

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.

4

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 nxt onto the queue, because nothing blocks it any more.
5

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.

04

Code in Python, C++ and Java

▶1from collections import deque
▶2 
▶3class Solution:
▶4 def findOrder(self, numCourses, prerequisites):
▶5 adj = [[] for _ in range(numCourses)]
▶6 indeg = [0] * numCourses
▶7 for a, b in prerequisites:
▶8 adj[b].append(a)
▶9 indeg[a] += 1
▶10 
▶11 q = deque(c for c in range(numCourses) if indeg[c] == 0)
▶12 order = []
▶13 while q:
▶14 c = q.popleft()
▶15 order.append(c)
▶16 for nxt in adj[c]:
▶17 indeg[nxt] -= 1
▶18 if indeg[nxt] == 0:
▶19 q.append(nxt)
▶20 return order if len(order) == numCourses else []
precourse0in 01in 12in 13in 2queueemptyorder0123build arrows + in-degrees
courses40 to 3
indeg[0, 1, 1, 2]unmet prerequisites
Each pair [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.
precourse0in 01in 12in 13in 2queue0order0123in 0 → queue: 0
queue[0]no prerequisites
Courses with in-degree 0 need nothing first, so they can go at the front of the schedule: 0. Every other course must wait until its count falls to 0.
precourse01in 12in 13in 2queueemptyorder00123take course 0 → place it 1st
c0front of the queue
order[0]
Pop course 0 and write it into slot 0. It was only queued once all its prerequisites were placed, so every course it needs already sits to its left. It unlocks 1, 2, which are checked next.
precourse01in 02in 13in 2queue1order00123course 1 needs 0 more → queue it
indeg[1]0one prerequisite done
queue[1]added 1
Course 0 is placed, so course 1 has one prerequisite fewer: its count drops to 0. That was its last one, so 1 joins the queue.
precourse01in 02in 03in 2queue12order00123course 2 needs 0 more → queue it
indeg[2]0one prerequisite done
queue[1, 2]added 2
Course 0 is placed, so course 2 has one prerequisite fewer: its count drops to 0. That was its last one, so 2 joins the queue.
precourse012in 03in 2queue2order001123take course 1 → place it 2nd
c1front of the queue
order[0, 1]
Pop course 1 and write it into slot 1. It was only queued once all its prerequisites were placed, so every course it needs already sits to its left. It unlocks 3, which is checked next.
precourse012in 03in 1queue2order001123course 3 needs 1 more → wait
indeg[3]1one prerequisite done
queue[2]no change
Course 1 is placed, so course 3 has one prerequisite fewer: its count drops to 1. It still waits on another course, so it stays out of the queue.
precourse0123in 1queueemptyorder0011223take course 2 → place it 3rd
c2front of the queue
order[0, 1, 2]
Pop course 2 and write it into slot 2. It was only queued once all its prerequisites were placed, so every course it needs already sits to its left. It unlocks 3, which is checked next.
precourse0123in 0queue3order0011223course 3 needs 0 more → queue it
indeg[3]0one prerequisite done
queue[3]added 3
Course 2 is placed, so course 3 has one prerequisite fewer: its count drops to 0. That was its last one, so 3 joins the queue.
precourse0123queueemptyorder00112233take course 3 → place it 4th
c3front of the queue
order[0, 1, 2, 3]
Pop course 3 and write it into slot 3. It was only queued once all its prerequisites were placed, so every course it needs already sits to its left. No course depends on it, so nothing else changes.
precourse0123queueemptyorder00112233all 4 placed → return order
len(order)4numCourses = 4
result[0, 1, 2, 3]
All 4 slots are filled, so the answer is [0, 1, 2, 3]. Every arrow points from an earlier slot to a later one. Other orders may also be valid; any one is accepted.
05

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 [].

▶1import sys
▶2 
▶3class Solution:
▶4 def findOrder(self, numCourses, prerequisites):
▶5 sys.setrecursionlimit(10000)
▶6 needs = [[] for _ in range(numCourses)]
▶7 for a, b in prerequisites:
▶8 needs[a].append(b)
▶9 NEW, ON_PATH, PLACED = 0, 1, 2
▶10 state = [NEW] * numCourses
▶11 order = []
▶12 
▶13 def place(c):
▶14 if state[c] == ON_PATH:
▶15 return False
▶16 if state[c] == PLACED:
▶17 return True
▶18 state[c] = ON_PATH
▶19 for pre in needs[c]:
▶20 if not place(pre):
▶21 return False
▶22 state[c] = PLACED
▶23 order.append(c)
▶24 return True
▶25 
▶26 for c in range(numCourses):
▶27 if not place(c):
▶28 return []
▶29 return order
06

Common pitfalls

Returning a partial order on a cycle

✗ Wrong
return order
✓ Right
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

✗ Wrong
for a, b in prerequisites:
    adj[a].append(b)
    indeg[a] += 1
✓ Right
for 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

✗ Wrong
return order[::-1]
✓ Right
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.

07

Edge cases

A course that appears in no pair

It starts at in-degree 0, so it is queued with the other free courses and still lands in order.

Your order differs from the expected output

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.

08

Complexity

Time
O(V + E)
Space
O(V + E)
V is 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.
09

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.