InferenceAI

Enter at least two characters to search.

Start free

Course Order

mediumGraphs25 min25 XP

There are n courses labelled 0 to n - 1. Each pair [a, b] in prereqs means course b must be taken before course a.

Return an order to take all courses. When several courses are available, always take the smallest label first, so the answer is unique. Return [] if a cycle makes it impossible.

Requirements

  • Use Kahn's algorithm (topological sort) with a min-heap.

Examples

EXAMPLE WALKTHROUGHdiamond

A guided view of the published example, not a trace of your code.

INPUT[4,[[1,0],[2,0],[3,1],[3,2]]]
TASKcourse_order()
EXPECTED OUTPUT[0,1,2,3]

Start with the input values shown in this example.

Example 1 of 3

Input: n = 4, prereqs = [[1,0],[2,0],[3,1],[3,2]]

Output: [0,1,2,3]

Explanation: diamond

Input: n = 2, prereqs = [[1,0],[0,1]]

Output: []

Explanation: cycle

Input: n = 3, prereqs = []

Output: [0,1,2]

Explanation: no prerequisites

Hint 1

Count incoming edges (prerequisites) for each course.

Hint 2

Repeatedly take the smallest course with no remaining prerequisites.

Topics

DSAGraphsPython