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?- A. 10 14
- B. 13 14
- C. 13 13
- 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
- Problem: Convert Roman numerals to integers: a symbol smaller than the one after it is subtracted. python def roman(s): v = {"I": 1, "V"…
- Problem: Is b a rotation of a? Check equal lengths and whether b occurs in a + a. python def isrot(a, b): return len(a) == len(b) and b in…
- Problem: String t is string s shuffled with one extra letter added. Find the extra letter by XOR-ing all character codes. python from…
- Problem: Look-and-say: read the previous term aloud in runs ("1" → "11" → "21" …). python def say(s): out, i = [], 0 while i < len(s): j =…
- Problem: Write a string in a zigzag over r rows (down, then diagonally up) and read it row by row. python def zigzag(s, rows): if rows ==…
- Problem: Compare dotted version strings numerically part by part (missing parts count as 0); return 1, 0 or −1. python def cmpver(a, b): x…