Compute shortest path in cyclic graph
MicrosoftSoftware Engineer · Technical ScreenLast updated
This question tests the ability to implement a shortest-path algorithm in a directed graph that may contain cycles, specifically evaluating the selection between Dijkstra's algorithm and Bellman-Ford based on edge weight constraints.
Shortest Path in a Cyclic Graph
You are given a directed graph represented as a list of edges, where each edge [u, v, w] indicates a directed path from node u to node v with weight w. The graph may contain cycles and self-loops. Your goal is to find the shortest distance from a starting node source to all other nodes in the graph.
Function Signature
def get_shortest_paths(n, edges, source):
Parameters
n: The number of nodes in the graph (labeled 0 to n-1).edges: A list of lists where each sub-list is[u, v, w].source: The starting node index.
Requirements
- Return a list of length
nwhere indexicontains the shortest path distance fromsourcetoi. - If a node is unreachable, return
float('inf')for that index. - Assume all weights
ware non-negative. - If a negative cycle exists, the function should identify it and raise a
ValueError.
Example
Input: n = 4, edges = [[0, 1, 5], [1, 2, 2], [2, 3, 1], [0, 3, 10]], source = 0
Output: [0, 5, 7, 8]
# Explanation: 0->1 is 5, 0->1->2 is 7, 0->1->2->3 is 8. Direct 0->3 is 10, so 8 is chosen.
Edge Cases
- Disconnected components.
- Graphs with cycles (but no negative weights).
- Self-loops (e.g.,
[1, 1, 5]). - Single node graph.
Hints
Hint 1
Since the graph contains cycles but edge weights are non-negative, Dijkstra's algorithm is the most efficient approach.
Hint 2
Use a min-priority queue to keep track of the node with the smallest known distance that has not yet been processed.
Hint 3
If negative edge weights were allowed, you would need to use the Bellman-Ford algorithm to handle cycles correctly.
Follow-up questions
- How would your implementation change if the graph contained negative edge weights but no negative cycles?
- What is the time complexity of your solution, and how does it change if you use a simple list instead of a priority queue?
- How would you modify the algorithm to return the actual path (the sequence of nodes) rather than just the total distance?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.