Parallel Courses - Problem
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 semester 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.
Input & Output
Example 1 — Basic Prerequisites
$
Input:
n = 3, relations = [[1,3],[2,3]]
›
Output:
2
💡 Note:
Course 1 and 2 have no prerequisites, so take them in semester 1. Course 3 requires both 1 and 2, so take it in semester 2.
Example 2 — Chain Dependencies
$
Input:
n = 3, relations = [[1,2],[2,3]]
›
Output:
3
💡 Note:
Course 1 → Course 2 → Course 3 forms a chain. Need 3 semesters: semester 1 (course 1), semester 2 (course 2), semester 3 (course 3).
Example 3 — Impossible Case
$
Input:
n = 2, relations = [[1,2],[2,1]]
›
Output:
-1
💡 Note:
Course 1 requires 2 and course 2 requires 1, creating a cycle. Impossible to complete all courses.
Constraints
- 1 ≤ n ≤ 5000
- 0 ≤ relations.length ≤ 5000
- relations[i].length == 2
- 1 ≤ prevCoursei, nextCoursei ≤ n
- prevCoursei ≠ nextCoursei
- All the pairs [prevCoursei, nextCoursei] are unique
Visualization
Tap to expand
Understanding the Visualization
1
Input
3 courses with relations [[1,3],[2,3]] - courses 1,2 are prerequisites for 3
2
Process
Use topological sort to find minimum semesters needed
3
Output
2 semesters minimum - take 1,2 first then 3
Key Takeaway
🎯 Key Insight: Use topological sorting to process courses level by level - each level represents one semester
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code