Number of Restricted Paths From First to Last Node - Problem

There is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n, and an array edges where each edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with weight equal to weighti.

A path from node start to node end is a sequence of nodes [z0, z1, z2, ..., zk] such that z0 = start and zk = end and there is an edge between zi and zi+1 where 0 ≤ i ≤ k-1.

The distance of a path is the sum of the weights on the edges of the path. Let distanceToLastNode(x) denote the shortest distance of a path between node n and node x. A restricted path is a path that also satisfies that distanceToLastNode(zi) > distanceToLastNode(zi+1) where 0 ≤ i ≤ k-1.

Return the number of restricted paths from node 1 to node n. Since that number may be too large, return it modulo 109 + 7.

Input & Output

Example 1 — Basic Path
$ Input: n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,3]]
Output: 3
💡 Note: There are 3 restricted paths: 1→2→5, 1→3→5, and 1→4→5. Each path has decreasing distance to node 5.
Example 2 — Simple Chain
$ Input: n = 2, edges = [[1,2,1]]
Output: 1
💡 Note: Only one path exists: 1→2. Distance decreases from 1 to 0, so it's a valid restricted path.
Example 3 — Complex Graph
$ Input: n = 4, edges = [[1,2,1],[2,3,1],[3,4,1],[1,3,3]]
Output: 2
💡 Note: Two restricted paths exist: 1→2→3→4 and 1→3→4. Both satisfy the decreasing distance condition.

Constraints

  • 2 ≤ n ≤ 200
  • n-1 ≤ edges.length ≤ 2 * 104
  • edges[i].length == 3
  • 1 ≤ ui, vi ≤ n
  • ui ≠ vi
  • 1 ≤ weighti ≤ 106
  • There is at most one edge between any two nodes

Visualization

Tap to expand
Restricted Paths: Distance Must Always Decrease12345332132StartTargetValid paths: 1→2→5, 1→3→5, 1→4→5Each path has decreasing distance to node 5Answer: 3 restricted paths
Understanding the Visualization
1
Input Graph
Weighted undirected graph with nodes 1 to n
2
Find Restricted Paths
Paths from 1 to n where distance to n decreases
3
Count Valid Paths
Return total count modulo 10^9 + 7
Key Takeaway
🎯 Key Insight: A restricted path requires distance to destination to always decrease at each step
Asked in
Google 12 Amazon 8 Microsoft 6 Facebook 4
18.5K Views
Medium Frequency
~35 min Avg. Time
342 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