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 Problem0123STARTENDGreen edges: Part of shortest path (distance = 3)Gray edges: Not on any shortest pathOutput: [true, true, false, false]
Understanding the Visualization
1
Input Graph
Weighted undirected graph with start node 0 and end node n-1
2
Find Shortest Paths
Use Dijkstra to compute shortest distances from both ends
3
Mark Valid Edges
Edge is valid if dist[0→u] + weight + dist[v→n-1] equals total shortest distance
Key Takeaway
🎯 Key Insight: An edge lies on a shortest path if the total distance through it equals the shortest path distance
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