Compute shortest path in cyclic graph
Company: Microsoft
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of graph algorithms and shortest-path computation in weighted directed graphs, including handling cycles, non-negative edge weights, self-loops, and related edge-case reasoning.
Constraints
- 1 <= n <= 2 * 10^5
- 0 <= len(edges) <= 3 * 10^5
- 0 <= u, v < n
- 0 <= w <= 10^9
- The graph is directed and may contain cycles, self-loops, and duplicate edges
Examples
Input: (5, [(0, 1, 2), (1, 2, 3), (2, 1, 1), (2, 3, 4), (0, 4, 10)], 0, 3)
Expected Output: 9
Explanation: The shortest path is 0 -> 1 -> 2 -> 3 with total cost 2 + 3 + 4 = 9.
Input: (3, [(0, 1, 5)], 0, 2)
Expected Output: -1
Explanation: Node 2 is not reachable from node 0.
Input: (4, [(0, 1, 2), (1, 2, 2)], 2, 2)
Expected Output: 0
Explanation: The source and target are the same node, so the shortest distance is 0.
Input: (4, [(0, 0, 7), (0, 1, 0), (1, 2, 0), (2, 1, 1), (2, 3, 5)], 0, 3)
Expected Output: 5
Explanation: The best path is 0 -> 1 -> 2 -> 3 with total weight 0 + 0 + 5 = 5. The self-loop and cycle do not improve the answer.
Input: (3, [(0, 1, 10), (0, 1, 3), (1, 2, 4), (0, 2, 20)], 0, 2)
Expected Output: 7
Explanation: There are multiple edges from 0 to 1. Using the cheaper one gives path 0 -> 1 -> 2 with cost 3 + 4 = 7.
Hints
- Since all edge weights are non-negative, think about using Dijkstra's algorithm with a min-heap.
- Store the best known distance to each node, and ignore heap entries that are worse than the current recorded distance.