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 - BFS Approach INPUT Course Dependency Graph 1 2 3 n = 3 relations = [[1,3],[2,3]] In-degrees: [0, 0, 2] Course 1,2: 0 | Course 3: 2 ALGORITHM STEPS 1 Build Graph Calculate in-degrees 2 Initialize Queue Add courses with in-degree 0 3 BFS Processing Process level by level 4 Count Semesters Return levels or -1 BFS Simulation Sem 1: 1 2 Sem 2: 3 All 3 courses completed! FINAL RESULT Minimum Semesters 2 Schedule Semester 1: Course 1, 2 Semester 2: Course 3 OK - Valid No cycles detected All courses taken Key Insight: BFS level order traversal naturally groups courses by semesters. Courses with in-degree 0 can be taken first. Each BFS level represents one semester. If we can't process all nodes, a cycle exists (return -1). The number of BFS levels = minimum semesters needed. TutorialsPoint - Parallel Courses | BFS Topological Sort Approach
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