Path with Maximum Probability (LeetCode 1514): Solution and Explanation

Medium
Array
Graph
Heap Priority Queue
Shortest Path

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

  1. Build an adjacency list where each undirected edge appears in both endpoints' lists with its probability.
  2. Set best[start_node] = 1 and push (1, start_node) into a max-heap.
  3. Pop the entry with the largest probability. Return it if the node is end_node. Skip it if it is older than best[node].
  4. For each neighbour, compute prob * p. If it is larger than the neighbour's best, store it and push it.
  5. If the heap runs out, end_node is 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
  1. best = [1, 0, 0] and the heap holds (1, 0).
  2. 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.
  3. 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.
  4. 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.0
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O((V + E) log V)

Each successful relaxation pushes one heap entry, and each push or pop costs O(log V).

Space

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 of end_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.