ntree.ai
ntree.aiParallel Courses

Parallel Courses

hardsolvedattempted

There are n courses, numbered from 1 to n. Each pair [before, after] in relations means course before has to be taken before course after.

In one semester you can take at most k courses, as long as every course you take had all its prerequisites finished in earlier semesters.

Return the fewest semesters needed to take every course. The relations never form a cycle, so every course can be taken.

Example 1:

Input:  n = 4, relations = [[2, 1], [3, 1], [1, 4]], k = 2
Output: 3
Explanation: take 2 and 3 in the first semester, 1 in the second and 4 in the third.

Example 2:

Input:  n = 5, relations = [[2, 1], [3, 1], [4, 1], [1, 5]], k = 2
Output: 4
Explanation: 2, 3 and 4 are all available at first, but only two fit in a semester. Course 1 needs all three, so it comes in the third semester and 5 in the fourth.

Constraints:

  • 1 <= n <= 15
  • 1 <= k <= n
  • 0 <= length of relations <= n * (n - 1) / 2
  • every pair in relations is different, and they never form a cycle
def minNumberOfSemesters(n: int, relations: list[list[int]], k: int) -> int:
pass
 

Press Visualise to step through your code.