Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard
Problem: A courier starts at depot 0, must visit every city exactly once and return to 0. Solve it with bitmask DP (Held–Karp).
Problem: A courier starts at depot 0, must visit every city exactly once and return to 0. Solve it with bitmask DP (Held–Karp).
INF = float('inf')
d = [[0, 10, 15, 20, 8],
[10, 0, 35, 25, 12],
[15, 35, 0, 30, 9],
[20, 25, 30, 0, 14],
[8, 12, 9, 14, 0]]
n = len(d)
dp = [[INF] * n for _ in range(1 << n)]; dp[1][0] = 0
for m in range(1 << n):
for u in range(n):
if dp[m][u] == INF: continue
for v in range(n):
if not m >> v & 1:
dp[m | 1 << v][v] = min(dp[m | 1 << v][v], dp[m][u] + d[u][v])
print(min(dp[(1 << n) - 1][u] + d[u][0] for u in range(n)))What is printed?- A. 73
- B. 68
- C. 82
- D. 79
Correct answer: A. 73
dp[mask][u] is the cheapest path from 0 visiting exactly the cities in mask and ending at u; closing the tour adds d[u][0]. The answer 73 matches checking all 24 orders, at O(2ⁿ·n²) instead of O(n!).
More Coding Interview Problems questions
- Problem: Sum a[i] XOR a[j] over all pairs i < j in O(n · bits) by counting, for each bit, how many numbers have it set. python def…
- Edge case: nCr mod p is computed with factorials and Fermat inverses. Here n ≥ p. python p = 7 fact = [1] 11 for i in range(1, 11)…
- Problem: Extended Euclid returns g = gcd(a, b) and integers x, y with a·x + b·y = g. python def eg(a, b): if b == 0: return a, 1, 0 g, x…
- Problem: A segment tree with lazy propagation supports 'add v to a[l..r]' and 'sum of a[l..r]' on an array of 8 zeros. python N = 8 t, lz…
- Problem: Count inversions (i < j, a[i] > a[j]) with a Fenwick tree over values, scanning from the right. python def inversions(a): n =…
- Problem: Return the longest word that can be built one letter at a time from other words in the list (every prefix must be present); ties…