Course Schedule II — LeetCode 210 Python Solution

MediumDepth-First SearchBreadth-First SearchGraphTopological Sort
Problem
#210
Reading time
3 min

The problem

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

Example

Input
numCourses = 2, prerequisites = [[1,0]]
Output
[0,1]
Explanation
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1].

Python solution

Python
class Solution:
    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
        g = defaultdict(list)
        indeg = [0] * numCourses
        for a, b in prerequisites:
            g[b].append(a)
            indeg[a] += 1
        ans = []
        q = deque(i for i, x in enumerate(indeg) if x == 0)
        while q:
            i = q.popleft()
            ans.append(i)
            for j in g[i]:
                indeg[j] -= 1
                if indeg[j] == 0:
                    q.append(j)
        return ans if len(ans) == numCourses else []

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

Pattern: Topological Sort

Order a set of tasks so that every dependency comes before the thing that needs it. LeetCode 210. Course Schedule II is filed here because LeetCode tags it Topological Sort, which is the vocabulary this hub collects.

The topological sort guide has the Python template for the pattern and the 32 LeetCode problems that use it.

Related problems

On study lists

This problem is on NeetCode 150 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 210. Course Schedule II?
LeetCode 210. Course Schedule II is rated Medium on LeetCode.
What is the time complexity of LeetCode 210. Course Schedule II?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 210. Course Schedule II?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 210. Course Schedule II cover?
LeetCode 210. Course Schedule II is tagged Depth-First Search, Breadth-First Search, Graph and Topological Sort on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview