We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Parallel Courses II

Number: 1587

Difficulty: Hard

Paid? No

Companies: Google, Microsoft, TikTok


Problem Description

You are given n courses labeled from 1 to n along with prerequisite relations. In a single semester you can take at most k courses if you have finished all their prerequisites in earlier semesters. The objective is to determine the minimum number of semesters required to complete all courses.


Key Insights

  • Use bitmasking to represent the set of courses taken. Since n is at most 15, a bitmask is an ideal representation for subsets.
  • For each course, precompute a bitmask that indicates its prerequisite courses.
  • Use Dynamic Programming (DP) where the state is a bitmask of completed courses. The DP transition involves selecting a valid subset of the available courses (with prerequisites met) that can be taken in the next semester.
  • When the number of available courses exceeds k, iterate through all submasks (subsets) of the available courses and consider those with at most k courses.
  • This problem involves a combination of bit manipulation and DP with state space of size 2^n, which is manageable given the constraint n <= 15.

Space and Time Complexity

Time Complexity: O(2^n * n * 2^k) in worst-case since for each state (2^n) we might enumerate subsets (up to 2^k) and check prerequisites which is O(n) per state. Space Complexity: O(2^n) for the DP table.


Solution

We use a bitmask DP approach where each state represents the set of courses taken so far. First, for every course, we compute a prerequisite mask showing which courses must be completed before taking that course. The DP state dp[mask] stores the minimum semesters required to reach that state.

For each state, we calculate the available courses which are not taken yet and whose prerequisites are all met in the current mask. If the number of available courses is less than or equal to k, we can take them all; otherwise, we iterate through all submasks of the available set that contain at most k courses and update the DP state accordingly.

Data structures used:

  • Integer bitmask for set representation.
  • Array dp of size 2^n for storing the minimum number of semesters for each state.

The algorithm leverages bit manipulation techniques for checking prerequisites and enumerating submasks.


Code Solutions

# Python solution for Parallel Courses II

from collections import deque

def minNumberOfSemesters(n, relations, k):
    # Build prerequisite mask for each course (using 0-indexing)
    prereq = [0] * n
    for pre, course in relations:
        prereq[course - 1] |= 1 << (pre - 1)  # Set bit for pre-course

    # Initialize DP table with high values; DP state space is 2^n states
    dp = [float('inf')] * (1 << n)
    dp[0] = 0  # no courses taken, 0 semesters
    
    # Process states
    for mask in range(1 << n):
        # Determine available courses for current mask
        available = 0
        for course in range(n):
            # If course not taken and its prerequisites are met in the mask
            if mask & (1 << course) == 0 and (mask & prereq[course]) == prereq[course]:
                available |= (1 << course)
        
        # If number of available courses <= k then take all them in one semester
        if bin(available).count("1") <= k:
            dp[mask | available] = min(dp[mask | available], dp[mask] + 1)
        else:
            # Enumerate submask of available courses
            submask = available
            while submask:
                # Only consider submask with at most k courses
                if bin(submask).count("1") <= k:
                    dp[mask | submask] = min(dp[mask | submask], dp[mask] + 1)
                # Move to next submask
                submask = (submask - 1) & available

    # Full mask representing all courses taken
    return dp[(1 << n) - 1]

# Example usage
#print(minNumberOfSemesters(4, [[2,1],[3,1],[1,4]], 2))
← Back to All Questions