Data Structures & AlgorithmsVery hardProduct company OA

Problem: Courses with prerequisites; at most k = 2 courses per semester. Exact DP over bitmasks of finished courses versus 'take the k lowest-numbered available courses'.

Problem: Courses with prerequisites; at most k = 2 courses per semester. Exact DP over bitmasks of finished courses versus 'take the k lowest-numbered available courses'.
from functools import lru_cache
def semesters(n, pre, k):
    need = [0] * n
    for a, b in pre: need[b] |= 1 << a
    full = (1 << n) - 1
    @lru_cache(None)
    def go(done):
        if done == full: return 0
        avail = [i for i in range(n) if not done >> i & 1 and need[i] & done == need[i]]
        if len(avail) <= k:
            m = 0
            for i in avail: m |= 1 << i
            return 1 + go(done | m)
        best = 99
        sub = 0
        am = sum(1 << i for i in avail)
        sub = am
        while sub:
            if bin(sub).count("1") == k: best = min(best, 1 + go(done | sub))
            sub = (sub - 1) & am
        return best
    return go(0)
def greedy(n, pre, k):
    need = [0] * n
    for a, b in pre: need[b] |= 1 << a
    done, sem = 0, 0
    while done != (1 << n) - 1:
        avail = [i for i in range(n) if not done >> i & 1 and need[i] & done == need[i]][:k]
        for i in avail: done |= 1 << i
        sem += 1
    return sem
pre = [(1, 4), (4, 5), (5, 6), (0, 6)]
print(semesters(7, pre, 2), greedy(7, pre, 2))
What is printed?
  1. A. 5 5
  2. B. 4 4
  3. C. 3 5
  4. D. 4 5

Correct answer: D. 4 5

Chain 1 → 4 → 5 → 6 needs 4 semesters on its own, and 6 also needs 0, so 4 is a lower bound. The DP finds 4 by taking course 1 in the FIRST semester. The greedy takes 0 and 1, then 2 and 3 (lowest indices) instead of 4, which delays the chain: 4, 5, 6 then take one semester each → 5. Choosing which available courses to take is the hard part (the problem is NP-hard in general), so with n ≤ 15 the intended solution enumerates submasks: O(3ⁿ).

More Coding Interview Problems questions

Exams that ask this topic