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 — Basic Prerequisites
$ Input: numCourses = 2, prerequisites = [[1,0]]
Output: [0,1]
💡 Note: Course 0 has no prerequisites, so take it first. Course 1 requires course 0, so take it after completing course 0.
Example 2 — Multiple Prerequisites
$ Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3]
💡 Note: Course 0 first (no prerequisites), then courses 1 and 2 (both depend on 0), finally course 3 (depends on both 1 and 2).
Example 3 — Impossible (Cycle)
$ Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: []
💡 Note: Course 1 requires course 0, but course 0 requires course 1. This creates a cycle, making it impossible to complete all courses.

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
INPUTALGORITHMRESULT10Prerequisites: [[1,0]]Course 1 requires Course 03120More complex graph1234BFS Topological SortStep 1:Count indegreesStep 2:Queue zero indegreeStep 3:Process queueStep 4:Update indegreesQueue Processing1. Start: Queue = [0]2. Process 0: Queue = [1]3. Process 1: Queue = []Course Order[0, 1]✓ Take Course 0 first✓ Then take Course 1Valid Schedule!If cycle detected:Return empty array []Key Insight:Always process courses with no remaining prerequisites first - this ensures topological orderingTutorialsPoint - Course Schedule II | Topological Sort
Asked in
Facebook 42 Amazon 38 Google 35 Microsoft 28 Uber 25
89.2K 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