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?- A. 10
- B. 13
- C. 17
- 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
- Problem: Maximum independent set (largest set of pairwise non-adjacent nodes) in a TREE with a two-state DP. python from collections…
- Edge case: greedy coin change versus DP when the coin system is not canonical. python def greedy(coins, x): cnt = 0 for c in sorted(coins…
- Problem: Count the ways to climb n stairs taking 1, 3 or 5 steps at a time (order matters). python def ways(n): dp = [1] + [0] n for i in…
- Problem: Fractional knapsack — take items (or fractions) by value/weight ratio to maximise value within capacity. python def frac(items…
- Problem: One pass of Lomuto partition (pivot = last element) as used in quicksort. python def lomuto(a): p = a[-1]; i = -1 for j in…
- Problem: Count the swaps made by bubble sort and by selection sort on the same array. python def bubble(a): a = a[:]; s = 0 for i in…