Parallel Courses II

Hard Dynamic Programming Bitmask DP

Reported atAmazonSnowflake

Parallel Courses II is a hard dynamic programming problem solved with the bitmask dp pattern. The best approach, optimal (bottom-up bitmask dp), runs in O(3^n + 2^n · n) time and O(2^n) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (try every group, recursively) up.

Problem

There are n courses, numbered from 1 to n. Each entry relations[i] = [prev, next] says that course prev must be finished in an earlier semester than course next.

In one semester you may take at most k courses, and only courses whose prerequisites were all finished in earlier semesters.

Return the fewest semesters needed to finish all n courses. The prerequisites never form a cycle, so finishing everything is always possible.

Watch out: picking the “most important” courses first, such as the ones with the longest chain of courses after them or the most courses waiting on them, does not always give the best schedule. Example 3 is one such case.

Examples

Example 1

Input
n = 5, relations = [[1,2],[2,3]], k = 2
Output
3
Why
Courses 1, 2 and 3 form a chain, so they need three semesters no matter what. Pair each chain course with a free one: {1, 4}, then {2, 5}, then {3}. Taking the free courses 4 and 5 first would waste a semester and give 4.

Example 2

Input
n = 4, relations = [[1,4],[2,4],[3,4]], k = 2
Output
3
Why
Course 4 needs 1, 2 and 3, but only two of them fit in the first semester. So: {1, 2}, then {3}, then {4}.

Example 3

Input
n = 8, relations = [[1,5],[1,7],[2,5],[3,4],[3,7],[4,6],[5,6],[5,7],[5,8]], k = 2
Output
4
Why
Course 5 unlocks three courses and needs 1 and 2, so take {1, 2} first. Then {3, 5}, then {4, 7}, then {6, 8}. Starting with {1, 3}, the two courses with the longest chains and the most dependents, needs 5 semesters.

Constraints

  • 1 <= n <= 15
  • 1 <= k <= n
  • 0 <= relations.length <= n * (n - 1) / 2
  • relations[i] = [prev, next] with 1 <= prev, next <= n and prev != next
  • All pairs are distinct, and the prerequisites never form a cycle, so every course can be finished.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 15 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (try every group, recursively)ExponentialO(n)
Memoized recursion over sets (top-down bitmask DP)O(3^n + 2^n · n)O(2^n)
Optimal (bottom-up bitmask DP)O(3^n + 2^n · n)O(2^n)

1Brute force (try every group, recursively)

TimeExponentialEach semester can branch into C(m, k) groups, where m is the number of available courses, and nothing is remembered, so the same sets are solved many times.
SpaceO(n)The prerequisite masks and a recursion at most n semesters deep.

Describe the state by the set of finished courses, stored as a bitmask. From a state, find the available courses: not finished, with every prerequisite finished. If there are at most k of them, take them all, since finishing more courses never hurts. Otherwise try every group of exactly k available courses, recurse on the new set, and keep the best. This explores every sensible schedule, so it is correct, but the same sets are reached again and again along different paths.

  1. Build pre[c], the bitmask of prerequisites of course c (0-based).
  2. solve(taken): if every course is in taken, return 0.
  3. Compute avail: every course c not in taken with (pre[c] & taken) == pre[c].
  4. If avail has at most k courses, return 1 + solve(taken | avail).
  5. Otherwise walk the submasks of avail; for each one with exactly k bits, try 1 + solve(taken | sub) and keep the minimum.
class Solution {
    private int n, k;
    private int[] pre;

    public int minNumberOfSemesters(int n, int[][] relations, int k) {
        this.n = n;
        this.k = k;
        pre = new int[n];
        for (int[] r : relations) pre[r[1] - 1] |= 1 << (r[0] - 1);
        return solve(0);
    }

    // fewest semesters left when the courses in taken are done
    private int solve(int taken) {
        if (taken == (1 << n) - 1) return 0;
        int avail = 0;
        for (int c = 0; c < n; c++)
            if ((taken >> c & 1) == 0 && (pre[c] & taken) == pre[c]) avail |= 1 << c;
        if (Integer.bitCount(avail) <= k) return 1 + solve(taken | avail);
        int best = Integer.MAX_VALUE;
        for (int sub = avail; sub > 0; sub = (sub - 1) & avail)
            if (Integer.bitCount(sub) == k) best = Math.min(best, 1 + solve(taken | sub));
        return best;
    }
}

2Memoized recursion over sets (top-down bitmask DP)

TimeO(3^n + 2^n · n)Each of the 2^n sets is solved once: n steps to find its available courses, plus a walk over the submasks of the courses not yet taken. Summed over all sets, those submask walks are at most 3^n.
SpaceO(2^n)The memo array has 2^n entries; the recursion is at most n deep.

The answer from a state depends only on which courses are finished, not on how we got there. There are at most 2^n sets, so store each answer the first time it is computed and reuse it. The recursion is the same as the brute force, plus a memo array indexed by the mask.

  1. Build pre[c] as before, and a memo array of size 2^n filled with -1.
  2. solve(taken): if taken is the full set, return 0; if memo[taken] is known, return it.
  3. Compute avail. If it has at most k courses, the answer is 1 + solve(taken | avail).
  4. Otherwise try every submask of avail with exactly k bits and keep the smallest 1 + solve(taken | sub).
  5. Store the result in memo[taken] and return it.
class Solution {
    private int n, k;
    private int[] pre, memo;

