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] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

For example, the pair [0, 1] indicates that to take course 0 you have to first take course 1.

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.

Input & Output

Example 1 — Linear Chain
$ Input: numCourses = 2, prerequisites = [[1,0]]
Output: [0,1]
💡 Note: To take course 1, you must first take course 0. So the correct order is [0,1].
Example 2 — Multiple Prerequisites
$ Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [0,2,1,3]
💡 Note: Course 0 has no prerequisites, courses 1 and 2 depend on 0, course 3 depends on both 1 and 2. Valid orderings include [0,1,2,3] or [0,2,1,3].
Example 3 — Impossible Case
$ Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: []
💡 Note: Course 1 depends on 0, and course 0 depends on 1, creating a cycle. No valid ordering exists.

Constraints

  • 1 ≤ numCourses ≤ 2000
  • 0 ≤ prerequisites.length ≤ numCourses × (numCourses - 1)
  • prerequisites[i].length == 2
  • 0 ≤ ai, bi < numCourses
  • ai ≠ bi
  • All the pairs [ai, bi] are distinct

Visualization

Tap to expand
Course Schedule II: Prerequisites → Topological OrderingInputnumCourses = 4prerequisites =[[1,0],[2,0],[3,1],[3,2]]Dependency Graph0123OutputValid Order:[0, 1, 2, 3]Topological Sort ensures prerequisites come before dependent courses🎯 Key: Transform prerequisites into dependency graph, then sort topologically
Understanding the Visualization
1
Input
Courses 0-3 with prerequisite relationships
2
Build Graph
Create directed graph from prerequisites
3
Topological Sort
Find valid ordering respecting all dependencies
Key Takeaway
🎯 Key Insight: Transform course prerequisites into a directed graph and use topological sorting to find a valid ordering
Asked in
Facebook 45 Google 38 Amazon 32 Microsoft 28
89.0K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen