You are given an undirected weighted graph of n nodes numbered from 0 to n - 1. The graph consists of m edges represented by a 2D array edges, where edges[i] = [ai, bi, wi] indicates that there is an edge between nodes ai and bi with weight wi.

Consider all the shortest paths from node 0 to node n - 1 in the graph. You need to find a boolean array answer where answer[i] is true if the edge edges[i] is part of at least one shortest path. Otherwise, answer[i] is false.

Return the array answer.

Note: The graph may not be connected.

Input & Output

Example 1 — Basic Graph
$ Input: n = 4, edges = [[0,1,1],[1,3,2],[0,2,4],[2,3,1]]
Output: [true,true,false,false]
💡 Note: Shortest path from 0 to 3 has distance 3. Path 0→1→3 uses edges [0,1,1] and [1,3,2]. Alternative path 0→2→3 has distance 5, so edges [0,2,4] and [2,3,1] are not on shortest paths.
Example 2 — Multiple Shortest Paths
$ Input: n = 4, edges = [[0,1,1],[1,3,1],[0,2,1],[2,3,1]]
Output: [true,true,true,true]
💡 Note: Two shortest paths exist: 0→1→3 (distance 2) and 0→2→3 (distance 2). All edges participate in at least one shortest path.
Example 3 — Disconnected Graph
$ Input: n = 3, edges = [[0,1,1]]
Output: [false]
💡 Note: No path exists from 0 to 2, so no edge can be part of a shortest path from 0 to n-1.

Constraints

  • 2 ≤ n ≤ 1000
  • 1 ≤ edges.length ≤ 5000
  • edges[i] = [ai, bi, wi]
  • 0 ≤ ai, bi < n
  • ai ≠ bi
  • 1 ≤ wi ≤ 105

Visualization

Tap to expand
Find Edges in Shortest Paths INPUT 0 1 2 3 w=1 w=2 w=4 w=1 n = 4 edges = [[0,1,1], [1,3,2],[0,2,4], [2,3,1]] Find: 0 ---> 3 shortest paths Mark edges on any path ALGORITHM STEPS 1 Dijkstra from 0 dist[0]=0,dist[1]=1 dist[2]=4,dist[3]=3 2 Dijkstra from n-1 rdist[3]=0,rdist[1]=2 rdist[2]=1,rdist[0]=3 3 Check each edge Edge (a,b,w) on path if: dist[a]+w+rdist[b]=SP 4 Verify edges SP = dist[n-1] = 3 [0,1,1]: 0+1+2=3 OK [1,3,2]: 1+2+0=3 OK [0,2,4]: 0+4+1=5 != 3 [2,3,1]: 4+1+0=5 != 3 Green = on shortest path FINAL RESULT 0 1 2 3 true true false false Output: [true, true, false, false] Path 0-->1-->3 = 1+2 = 3 Edges [0,1] and [1,3] used Key Insight: An edge (a,b,w) lies on SOME shortest path from 0 to n-1 if and only if: dist_from_0[a] + w + dist_from_n1[b] == shortest_path_length Run Dijkstra twice (from node 0 and from node n-1), then check each edge in O(m) time. TutorialsPoint - Find Edges in Shortest Paths | Dijkstra with Path Reconstruction
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
12.5K Views
Medium Frequency
~35 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen