Second shortest path
You are given a directed acyclic graph (DAG) on n nodes as edges [u, v, w] with positive integer weights, plus a source s and target t. Return the length of the SECOND smallest distinct path length from s to t (the next value strictly greater than the shortest-path length, considering all distinct path-length values). Return -1 if fewer than two distinct path lengths exist. Constraints: the graph is a DAG; up to 60 nodes; parallel edges allowed.
Implement
second_shortest(n: int, edges: list[list[int]], s: int, t: int) → intExamples
in
[4,[[0,1,1],[0,2,5],[1,3,2],[2,3,1]],0,3]out6What 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
solution.py
InputExpectedGot
[4,[[0,1,1],[0,2,5],[1,3,2],[2,3,1]],0,3]6not run yetsample