LeetCode 210: Course Schedule II — Python Solution

LeetCode 210: Course Schedule II is a Medium graph general problem. This Python walkthrough develops a topological ordering solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyMedium
TopicGraph General
Reusable patterntopological ordering
ComplexityO(V+E) time and O(V+E) space

Recognizing the pattern

Graph traversal separates reachability from representation: adjacency describes possible moves, while a visited structure prevents repeated work.

For this problem specifically, use Kahn’s algorithm and append each removed zero-indegree course to the order; return it only if every course is processed. The invariant worth writing beside the code is: Every appended course has all prerequisites earlier in the output.

Step-by-step algorithm

  1. Identify the input state consumed by findOrder(numCourses, prerequisites) and initialize the data required by the topological ordering pattern.
  2. Use Kahn’s algorithm and append each removed zero-indegree course to the order; return it only if every course is processed.
  3. After each update, verify the page’s central invariant: Every appended course has all prerequisites earlier in the output.
  4. Finish only after the boundary behavior is covered: A cycle returns an empty list; isolated courses begin with zero indegree.

Python solution

from collections import deque

class Solution:
    def findOrder(self, numCourses, prerequisites):
        graph = [[] for _ in range(numCourses)]; indegree = [0] * numCourses
        for course, prerequisite in prerequisites:
            graph[prerequisite].append(course); indegree[course] += 1
        queue = deque(i for i, degree in enumerate(indegree) if degree == 0)
        order = []
        while queue:
            course = queue.popleft(); order.append(course)
            for following in graph[course]:
                indegree[following] -= 1
                if indegree[following] == 0: queue.append(following)
        return order if len(order) == numCourses else []

Reading the implementation

The main entry point is findOrder(numCourses, prerequisites). The named working state includes graph, queue, order, course; those variables make the topological ordering state visible instead of hiding it in incidental control flow.

The implementation uses 3 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, use Kahn’s algorithm and append each removed zero-indegree course to the order; return it only if every course is processed.

Correctness argument

Initialization. The data structure starts with exactly the information known before any input element is processed.

Preservation. Use Kahn’s algorithm and append each removed zero-indegree course to the order; return it only if every course is processed. Each update records the current item without invalidating earlier decisions; consequently, every appended course has all prerequisites earlier in the output.

Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.

Complexity and trade-offs

O(V+E) time and O(V+E) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

DFS and BFS often have the same asymptotic cost; choose DFS for recursive structure and BFS when distance or processing order matters. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

assert Solution().findOrder(2,[[1,0]])==[0,1]

Common mistakes and edge cases

  • Problem-specific boundary: A cycle returns an empty list; isolated courses begin with zero indegree.
  • Pattern-level pitfall: Mark a state when it is discovered rather than after all of its neighbors are processed, or cycles can enqueue it repeatedly.
  • Invariant check: after every update, confirm that every appended course has all prerequisites earlier in the output.

Interview review checklist

  • Explain why topological ordering matches the structure of this input.
  • State the invariant in one sentence before tracing code: Every appended course has all prerequisites earlier in the output.
  • Derive O(V+E) time and O(V+E) space from how many times each element or state is visited.
  • Test the boundary explicitly: A cycle returns an empty list; isolated courses begin with zero indegree.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 207. Course Schedule · Next: 909. Snakes and Ladders