Solving Leetcode Interviews in Seconds with AI: Parallel Courses II
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1494" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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. Example 1: Input: n = 4, relations = [[2,1],[3,1],[1,4]], k = 2 Output: 3 Explanation: The figure above represents the given graph. In the first semester, you can take courses 2 and 3. In the second semester, you can take course 1. In the third semester, you can take course 4. Example 2: Input: n = 5, relations = [[2,1],[3,1],[4,1],[1,5]], k = 2 Output: 4 Explanation: The figure above represents the given graph. In the first semester, you can only take courses 2 and 3 since you cannot take more than two per semester. In the second semester, you can take course 4. In the third semester, you can take course 1. In the fourth semester, you can take course 5. 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 directed acyclic graph.
Explanation
- Represent Prerequisites and States: Use a bitmask to represent the state of courses taken. A bit set to 1 indicates the course is taken, and 0 indicates it's not. Track prerequisites using an adjacency list.
- Dynamic Programming with Memoization: Employ dynamic programming to explore all possible course-taking combinations. Memoize the minimum semesters required for each state to avoid redundant computations.
- Iterate Through Possible Course Combinations: For each state, identify available courses (prerequisites met and not yet taken). Then, iterate through all possible combinations of taking up to
kavailable courses in the current semester.
- Time Complexity: O(n 2n), *Space Complexity: O(2n)
Code
def min_semesters(n: int, relations: list[list[int]], k: int) -> int:
"""
Calculates the minimum number of semesters needed to take all courses
given prerequisites and a maximum courses per semester limit.
Args:
n: The number of courses.
relations: A list of prerequisite relationships (prevCourse, nextCourse).
k: The maximum number of courses that can be taken in one semester.
Returns:
The minimum number of semesters needed to take all courses.
"""
prerequisites = [0] * n
for prev, next_ in relations:
prerequisites[next_ - 1] |= (1 << (prev - 1))
dp = {} # Memoization for states (bitmask of taken courses)
def solve(mask):
if mask == (1 << n) - 1:
return 0 # All courses are taken
if mask in dp:
return dp[mask]
available_courses = []
for i in range(n):
if not (mask & (1 << i)) and (mask & prerequisites[i]) == prerequisites[i]:
available_courses.append(i)
min_semesters_needed = float('inf')
for i in range(1 << len(available_courses)):
# Generate all possible combinations of available courses
taken_count = 0
next_mask = mask
taken_courses = []
for j in range(len(available_courses)):
if (i >> j) & 1:
taken_count += 1
next_mask |= (1 << available_courses[j])
taken_courses.append(available_courses[j])
if 0 < taken_count <= k:
min_semesters_needed = min(min_semesters_needed, 1 + solve(next_mask))
dp[mask] = min_semesters_needed
return min_semesters_needed
return solve(0)