Data Structures & AlgorithmsVery hardProduct company OA

Problem: Assign 4 workers to 4 jobs (one each) minimising total cost with a bitmask DP over the set of jobs already taken; compare with greedy row-by-row picking.

Problem: Assign 4 workers to 4 jobs (one each) minimising total cost with a bitmask DP over the set of jobs already taken; compare with greedy row-by-row picking.
from functools import lru_cache
C = ((9, 2, 7, 8), (6, 4, 3, 7), (5, 8, 1, 8), (7, 6, 9, 4))
def assign(cost):
    n = len(cost)
    @lru_cache(None)
    def f(i, mask):
        if i == n: return 0
        return min(cost[i][j] + f(i + 1, mask | 1 << j) for j in range(n) if not mask >> j & 1)
    return f(0, 0)
def greedy_assign(c):
    used = set(); tot = 0
    for row in c:
        j = min((v, j) for j, v in enumerate(row) if j not in used)[1]; used.add(j); tot += row[j]
    return tot
print(assign(C), greedy_assign(C))
What is printed?
  1. A. 10 14
  2. B. 13 14
  3. C. 13 13
  4. D. 14 13

Correct answer: B. 13 14

State (worker i, mask of used jobs): 2ⁿ·n states with n transitions → O(n²·2ⁿ), fine for n ≤ 20. Optimum: worker 0 → job 1 (2), worker 1 → job 0 (6), worker 2 → job 2 (1), worker 3 → job 3 (4) = 13. Greedy takes 2, then 3 for worker 1 (job 2), which forces worker 2 onto job 0 (5): 2 + 3 + 5 + 4 = 14. Summing row minima (10) ignores the one-job-each rule. The Hungarian algorithm does it in O(n³).

More Coding Interview Problems questions

Exams that ask this topic