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
Parallel Courses: Minimum Semesters to Complete AllInput: n=3, relations=[[1,3],[2,3]]123Semester 1Semester 2Solution Process1. Courses 1,2: indegree = 02. Take both in Semester 13. Course 3: indegree = 0 now4. Take 3 in Semester 2Result: 2 semestersOutput: 2 semesters minimum
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
Asked in
Google 45 Amazon 32 Facebook 28 Microsoft 25
28.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen