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 - Bitmask DP INPUT Course Dependency Graph 2 3 1 4 n = 4, k = 2 relations = [[2,1],[3,1],[1,4]] Max 2 courses per semester ALGORITHM STEPS 1 Encode State as Bitmask Each bit = course taken/not 0 0 0 0 4 3 2 1 2 Find Available Courses Prerequisites satisfied 3 Enumerate Subsets Try all subsets of size <= k 4 DP Transition dp[new_mask] = min(dp[mask]+1) State Transitions Sem1: Take {2,3} 0000 --> 0110 Sem2: Take {1} 0110 --> 0111 Sem3: Take {4} 0111 --> 1111 FINAL RESULT Optimal Course Schedule Semester 1 2 3 Semester 2 1 Semester 3 4 Output: 3 [OK] Minimum semesters = 3 All courses completed! Key Insight: Bitmask DP encodes which courses are completed (2^n states). For each state, find all courses with satisfied prerequisites and try all subsets of size <= k. Enumerate subsets efficiently using bit manipulation: for(s=avail; s; s=(s-1)&avail). Time: O(3^n * n), Space: O(2^n). TutorialsPoint - Parallel Courses II | Dynamic Programming with Bitmask
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