Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Assign 4 workers to 4 jobs (one each) to minimise total cost, with a DP over the bitmask of used jobs.

Problem: Assign 4 workers to 4 jobs (one each) to minimise total cost, with a DP over the bitmask of used jobs.
cost = [[9, 2, 7, 8], [6, 4, 3, 7], [5, 8, 1, 8], [7, 6, 9, 4]]
n = 4; INF = float('inf'); dp = [INF] * (1 << n); dp[0] = 0
for m in range(1 << n):
    w = bin(m).count('1')
    if w == n or dp[m] == INF: continue
    for j in range(n):
        if not m >> j & 1:
            dp[m | 1 << j] = min(dp[m | 1 << j], dp[m] + cost[w][j])
print(dp[-1])
What is printed?
  1. A. 10
  2. B. 13
  3. C. 17
  4. D. 11

Correct answer: B. 13

Worker w = popcount(mask) is assigned next, so each mask is processed once: O(2ⁿ·n). The optimum is worker 0 → job 1 (2), worker 1 → job 0 (6), worker 2 → job 2 (1), worker 3 → job 3 (4) = 13. Greedy choosing each row's minimum clashes on job 2.

More Coding Interview Problems questions

Exams that ask this topic