Parallel Courses

Given n courses and prerequisite relations, return the minimum number of semesters needed to complete all courses. If it is impossible, return -1. Pattern focus: Indegree. Grouping nodes by indegree-zero layers gives the semester count naturally.

Input Format

n = number of courses, relations = prerequisite pairs [u, v]

Output Format

minimum semesters needed, or -1 if impossible

Constraints

  • 1 <= input size <= 10^5
  • -10^9 <= numeric values <= 10^9

Examples

Example 1:

Input:

n = 3
relations = [[1,3],[2,3]]

Output:

2

Explanation:

Courses 1 and 2 can be taken together, then course 3.

Example 2:

Input:

n = 3
relations = [[1,2],[2,3],[3,1]]

Output:

-1

Explanation:

A cycle makes completion impossible.

Example 3:

Input:

n = 4
relations = [[1,2],[2,3],[3,4]]

Output:

4

Explanation:

The chain forces one course per semester.

Loading...
Parallel Courses - Topological Sort DSA Problem