Skip to content
RED SAGSkills

Fewest Terms to Finish a Program

A study programme has n courses numbered 0 to n - 1. Each pair [a, b] in prereqs means course a must be completed in an earlier term than course b. A student may take any number of courses in one term, as long as all their prerequisites were finished in earlier terms.

Return the minimum number of terms needed to finish every course, or -1 if the prerequisites contain a cycle and the programme can never be finished.

Example 1

Input: n = 3, prereqs = [[0,2],[1,2]]
Output: 2
Explanation: Courses 0 and 1 in term 1, course 2 in term 2.

Example 2

Input: n = 3, prereqs = [[0,1],[1,2],[2,0]]
Output: -1
Explanation: 0 → 1 → 2 → 0 is a cycle.

Constraints

  • 1 <= n <= 2 * 10^4
  • 0 <= prereqs.length <= 5 * 10^4
  • No duplicate pairs; a != b
Hint 1

Use Kahn's algorithm: repeatedly take every course whose prerequisites are all done.

Hint 2

Process the courses in waves; each wave is one term. If some courses are never freed, there is a cycle.

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

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