Skip to content
Veltoryx Technologies
ProProblem 122● MediumLeetCode #210 ↗3 min readUpdated 30 October 2026

Course Schedule II

Return a valid course ordering that satisfies all prerequisite dependencies using Kahn's topological sort algorithm.

01The 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] = [a_i, b_i] indicates that you must take course b_i first if you want to take course a_i.

Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.

InputOutputWhy
numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]][0, 1, 2, 3]Course 0 is taken first, unlocking 1 and 2, which unlock 3. [0, 2, 1, 3] is also valid.
numCourses = 2, prerequisites = [[1,0],[0,1]][]Cycle detected: impossible to schedule.

Constraints

  • 1 <= numCourses <= 2000
  • 0 <= prerequisites.length <= numCourses * (numCourses - 1)
  • prerequisites[i].length == 2
  • 0 <= a_i, b_i < numCourses
  • a_i != b_i
  • All [a_i, b_i] pairs are distinct.

Loading the rest of the lesson…