787. Cheapest Flights Within K Stops
Medium
Problem:
Calculate the cheapest price from the starting point to the destination, but return the price that arrives within k stopovers. If a route does not exist, return -1.

https://leetcode.com/problems/cheapest-flights-within-k-stops/
Solution:
Time Limit Exceeded
Logic error
The problem I was facing is due to the way I was handling the dist dictionary. I was marking a node as visited once I've popped it from the priority queue, but this approach doesn't account for the possibility of reaching the same node through a different path with fewer stops or a lower cost.
Let's address the issues:
Instead of using the
distdictionary to track visited nodes, use it to track the minimum cost to reach each node. This way, you can prune paths that have a higher cost than a previously discovered path to the same node.The
resultdictionary is not necessary. You can track the minimum cost to reach the destination directly.The logic for checking the number of stops (
k) needs to be incorporated into the while loop to prune paths that exceed the allowed number of stops.
Modified, but still get "time limit exceeded"
Implement it in the same way as the previous Dijkstra's algorithm, but when adding to the priority queue for arriving within k stops, only add the path if it's within k, so that paths exceeding k are no longer explored.
Since there's no need to store the entire distance anymore, the
distdictionary is removed.Only the shortest path to the destination needs to be calculated, so there's no need to check the total number of paths either.
This code uses a breadth-first search (BFS) strategy with a priority queue to ensure that the path with the smallest cost is explored first. However, the algorithm can end up processing nodes multiple times, leading to an increase in the number of operations, especially when the graph is dense.
Optimization: Dijkstra's Algorithm
A way to avoid unnecessary computations is to keep track of the minimum cost to reach a particular node with a given number of stops. If you've already reached a node with a certain cost and a certain number of stops before, then you don't need to explore that state again.
Here's how you can optimize your code:
Add a
costarray to keep track of the lowest price to reach each node for a given number of stops.Before adding a state to the queue, check if the price is cheaper than a previously found price to get to that node with the same or fewer stops.
The above optimization ensures that we're not revisiting the same node-stop combination multiple times, which can reduce the number of operations and prevent a time limit exceeded error.
Bellman-Ford Algorithm
The drawing below illustrates the implementation of BFS for one layer. However, we need to execute it k + 1 times because in this context, 'k' represents a node while a layer represents an edge.


Time complexity: O(E⋅K)
Reference: https://www.youtube.com/watch?v=5eIK3zUdYmE
Last updated