There are numCourses courses labeled from 0 to numCourses - 1. You are given a list prerequisites where each entry [a, b] means course b must be completed before course a.
Return any ordering of courses that lets you finish all of them. If more than one valid ordering exists you may return any of them.
If it is impossible to finish every course because of a circular dependency, return an empty array.
Example 1
Input: numCourses = 2, prerequisites = [[1,0]]
Output: [0,1]
Course 1 depends on course 0, so course 0 must come first. The order [0, 1] finishes both.
Example 2
Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3]
Course 0 unblocks 1 and 2, and both feed into 3. The order [0, 1, 2, 3] respects every prerequisite (other valid orders exist).
Constraints
1 <= numCourses <= 20000 <= prerequisites.length <= numCourses * (numCourses - 1)prerequisites[i].length == 20 <= a_i, b_i < numCoursesa_i != b_iAll the pairs [a_i, b_i] are distinct.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI