Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
Problem: n ≤ 18 cities, find the shortest route visiting every city exactly once (travelling salesman). Which approach fits?
- A. Try all permutations – O(n!) ≈ 6.4 × 10¹⁵
- B. Greedy nearest neighbour – always optimal
- C. Bitmask DP over (visited set, last city) – O(2ⁿ · n²) ≈ 8.5 × 10⁷
- D. Dijkstra from the start city – O(E log V)
Correct answer: C. Bitmask DP over (visited set, last city) – O(2ⁿ · n²) ≈ 8.5 × 10⁷
Held–Karp stores the best cost for each subset ending at each city: 2¹⁸ × 18 states with 18 transitions each. Permutations explode, nearest-neighbour is only a heuristic, and Dijkstra solves a different problem (it does not force visiting all cities).
More Coding Interview Problems questions
- Problem: n = 10⁵ intervals; for each, count how many other intervals it overlaps. What is the best complexity?
- Problem: A function does for i in range(n): for j in range(i, n, i + 1): work(). What is its time complexity?
- Problem: A recursive function on n does O(1) work and makes two calls on n/2. What is T(n)?
- Problem: Inside a loop of n iterations, the code calls Python's list.pop(0) and Java's String +=. What is the real complexity of the loop?
- Problem: For n = 10⁶ distinct integers up to 10⁹, find the smallest positive integer missing from the array in O(n) time and O(1) extra…
- Problem: Find the smallest missing positive integer using cyclic placement. python def firstmissing(a): n = len(a) for i in range(n)…