949. Course Load Limit

A small college offers courses numbered 1 to n. Each entry [a, b] in relations means course a must be finished in an earlier semester before course b can be taken (they cannot be taken in the same semester). A student may take at most k courses in one semester, and may take fewer.

Return the minimum number of semesters needed to finish all n courses. If the prerequisite rules contain a cycle so that finishing everything is impossible, return -1. Relations are listed without duplicates and always have a != b.

Example 1

Input:
n = 5, relations = [[1,3],[2,3],[3,4],[3,5]], k = 2
Output:
3
Explanation:

Semester 1 takes courses 1 and 2, semester 2 takes course 3, and semester 3 takes courses 4 and 5; course 3 needs both 1 and 2 first, so 3 semesters is the minimum.

Example 2

Input:
n = 4, relations = [[1,2],[2,3],[3,4]], k = 3
Output:
4
Explanation:

The courses form a single chain, so each must be in its own semester and 4 semesters are needed regardless of the limit.

Constraints

  • 1 ≤ n ≤ 15
  • 0 ≤ relations.length ≤ n * (n - 1) / 2; each relation is [a, b] with 1 ≤ a, b ≤ n and a ≠ b, no repeated pair
  • 1 ≤ k ≤ n

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(2^n * C(n,k))
Space
O(2^n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…