Skip to main content
Medium Topological Sort High frequency

Course Schedule II

Open on LeetCode

Approach Summary

Kahn's algorithm: start with 0-in-degree nodes. Return ordering; if not all nodes processed, cycle exists.

Full Solution & Approach

This asks for an actual valid order, so run Kahn's algorithm and collect the order instead of just counting. Build the adjacency list and indegree array; seed a queue with all zero-indegree courses. Repeatedly pop a course, append it to the result, and decrement the indegree of every course that depends on it, enqueueing any that reach zero. If the result contains all numCourses courses, return it — it is a valid topological order. If not, a cycle blocks the remaining courses and the answer is an empty array. The BFS-based Kahn's approach is preferred over the DFS three-color variant here because it directly produces the order in the same pass and is easier to reason about under interview time pressure.

Every edge is relaxed once — O(V + E) time. The adjacency list, indegree array, queue, and result use O(V + E) space.

Solution Code

Solution

def find_order(num_courses: int, prerequisites: list[list[int]]) -> list[int]:
    graph = [[] for _ in range(num_courses)]
    indegree = [0] * num_courses
    for course, prereq in prerequisites:
        graph[prereq].append(course)
        indegree[course] += 1
    queue = [c for c in range(num_courses) if indegree[c] == 0]
    order = []
    for c in queue:
        order.append(c)
        for nxt in graph[c]:
            indegree[nxt] -= 1
            if indegree[nxt] == 0:
                queue.append(nxt)
    return order if len(order) == num_courses else []

Edge Cases to Watch

  • No prerequisites — any order is valid; the queue starts with all courses
  • A cycle — return []
  • Unreachable courses (no prerequisites and none depending on them) — they simply start in the queue
  • A single course — [0]

How to Recognize This Pattern

  • Return topological order of courses

Complexity Analysis

Time Complexity

O(V + E)

Space Complexity

O(V + E)

Tags

Graph DFS BFS Topological Sort

This site is free. If these guides are helping your prep, consider buying me a coffee. ☕

Support →
Buy me a coffee