Shortest path with negative weights
Given a directed weighted graph with n nodes (0..n-1) and edges [u, v, w] where weights may be negative, compute the shortest distance from node src to every node. Return a list of length n: entry i is the shortest distance to i, or the string "INF" if unreachable, or the string "NEG" if the shortest distance is unbounded below because i is reachable through a negative-weight cycle. The source's distance is 0 (unless it itself sits on/after a negative cycle).
Implement
bellman_ford(n: int, edges: list[list[int]], src: int) → listExamples
in
[5,[[0,1,6],[0,2,7],[1,2,8],[1,3,5],[1,4,-4],[2,3,-3],[2,4,9],[3,1,-2],[4,0,2],[4,3,7]],0]out[0,2,7,4,-2]What a strong answer looks like
State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.
0:00 of about 40 min
solution.py
InputExpectedGot
[5,[[0,1,6],[0,2,7],[1,2,8],[1,3,5],[1,4,-4],[2,3,-3],[2,4,9],[3,1,-2],[4,0,2],[4,3,7]],0][0,2,7,4,-2]not run yetsample