Code RoomJohnson shortest paths
HardPrep Room Coding #1028

Johnson shortest paths

CodingAlgorithms & data structuresSenior–Staff~35 min

Given a directed weighted graph with n nodes (0..n-1) and edges [u, v, w] where w may be negative, compute the shortest-path distances from a given source to every node using Johnson's reweighting technique (a virtual node with 0-weight edges to all, one Bellman-Ford pass to get potentials, then Dijkstra on the reweighted non-negative graph, then undo the reweighting). Return a list dist where dist[v] is the shortest distance from src to v, or -1 if v is unreachable; if the graph contains a negative cycle, return an empty list. Assume 1 <= n <= 300.

Implement
johnson_apsp_from_source(n: int, edges: list[list[int]], src: int) → list[int]
Examples
in[4,[[0,1,1],[1,2,2],[0,2,5],[2,3,1]],0]out[0,1,3,4]
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 35 min
InputExpectedGot
[4,[[0,1,1],[1,2,2],[0,2,5],[2,3,1]],0][0,1,3,4]not run yetsample