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?
  1. A. 73
  2. B. 68
  3. C. 82
  4. 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

Exams that ask this topic