    public int minNumberOfSemesters(int n, int[][] relations, int k) {
        this.n = n;
        this.k = k;
        pre = new int[n];
        for (int[] r : relations) pre[r[1] - 1] |= 1 << (r[0] - 1);
        memo = new int[1 << n];
        Arrays.fill(memo, -1);
        return solve(0);
    }

    private int solve(int taken) {
        if (taken == (1 << n) - 1) return 0;
        if (memo[taken] != -1) return memo[taken];
        int avail = 0;
        for (int c = 0; c < n; c++)
            if ((taken >> c & 1) == 0 && (pre[c] & taken) == pre[c]) avail |= 1 << c;
        int best;
        if (Integer.bitCount(avail) <= k) {
            best = 1 + solve(taken | avail);
        } else {
            best = Integer.MAX_VALUE;
            for (int sub = avail; sub > 0; sub = (sub - 1) & avail)
                if (Integer.bitCount(sub) == k) best = Math.min(best, 1 + solve(taken | sub));
        }
        memo[taken] = best;
        return best;
    }
}

3Optimal (bottom-up bitmask DP)

TimeO(3^n + 2^n · n)There are 2^n masks; each needs n steps to find its available courses and a walk over the submasks of its available set. A course is either taken, in the submask, or neither, which bounds the total submask work by 3^n, about 14 million for n = 15.
SpaceO(2^n)One dp entry per set of courses, plus n prerequisite masks.

Turn the recursion around. Let dp[mask] be the fewest semesters needed to have finished exactly the courses in mask. Taking courses only adds bits, so a set is always numerically larger than any set it came from, and walking the masks in increasing order processes every set after all the sets that lead to it. From each reachable mask, compute the available courses and push dp[mask] + 1 forward to mask | group, for every group of min(k, available) courses. The answer is dp of the full set.

  1. Build pre[c], the prerequisite mask of each course. Fill dp with infinity and set dp[0] = 0.
  2. For mask from 0 up to full - 1, skip it if dp[mask] is infinity (that set can never happen).
  3. Compute avail, the courses not in mask whose prerequisites are all in mask, and take = min(k, bitCount(avail)).
  4. For every submask sub of avail with exactly take bits: dp[mask | sub] = min(dp[mask | sub], dp[mask] + 1).
  5. Return dp[full].
class Solution {
    public int minNumberOfSemesters(int n, int[][] relations, int k) {
        int[] pre = new int[n];
        for (int[] r : relations) pre[r[1] - 1] |= 1 << (r[0] - 1);
        int full = (1 << n) - 1;
        int[] dp = new int[1 << n];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;
        for (int mask = 0; mask < full; mask++) {
            if (dp[mask] == Integer.MAX_VALUE) continue;
            int avail = 0;
            for (int c = 0; c < n; c++)
                if ((mask >> c & 1) == 0 && (pre[c] & mask) == pre[c]) avail |= 1 << c;
            int take = Math.min(k, Integer.bitCount(avail));
            for (int sub = avail; sub > 0; sub = (sub - 1) & avail) {
                if (Integer.bitCount(sub) != take) continue;
                dp[mask | sub] = Math.min(dp[mask | sub], dp[mask] + 1);
            }
        }
        return dp[full];
    }
}

Edge cases to test

  • No relations: the answer is n / k rounded up
  • k = 1: one course per semester, so the answer is n
  • k >= n: the limit never bites, and the answer is the length of the longest prerequisite chain
  • A single course
  • A long chain: the answer is at least the number of courses in the longest chain, whatever k is
  • Greedy picks fail: taking the courses with the longest chain below them, or the most dependents, can cost an extra semester

Hints

Hint 1

With n at most 15, a set of finished courses fits in one integer: bit c is 1 when course c + 1 is done. There are only 2^15 = 32768 such sets.

Hint 2

Given the set of finished courses, which courses could you take now? Those not yet done whose prerequisite set is inside the finished set.

Hint 3

If at most k courses are available, take them all: having more courses done is never worse. If more than k are available, the right choice is not obvious, so try every group of exactly k.

Hint 4

Let dp[mask] be the fewest semesters to finish exactly the courses in mask. Go through the masks in increasing order and push dp[mask] + 1 to mask | group for every allowed group.

FAQ

What is the best time complexity for Parallel Courses II?

Optimal (bottom-up bitmask DP) runs in O(3^n + 2^n · n) time and O(2^n) extra space. There are 2^n masks; each needs n steps to find its available courses and a walk over the submasks of its available set. A course is either taken, in the submask, or neither, which bounds the total submask work by 3^n, about 14 million for n = 15.

Which pattern does Parallel Courses II use?

It is a dynamic programming problem that uses the bitmask dp pattern. Other problems with the same pattern: Optimal Account Balancing, Smallest Sufficient Team, Frequencies of Shortest Supersequences.

Is there a brute force solution for Parallel Courses II?

Yes. Brute force (try every group, recursively) takes Exponential time and O(n) space. Describe the state by the set of finished courses, stored as a bitmask.

Which edge cases should I test for Parallel Courses II?

No relations: the answer is n / k rounded up; k = 1: one course per semester, so the answer is n; k = n: the limit never bites, and the answer is the length of the longest prerequisite chain; A single course; A long chain: the answer is at least the number of courses in the longest chain, whatever k is; Greedy picks fail: taking the courses with the longest chain below them, or the most dependents, can cost an extra semester.