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?- A. 5 5
- B. 4 4
- C. 3 5
- 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
- Problem: Count 'heavy pairs' i < j with a[i] > 2·a[j] in O(n log n) using a Fenwick tree over coordinate-compressed values (both x and 2x…
- Problem: A segment tree stores (sum, best prefix, best suffix, best subarray) per node to answer 'maximum subarray sum inside a[l..r]'…
- Problem: Smallest period of a log pattern from its KMP prefix function: per = n − π[n − 1], and s is a whole repetition only if per…
- Problem: Find the longest string that is a prefix of s, a suffix of s, and also occurs somewhere strictly inside (not as the prefix or the…
- Problem: Count pairs i < j with a[i] XOR a[j] < 6 using a binary trie that stores subtree counts (4-bit values). python def countless(a…
- Problem: For every contiguous block, score = (minimum of the block) × (sum of the block). Return the maximum score using a monotonic stack…