PPractick

DSA interview question

Cheapest Flights Within K Stops

Hard · Algorithms · Topics: graph, bellman ford, dp

The problem

A travel site searches for the cheapest itinerary from city src to city dst using at most k stops (so at most k + 1 flights). Plain Dijkstra optimises cost alone and can pick a cheap route with too many stops. The clean solution is Bellman–Ford limited to k + 1 rounds. After round i, dist[v] is the cheapest cost using at most i flights. Each round must relax from a copy of the previous round's distances, so a single round can't chain several flights together.

Example: 4 cities, flights 0→1 (100), 1→2 (100), 2→0 (100), 1→3 (600), 2→3 (200), src 0, dst 3, k = 1 → 700.

Function signature

int findCheapestPrice(int n, const vector<array<int, 3>>& flights, int src, int dst, int k);  // -1 if impossible

Test cases

Input (n, flights, src, dst, k)OutputExplanation
(4, [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], 0, 3, 1)7000-1-3; the cheaper 0-1-2-3 needs 2 stops
(3, [[0,1,100],[1,2,100],[0,2,500]], 0, 2, 1)200
(3, [[0,1,100],[1,2,100],[0,2,500]], 0, 2, 0)500No stops: direct only
(3, [[0,1,100]], 0, 2, 1)-1No route
(2, [[0,1,5]], 0, 1, 0)5

(Confirm: flights are directed with positive prices; "k stops" means at most k + 1 flights.)

How interviewers phrase it

Clarifying questions to ask

  1. Does k count intermediate cities or flights? (Intermediate stops, so k + 1 flights.)
  2. Are prices positive? (Yes.)
  3. How large? (n ≤ 100 cities, so O(k · E) is fine.)

Follow-ups to expect

  1. "Why not plain Dijkstra?"
  2. "Why copy the distances each round?"
  3. "BFS alternative?"
  4. "What happens to cycles?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in