Leetcode #1976: Number of Ways to Arrive at Destination
In this guide, we solve Leetcode #1976 Number of Ways to Arrive at Destination in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Graph, Topological Sort, Dynamic Programming, Shortest Path
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]
Output: 4
Explanation: The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.
The four ways to get there in 7 minutes are:
- 0 ➝ 6
- 0 ➝ 4 ➝ 6
- 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6
- 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6
Python Solution
class Solution:
def countPaths(self, n: int, roads: List[List[int]]) -> int:
g = [[inf] * n for _ in range(n)]
for u, v, t in roads:
g[u][v] = g[v][u] = t
g[0][0] = 0
dist = [inf] * n
dist[0] = 0
f = [0] * n
f[0] = 1
vis = [False] * n
for _ in range(n):
t = -1
for j in range(n):
if not vis[j] and (t == -1 or dist[j] < dist[t]):
t = j
vis[t] = True
for j in range(n):
if j == t:
continue
ne = dist[t] + g[t][j]
if dist[j] > ne:
dist[j] = ne
f[j] = f[t]
elif dist[j] == ne:
f[j] += f[t]
mod = 10**9 + 7
return f[-1] % mod
Complexity
The time complexity is , and the space complexity is , where is the number of points. The space complexity is , where is the number of points.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.