Imagine you're a university student trying to graduate as quickly as possible! ๐ You have n courses labeled from 1 to n that you need to complete, but there's a catch - some courses have prerequisites.
You're given an array relations where relations[i] = [prevCoursei, nextCoursei] means you must complete prevCoursei before you can take nextCoursei. The good news? In any semester, you can take unlimited courses as long as you've completed all their prerequisites in previous semesters.
Goal: Find the minimum number of semesters needed to complete all courses. If it's impossible due to circular dependencies (like Course A requires Course B, but Course B requires Course A), return -1.
Example: If you have 3 courses with relations [[1,3],[2,3]], you can take courses 1 and 2 in semester 1, then course 3 in semester 2, requiring 2 semesters total.
Input & Output
Constraints
- 1 โค n โค 5000
- 0 โค relations.length โค 5000
- relations[i].length == 2
- 1 โค prevCoursei, nextCoursei โค n
- prevCoursei โ nextCoursei
- All prerequisite relationships are distinct