Skip to content

Course Schedule II

Order the courses so every prerequisite comes first, or return an empty list when a cycle makes it impossible.

MediumTopological Sort
Solve on LeetCode

The problem

There are numCourses courses, numbered 0 to numCourses - 1. Each pair [a, b] in prerequisites means you must finish course b before you take course a. Return any order that lets you take every course, or an empty list if no such order exists.

Input numCourses = 5, prerequisites = [[1, 0], [2, 1], [4, 3]]

Output [0, 3, 1, 4, 2]

0 comes before 1, 1 before 2, and 3 before 4. Other orders, such as [3, 4, 0, 1, 2], are just as correct.

Input numCourses = 3, prerequisites = [[0, 1], [1, 2], [2, 0]]

Output []

0 needs 1, 1 needs 2 and 2 needs 0, so none of them can go first.

Key constraint: Any valid order is accepted, and a cycle anywhere in the prerequisites means the answer is an empty list.

How to spot the pattern

  • There are "do this before that" rules between tasks.
  • You need a full ordering, not just a yes or no.
  • A cycle in the rules makes the task impossible.

The idea

A course with no unfinished prerequisites can be taken right away. Taking it may free the courses that were waiting on it, so you keep taking any free course and lower the count of what still blocks each course that needed it. If you manage to take every course, the order you took them in is the answer; courses that are never freed sit on a cycle, and then the answer is empty.

Brute force: Repeatedly scan every course for one whose prerequisites are all done, which takes O(V * (V + E)) time.

Step by step

  1. 1Build a list from each course b to the courses a that need it, and count each course's prerequisites (its indegree).
  2. 2Put every course with indegree 0 into a queue.
  3. 3Take a course from the queue, add it to the order, and lower the indegree of each course that needs it.
  4. 4Whenever a course's indegree drops to 0, add it to the queue.
  5. 5At the end, return the order if it has all numCourses courses, otherwise return an empty list.

See the pattern move

The topological sort pattern on a small example. Step through it, or press play.

Code

from collections import deque


class Solution:
    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
        unlocks = [[] for _ in range(numCourses)]  # course -> courses that need it first
        indegree = [0] * numCourses                # prerequisites each course still waits for
        for course, before in prerequisites:
            unlocks[before].append(course)
            indegree[course] += 1

        ready = deque(c for c in range(numCourses) if indegree[c] == 0)
        order = []
        while ready:
            course = ready.popleft()
            order.append(course)
            for dependent in unlocks[course]:
                indegree[dependent] -= 1
                if indegree[dependent] == 0:
                    ready.append(dependent)

        # Courses on a cycle never reach indegree 0, so they never get taken.
        return order if len(order) == numCourses else []

Complexity

Time

O(V + E)

Space

O(V + E)

Each course enters the queue at most once and each prerequisite pair is used once; the adjacency list stores every pair.

Watch out for

  • Reversing the edges: [a, b] means b comes first, so the edge goes from b to a.
  • Returning a partial order when there is a cycle, instead of an empty list.
  • Forgetting courses that have no prerequisites and nothing depending on them; they still belong in the order.

Follow-up questions

How would you do it with DFS?

Add each course to a list once all the courses it unlocks are finished, then reverse that list. Reaching a course that is still on the current DFS path means there is a cycle.

What if you only need to know whether finishing is possible?

Run the same algorithm and check whether it took all numCourses courses. That is Course Schedule.

In Hinglish

Jis course ka koi prerequisite baaki nahi, use pehle le lo. Uske baad jo courses free hote hain unhe queue mein daalo; agar sab courses nahi nikle toh cycle hai, empty list return karo.

Related problems