You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a prerequisite relationship between course prevCoursei and course nextCoursei: course prevCoursei has to be taken before course nextCoursei.
In one semester, you can take any number of courses as long as you have taken all the prerequisites in the previous semesters for the courses you are taking.
Return the minimum number of semesters needed to take all courses. If there is no way to take all the courses, return -1.
The insight: Each "semester" corresponds to one level in topological sort. Courses with in-degree 0 can be taken in the current semester. After taking them, we update in-degrees and move to the next semester. The number of semesters equals the longest path in the DAG.
Real-world analogy: Think of a university student planning their course load. They can take multiple courses simultaneously in one semester, as long as all prerequisites are satisfied. The minimum time to graduate is determined by the longest prerequisite chain.
n = 3, relations = [[1,3],[2,3]]2n = 3, relations = [[1,2],[2,3],[3,1]]-1n = 4, relations = [[1,2],[2,3],[3,4]]41 <= n <= 50001 <= relations.length <= 5000relations[i].length == 21 <= prevCoursei, nextCoursei <= nprevCoursei != nextCourseiAll the pairs [prevCoursei, nextCoursei] are uniqueClick "Run" to execute your code against test cases
Socratic guidance - I'll ask questions, not give answers