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?
  1. A. 300 300 500
  2. B. 350 300 500
  3. C. 350 350 500
  4. 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

Exams that ask this topic