Compute minimum semesters to finish courses
Company: Netflix
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates graph theory and scheduling competencies, including dependency resolution, cycle detection in directed graphs, and capacity-constrained task scheduling based on prerequisites.
Part 1: Minimum Semesters with Unlimited Courses per Semester
Constraints
- 1 <= n <= 100000
- 0 <= len(prereq) <= 200000
- 1 <= a, b <= n
- All prerequisite pairs are distinct.
Examples
Input: (3, [[1, 3], [2, 3]])
Expected Output:
Explanation: Courses 1 and 2 can be taken in semester 1, then course 3 in semester 2.
Input: (4, [[1, 2], [2, 3], [3, 4]])
Expected Output:
Explanation: This is a chain, so only one new course becomes available each semester.
Input: (3, [[1, 2], [2, 3], [3, 1]])
Expected Output:
Explanation: The courses form a cycle, so no valid completion order exists.
Input: (1, [])
Expected Output:
Explanation: Edge case: a single course with no prerequisites takes one semester.
Input: (4, [])
Expected Output:
Explanation: With no prerequisites, all courses can be taken in the first semester.
Hints
- Courses with zero remaining prerequisites can all be taken in the current semester.
- If you process the graph level by level with topological sorting, each level corresponds to one semester.
Part 2: Minimum Semesters with at Most k Courses per Semester
Constraints
- 1 <= n <= 15
- 0 <= len(prereq) <= n * (n - 1) / 2
- 1 <= k <= n
- 1 <= a, b <= n
- All prerequisite pairs are distinct.
Examples
Input: (4, [[1, 4], [2, 4]], 2)
Expected Output:
Explanation: Take courses 1 and 2 first to unlock 4, then take 3 and 4 in the second semester.
Input: (4, [[1, 2], [1, 3], [2, 4], [3, 4]], 2)
Expected Output:
Explanation: Take 1, then 2 and 3, then 4.
Input: (5, [], 2)
Expected Output:
Explanation: With no prerequisites, the answer is ceil(5 / 2) = 3.
Input: (3, [[1, 2], [2, 3], [3, 1]], 2)
Expected Output:
Explanation: A cycle makes it impossible to finish all courses.
Input: (1, [], 1)
Expected Output:
Explanation: Edge case: one course and capacity 1.
Hints
- Represent the set of completed courses as a bitmask.
- From each state, find all currently available courses. If there are more than k, try every subset of size k and use BFS or DP to find the fewest semesters.