Parallel Courses

Medium

Topics
GraphTopological SortBFS

You are given n courses labelled 0 to n - 1 and a list of edges where edges[i] = [a, b] means course a must be taken before course b.

In one semester you may take any number of courses, as long as every prerequisite of each one was completed in an earlier semester.

Return the minimum number of semesters needed to take all courses, or -1 if it is impossible.

Example 1

Input:  n = 3, edges = [[0,1],[0,2]]
Output: 2
Explanation: Take course 0 in semester 1, then courses 1 and 2 together in semester 2.

Example 2

Input:  n = 3, edges = [[0,1],[1,2],[2,0]]
Output: -1
Explanation: The three courses form a cycle, so no valid order exists.

Constraints

  • 1 <= n <= 5000
  • 0 <= edges.length <= 5000
  • edges[i].length == 2
  • All pairs are distinct
Run ⌘' · Submit ⌘⏎