Number of Ways to Arrive at Destination - Problem

You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections.

You are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means that there is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time.

Return the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo 109 + 7.

Input & Output

Example 1 — Basic Graph
$ Input: n = 4, roads = [[0,1,1],[0,2,3],[1,3,2],[2,3,1]]
Output: 1
💡 Note: There are two paths from 0 to 3: 0→1→3 (time 3) and 0→2→3 (time 4). Only one path has the shortest time of 3.
Example 2 — Multiple Shortest Paths
$ Input: n = 3, roads = [[0,1,1],[0,2,1],[1,2,1]]
Output: 2
💡 Note: Two shortest paths from 0 to 2: direct path 0→2 (time 1) and path 0→1→2 (time 2). Wait, direct path is shorter, so answer is 1.
Example 3 — Single Path
$ Input: n = 2, roads = [[0,1,5]]
Output: 1
💡 Note: Only one path from 0 to 1 with time 5, so count is 1.

Constraints

  • 1 ≤ n ≤ 200
  • n - 1 ≤ roads.length ≤ n * (n - 1) / 2
  • roads[i].length == 3
  • 0 ≤ ui, vi ≤ n - 1
  • 1 ≤ timei ≤ 109
  • ui != vi

Visualization

Tap to expand
Number of Ways to Arrive at Destination01231321StartDestinationPath 1: 0→1→3 (time: 1+2=3) ✓Path 2: 0→2→3 (time: 3+1=4) ✗Result: 1 way with shortest time 3
Understanding the Visualization
1
Input Graph
Weighted undirected graph with intersections and travel times
2
Find Shortest Paths
Use Dijkstra to find minimum time and count paths achieving it
3
Output Count
Return number of shortest paths modulo 10^9 + 7
Key Takeaway
🎯 Key Insight: Use Dijkstra's algorithm while tracking path counts - reset count on shorter path, add count on equal path
Asked in
Google 15 Facebook 12 Amazon 8
28.0K Views
Medium Frequency
~25 min Avg. Time
890 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