Fewest Terms to Graduate

Medium · Topological Sort & Shortest Paths · about 20 min

A degree has n courses, numbered 0 to n - 1. Each [before, after] in needs means course before must be passed in an earlier term than course after. You may take any number of courses in one term.

Return the fewest terms needed to pass every course, or -1 if that is impossible.

  • 1 <= n <= 5000, pairs may repeat.

Example: fewest_terms(3, [[0, 2], [1, 2]]) → 2 (courses 0 and 1 in term 1, course 2 in term 2).

Hints

  • Which courses can you take in the very first term? Those with no prerequisites.
  • After a term, some courses lose their last unpassed prerequisite. They form the next term.
  • Count the terms, and check at the end that every course was taken.

Learn the pattern first: the Topological Sort & Shortest Paths lesson.

More Topological Sort & Shortest Paths problems