Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: A graph of flights has prices; find the cheapest price from src to dst using at most k stops (Bellman–Ford limited to k + 1 rounds).
Problem: A graph of flights has prices; find the cheapest price from src to dst using at most k stops (Bellman–Ford limited to k + 1 rounds).
def cheapest(n, flights, src, dst, k):
dist = [float('inf')] * n; dist[src] = 0
for _ in range(k + 1):
nd = dist[:]
for u, v, w in flights:
if dist[u] + w < nd[v]: nd[v] = dist[u] + w
dist = nd
return -1 if dist[dst] == float('inf') else dist[dst]
f = [(0, 1, 100), (1, 2, 100), (2, 3, 100), (0, 3, 500), (0, 2, 250)]
print(cheapest(4, f, 0, 3, 1), cheapest(4, f, 0, 3, 2), cheapest(4, f, 0, 3, 0))What is printed?- A. 300 300 500
- B. 350 300 500
- C. 350 350 500
- D. 350 300 -1
Correct answer: B. 350 300 500
Round i allows paths with at most i edges. With 1 stop (2 edges): 0→2→3 = 350. With 2 stops: 0→1→2→3 = 300. With 0 stops only the direct 500. Copying dist into nd is essential – relaxing in place could chain several edges in one round and ignore the stop limit. O(k·E). Plain Dijkstra ignores the stop limit.
More Coding Interview Problems questions
- Problem: Count connected components of an undirected graph given as an edge list on n nodes. cpp int find(vector<int>& p, int x) { return…
- Problem: Return the k-th largest value in a stream of scores using a min-heap of size k. python import heapq def kthlargest(a, k): h = []…
- Problem: From n = 10⁶ log entries, return the k = 10 most frequent error codes. Which approach is the most efficient?
- Problem: Merge k sorted lists of order timestamps into one sorted list. python import heapq def mergek(lists): h = [(l[0], i, 0) for i, l…
- Problem: Maintain the median of a stream with two heaps (max-heap for the lower half, min-heap for the upper half). python import heapq…
- Problem: Connect ropes into one; joining two ropes costs the sum of their lengths. Find the minimum total cost. python import heapq def…