Question presented to candidate: "There are n cities and a list of one-way flights, each given as [from, to, price]. Given a source, a destination and a number K, find the cheapest price from source to destination with at most K stops, or return -1 if there is no such route. Please code it in Python."
What a strong answer should cover:
- Model it as a directed weighted graph and translate "at most K stops" into "at most K + 1 flights".
- Explain why plain Dijkstra is wrong here: a cheaper arrival with more flights can be a dead end, so the state must include the flight count.
- Bounded Bellman-Ford: K + 1 rounds of relaxing every flight, reading last round's prices and writing a copy (
cost[:]), in O((K + 1) ยท E) time and O(n) space. - The alternative Dijkstra over (cost, flights, city) states with
heapq, and why it can skip a pop only when an earlier pop used no more flights. - Python details:
float("inf")as "unreachable" (and converting it back to -1),cost[:]orlist(cost)for a shallow copy, andheapqbeing a min-heap over tuples. - Edge cases: source equals destination, unreachable destination, K = 0.
Clarifying questions expected:
- Does K stops mean K intermediate cities, so K + 1 flights?
- Are prices always positive, and what should be returned when there is no route?
Code / implementation expected: Yes โ find_cheapest_price(n, flights, src, dst, k) in Python 3, with bounded Bellman-Ford (or a heap-based state search).