Parallel Courses II - 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.

Also, you are given the integer k. In one semester, you can take at most k 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. The testcases will be generated such that it is possible to take every course.

Input & Output

Example 1 — Basic Prerequisites
$ Input: n = 4, relations = [[2,1],[3,1],[1,4]], k = 2
Output: 3
💡 Note: Course 1 needs courses 2 and 3. Course 4 needs course 1. Semester 1: take 2,3. Semester 2: take 1. Semester 3: take 4.
Example 2 — No Prerequisites
$ Input: n = 3, relations = [], k = 2
Output: 2
💡 Note: No prerequisites, so we can take any courses. Take 2 courses per semester: Semester 1: courses 1,2. Semester 2: course 3.
Example 3 — Linear Chain
$ Input: n = 3, relations = [[1,2],[2,3]], k = 1
Output: 3
💡 Note: Linear dependency: 1→2→3. Must take one course per semester in order: 1, then 2, then 3.

Constraints

  • 1 ≤ n ≤ 15
  • 1 ≤ k ≤ n
  • 0 ≤ relations.length ≤ n × (n-1) / 2
  • relations[i].length == 2
  • 1 ≤ prevCoursei, nextCoursei ≤ n
  • prevCoursei ≠ nextCoursei
  • All the pairs [prevCoursei, nextCoursei] are unique
  • The given graph is a valid DAG (directed acyclic graph)

Visualization

Tap to expand
Parallel Courses II: Optimal Course Scheduling2314Semester 1: {2,3}Semester 2: {1}Semester 3: {4}Result: 3 semesters (optimal)
Understanding the Visualization
1
Input Analysis
4 courses with prerequisites: 2,3→1→4, can take 2 per semester
2
Dependency Resolution
Build prerequisite graph and find valid course combinations
3
Optimal Schedule
Minimum 3 semesters: {2,3} → {1} → {4}
Key Takeaway
🎯 Key Insight: Use bitmask DP to efficiently track course completion states and find optimal semester scheduling
Asked in
Google 15 Facebook 12 Amazon 8
28.0K Views
Medium Frequency
~35 min Avg. Time
856 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