Minimum Semesters

Given n courses numbered from 1 to n and a list of prerequisite relations, return the minimum number of semesters needed to finish all courses. If it is impossible, return -1. Pattern focus: Kahn's Algorithm. Level-by-level processing 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...
Minimum Semesters - Topological Sort DSA Problem