Skip to content
RED SAGSkills

Plan Courses Smallest-First

There are n courses numbered 0 to n - 1. Each pair [a, b] in prereqs means course b must be taken before course a.

Return an order in which all courses can be taken. Whenever several courses are available at the same time, always take the one with the smallest number next, so the answer is unique. If the prerequisites contain a cycle and no valid order exists, return an empty array. (Build systems and job schedulers solve exactly this problem.)

Example 1

Input: n = 4, prereqs = [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3]

Example 2

Input: n = 2, prereqs = [[1,0],[0,1]]
Output: []
Explanation: Each course requires the other.

Constraints

  • 1 <= n <= 2000
  • 0 <= prereqs.length <= 5000
  • 0 <= a, b < n
Hint 1

Count incoming edges for every course; courses with zero are available.

Hint 2

Keep the available courses in a min-heap so you always pick the smallest. If you finish with fewer than n courses, there is a cycle.

Good practice for: Backend Developer, DevOps Engineer, Data Engineer, Full Stack Developer, Cloud Engineer, MLOps Engineer

Run checks your code on 3 sample tests. Submit runs all 8 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.