Path with Maximum Probability (LeetCode 1514): Solution and Explanation
Each edge succeeds with some probability. Find the path from the start node to the end node whose success probability, the product of its edges, is largest.
Intuition
A path succeeds only if every edge on it succeeds, so its probability is the product of the edge probabilities.
Every probability is at most 1, so adding an edge to a path can only keep its value the same or lower it. That is the same shape as shortest paths with non-negative weights, where adding an edge can only make a path longer.
That property is what makes Dijkstra correct. Flip it around: use a max-heap, start the source at 1, and combine with multiplication instead of addition.
When a node is popped with the highest probability in the heap, nothing still waiting can reach it with more, because every other path is already at most that value and only shrinks further. So the first time end_node is popped, its value is the answer.
Approach: Dijkstra with a max-heap
- Build an adjacency list where each undirected edge appears in both endpoints' lists with its probability.
- Set
best[start_node] = 1and push(1, start_node)into a max-heap. - Pop the entry with the largest probability. Return it if the node is
end_node. Skip it if it is older thanbest[node]. - For each neighbour, compute
prob * p. If it is larger than the neighbour's best, store it and push it. - If the heap runs out,
end_nodeis unreachable, so return 0.
Step-by-step example
n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start_node = 0, end_node = 2
- best = [1, 0, 0] and the heap holds (1, 0).
- Pop node 0 at 1. Edge 0-1 gives 0.5, so best[1] = 0.5. Edge 0-2 gives 0.2, so best[2] = 0.2. Both are pushed.
- Pop node 1 at 0.5. Edge 1-2 gives 0.5 * 0.5 = 0.25, which beats 0.2, so best[2] = 0.25 and (0.25, 2) is pushed.
- Pop node 2 at 0.25. It is the end node, so return 0.25. The old (0.2, 2) entry is never needed.
Code: Python, Java, C++
1class Solution:
2 def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start_node: int, end_node: int) -> float:
3 graph = [[] for _ in range(n)]
4 for (a, b), p in zip(edges, succProb):
5 graph[a].append((b, p))
6 graph[b].append((a, p))
7 best = [0.0] * n
8 best[start_node] = 1.0
9 heap = [(-1.0, start_node)]
10 while heap:
11 neg, node = heapq.heappop(heap)
12 prob = -neg
13 if node == end_node:
14 return prob
15 if prob < best[node]:
16 continue
17 for nxt, p in graph[node]:
18 cand = prob * p
19 if cand > best[nxt]:
20 best[nxt] = cand
21 heapq.heappush(heap, (-cand, nxt))
22 return 0.01class Solution {
2 public double maxProbability(int n, int[][] edges, double[] succProb, int start_node, int end_node) {
3 List<List<double[]>> graph = new ArrayList<>();
4 for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
5 for (int i = 0; i < edges.length; i++) {
6 graph.get(edges[i][0]).add(new double[]{edges[i][1], succProb[i]});
7 graph.get(edges[i][1]).add(new double[]{edges[i][0], succProb[i]});
8 }
9 double[] best = new double[n];
10 best[start_node] = 1.0;
11 PriorityQueue<double[]> heap = new PriorityQueue<>((x, y) -> Double.compare(y[0], x[0]));
12 heap.offer(new double[]{1.0, start_node});
13 while (!heap.isEmpty()) {
14 double[] top = heap.poll();
15 double prob = top[0];
16 int node = (int) top[1];
17 if (node == end_node) {
18 return prob;
19 }
20 if (prob < best[node]) continue;
21 for (double[] e : graph.get(node)) {
22 int next = (int) e[0];
23 double cand = prob * e[1];
24 if (cand > best[next]) {
25 best[next] = cand;
26 heap.offer(new double[]{cand, next});
27 }
28 }
29 }
30 return 0.0;
31 }
32}1class Solution {
2public:
3 double maxProbability(int n, vector<vector<int>>& edges, vector<double>& succProb, int start_node, int end_node) {
4 vector<vector<pair<int, double>>> graph(n);
5 for (int i = 0; i < (int)edges.size(); i++) {
6 graph[edges[i][0]].push_back({edges[i][1], succProb[i]});
7 graph[edges[i][1]].push_back({edges[i][0], succProb[i]});
8 }
9 vector<double> best(n, 0.0);
10 best[start_node] = 1.0;
11 priority_queue<pair<double, int>> heap;
12 heap.push({1.0, start_node});
13 while (!heap.empty()) {
14 auto [prob, node] = heap.top();
15 heap.pop();
16 if (node == end_node) {
17 return prob;
18 }
19 if (prob < best[node]) continue;
20 for (auto [next, p] : graph[node]) {
21 double cand = prob * p;
22 if (cand > best[next]) {
23 best[next] = cand;
24 heap.push({cand, next});
25 }
26 }
27 }
28 return 0.0;
29 }
30};Time and space complexity
O((V + E) log V)
Each successful relaxation pushes one heap entry, and each push or pop costs O(log V).
O(V + E)
The adjacency list stores every edge twice, plus the best array and the heap.
Other approaches
Bellman-Ford style relaxation (time O(V * E), space O(V))
Repeat a pass over every edge, updating both endpoints, until nothing changes. Simple and correct, but up to V passes over E edges.
Dijkstra on negative logarithms (time O((V + E) log V), space O(V + E))
Turn each probability into the weight -log(p) and run a standard min-heap Dijkstra on sums. Equivalent, but logs add rounding error and need special care for p = 0.
Common mistakes
- Using a min-heap out of habit. You want the most likely node first.
- Forgetting the edges are undirected. Add each edge to both endpoints.
- Returning
best[end_node]before the search ends. Returning on the first pop ofend_node, or after the heap empties, is correct; returning when it is first pushed is not. - Starting every node at 1 or the start node at 0. The start is 1 and every other node is 0.
Frequently asked questions
Why does Dijkstra work with multiplication?
Dijkstra needs extending a path to never improve it. Multiplying by a number in [0, 1] never increases the product, so the greedy choice of the most likely node is safe.
What about edges with probability 0?
They give a candidate of 0, which never beats the initial 0, so they are effectively ignored.
Why might my answer differ in the last digits?
Floating point products are rounded. Multiplying the same edges in the same order gives the same bits. LeetCode accepts answers within 1e-5 of the expected value.