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 node1to noden. Since that number may be too large, return it modulo109 + 7.
Example 1:
Input: n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]
Output: 3
Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The three restricted paths are:
1) 1 --> 2 --> 5
2) 1 --> 2 --> 3 --> 5
3) 1 --> 3 --> 5
Example 2:
Input: n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]
Output: 1
Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The only restricted path is 1 --> 3 --> 7.
Problem summary: 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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
All Ancestors of a Node in a Directed Acyclic Graph (all-ancestors-of-a-node-in-a-directed-acyclic-graph)
Design Graph With Shortest Path Calculator (design-graph-with-shortest-path-calculator)
Minimum Cost of a Path With Special Roads (minimum-cost-of-a-path-with-special-roads)
Step 02
Core Insight
What unlocks the optimal approach
Run a Dijkstra from node numbered n to compute distance from the last node.
Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge.
Now this problem reduces to computing the number of paths from 1 to n in a DAG, a standard DP problem.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1786: Number of Restricted Paths From First to Last Node
class Solution {
private static final int INF = Integer.MAX_VALUE;
private static final int MOD = (int) 1e9 + 7;
private List<int[]>[] g;
private int[] dist;
private int[] f;
private int n;
public int countRestrictedPaths(int n, int[][] edges) {
this.n = n;
g = new List[n + 1];
for (int i = 0; i < g.length; ++i) {
g[i] = new ArrayList<>();
}
for (int[] e : edges) {
int u = e[0], v = e[1], w = e[2];
g[u].add(new int[] {v, w});
g[v].add(new int[] {u, w});
}
PriorityQueue<int[]> q = new PriorityQueue<>((a, b) -> a[0] - b[0]);
q.offer(new int[] {0, n});
dist = new int[n + 1];
f = new int[n + 1];
Arrays.fill(dist, INF);
Arrays.fill(f, -1);
dist[n] = 0;
while (!q.isEmpty()) {
int[] p = q.poll();
int u = p[1];
for (int[] ne : g[u]) {
int v = ne[0], w = ne[1];
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
q.offer(new int[] {dist[v], v});
}
}
}
return dfs(1);
}
private int dfs(int i) {
if (f[i] != -1) {
return f[i];
}
if (i == n) {
return 1;
}
int ans = 0;
for (int[] ne : g[i]) {
int j = ne[0];
if (dist[i] > dist[j]) {
ans = (ans + dfs(j)) % MOD;
}
}
f[i] = ans;
return ans;
}
}
// Accepted solution for LeetCode #1786: Number of Restricted Paths From First to Last Node
const inf = math.MaxInt32
const mod = 1e9 + 7
type pair struct {
first int
second int
}
var _ heap.Interface = (*pairs)(nil)
type pairs []pair
func (a pairs) Len() int { return len(a) }
func (a pairs) Less(i int, j int) bool {
return a[i].first < a[j].first || a[i].first == a[j].first && a[i].second < a[j].second
}
func (a pairs) Swap(i int, j int) { a[i], a[j] = a[j], a[i] }
func (a *pairs) Push(x any) { *a = append(*a, x.(pair)) }
func (a *pairs) Pop() any { l := len(*a); t := (*a)[l-1]; *a = (*a)[:l-1]; return t }
func countRestrictedPaths(n int, edges [][]int) int {
g := make([]pairs, n+1)
for _, e := range edges {
u, v, w := e[0], e[1], e[2]
g[u] = append(g[u], pair{v, w})
g[v] = append(g[v], pair{u, w})
}
dist := make([]int, n+1)
f := make([]int, n+1)
for i := range dist {
dist[i] = inf
f[i] = -1
}
dist[n] = 0
h := make(pairs, 0)
heap.Push(&h, pair{0, n})
for len(h) > 0 {
u := heap.Pop(&h).(pair).second
for _, ne := range g[u] {
v, w := ne.first, ne.second
if dist[v] > dist[u]+w {
dist[v] = dist[u] + w
heap.Push(&h, pair{dist[v], v})
}
}
}
var dfs func(int) int
dfs = func(i int) int {
if f[i] != -1 {
return f[i]
}
if i == n {
return 1
}
ans := 0
for _, ne := range g[i] {
j := ne.first
if dist[i] > dist[j] {
ans = (ans + dfs(j)) % mod
}
}
f[i] = ans
return ans
}
return dfs(1)
}
# Accepted solution for LeetCode #1786: Number of Restricted Paths From First to Last Node
class Solution:
def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:
@cache
def dfs(i):
if i == n:
return 1
ans = 0
for j, _ in g[i]:
if dist[i] > dist[j]:
ans = (ans + dfs(j)) % mod
return ans
g = defaultdict(list)
for u, v, w in edges:
g[u].append((v, w))
g[v].append((u, w))
q = [(0, n)]
dist = [inf] * (n + 1)
dist[n] = 0
mod = 10**9 + 7
while q:
_, u = heappop(q)
for v, w in g[u]:
if dist[v] > dist[u] + w:
dist[v] = dist[u] + w
heappush(q, (dist[v], v))
return dfs(1)
// Accepted solution for LeetCode #1786: Number of Restricted Paths From First to Last Node
/**
* [1786] Number of Restricted Paths From First to Last Node
*
* 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 10^9 + 7.
*
* Example 1:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/02/17/restricted_paths_ex1.png" style="width: 351px; height: 341px;" />
* Input: n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]
* Output: 3
* Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The three restricted paths are:
* 1) 1 --> 2 --> 5
* 2) 1 --> 2 --> 3 --> 5
* 3) 1 --> 3 --> 5
*
* Example 2:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/02/17/restricted_paths_ex22.png" style="width: 356px; height: 401px;" />
* Input: n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]
* Output: 1
* Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The only restricted path is 1 --> 3 --> 7.
*
*
* Constraints:
*
* 1 <= n <= 2 * 10^4
* n - 1 <= edges.length <= 4 * 10^4
* edges[i].length == 3
* 1 <= ui, vi <= n
* ui != vi
* 1 <= weighti <= 10^5
* There is at most one edge between any two nodes.
* There is at least one path between any two nodes.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node/
// discuss: https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
// Credit: https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node/solutions/1190377/rust-dijkstra-dfs-solution/
pub fn count_restricted_paths(n: i32, edges: Vec<Vec<i32>>) -> i32 {
let n = n as usize;
let adjancency_list = {
let mut res = vec![vec![]; n + 1];
for edge in edges {
let u = edge[0] as usize;
let v = edge[1] as usize;
let w = edge[2];
res[u].push((v, w));
res[v].push((u, w));
}
res
};
// Step1: use dijkstra to calc all shortest path from i to n.
let mut distances = vec![std::i32::MAX; n + 1];
distances[n] = 0;
let mut pq = std::collections::BinaryHeap::new();
pq.push((std::cmp::Reverse(0), n));
while let Some((std::cmp::Reverse(distance), u)) = pq.pop() {
for &(v, w) in &adjancency_list[u] {
let next_distance = distance + w;
if next_distance < distances[v] {
distances[v] = next_distance;
pq.push((std::cmp::Reverse(next_distance), v));
}
}
}
// Step2: use top-down dp to calc numbers of paths
let mut cache = std::collections::HashMap::new();
Self::dfs_helper(&adjancency_list, &distances, 1, &mut cache) as i32
}
fn dfs_helper(
adjancency_list: &[Vec<(usize, i32)>],
distances: &[i32],
u: usize,
cache: &mut std::collections::HashMap<usize, i64>,
) -> i64 {
if let Some(&cached) = cache.get(&u) {
return cached;
}
let mut result = 0;
for &(v, _) in &adjancency_list[u] {
if distances[v] == 0 {
result += 1;
} else if distances[u] > distances[v] {
result += Self::dfs_helper(adjancency_list, distances, v, cache);
}
}
result %= 1_000_000_007;
cache.insert(u, result);
result
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1786_example_1() {
let n = 5;
let edges = vec![
vec![1, 2, 3],
vec![1, 3, 3],
vec![2, 3, 1],
vec![1, 4, 2],
vec![5, 2, 2],
vec![3, 5, 1],
vec![5, 4, 10],
];
let result = 3;
assert_eq!(Solution::count_restricted_paths(n, edges), result);
}
#[test]
fn test_1786_example_2() {
let n = 7;
let edges = vec![
vec![1, 3, 1],
vec![4, 1, 2],
vec![7, 3, 4],
vec![2, 5, 3],
vec![5, 6, 1],
vec![6, 7, 2],
vec![7, 5, 3],
vec![2, 6, 4],
];
let result = 1;
assert_eq!(Solution::count_restricted_paths(n, edges), result);
}
}
// Accepted solution for LeetCode #1786: Number of Restricted Paths From First to Last Node
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1786: Number of Restricted Paths From First to Last Node
// class Solution {
// private static final int INF = Integer.MAX_VALUE;
// private static final int MOD = (int) 1e9 + 7;
// private List<int[]>[] g;
// private int[] dist;
// private int[] f;
// private int n;
//
// public int countRestrictedPaths(int n, int[][] edges) {
// this.n = n;
// g = new List[n + 1];
// for (int i = 0; i < g.length; ++i) {
// g[i] = new ArrayList<>();
// }
// for (int[] e : edges) {
// int u = e[0], v = e[1], w = e[2];
// g[u].add(new int[] {v, w});
// g[v].add(new int[] {u, w});
// }
// PriorityQueue<int[]> q = new PriorityQueue<>((a, b) -> a[0] - b[0]);
// q.offer(new int[] {0, n});
// dist = new int[n + 1];
// f = new int[n + 1];
// Arrays.fill(dist, INF);
// Arrays.fill(f, -1);
// dist[n] = 0;
// while (!q.isEmpty()) {
// int[] p = q.poll();
// int u = p[1];
// for (int[] ne : g[u]) {
// int v = ne[0], w = ne[1];
// if (dist[v] > dist[u] + w) {
// dist[v] = dist[u] + w;
// q.offer(new int[] {dist[v], v});
// }
// }
// }
// return dfs(1);
// }
//
// private int dfs(int i) {
// if (f[i] != -1) {
// return f[i];
// }
// if (i == n) {
// return 1;
// }
// int ans = 0;
// for (int[] ne : g[i]) {
// int j = ne[0];
// if (dist[i] > dist[j]) {
// ans = (ans + dfs(j)) % MOD;
// }
// }
// f[i] = ans;
// return ans;
// }
// }
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × m)
Space
O(n × m)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.