← All Exercises

Kahn's Algorithm for Course Ordering

advancedjavascript~25min

Background

Topological sorting drives build systems, package installers, and task schedulers that must respect dependency order.

Problem

Given numCourses courses and prerequisite pairs [course, prerequisite], return a valid study order, or an empty array if the requirements contain a cycle.

Input

An integer numCourses and an array of [course, prerequisite] pairs with course indices from 0 to numCourses - 1.

Output

An array containing every course exactly once in dependency order, or [] when no order exists.

Sample tests

Sample 1

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

Sample 2

Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Expected: []

Sample 3

Input: numCourses = 1, prerequisites = []
Expected: [0]

Your solution

Learning objective

Implement Kahn's algorithm with an indegree array and detect cycles by counting emitted nodes.