Path with Maximum Probability solution explained

Path with Maximum Probability gives you an undirected graph where each edge has a chance of success between 0 and 1, and asks for the highest chance of getting from a start node to an end node, multiplying the chances along the route; return 0 if the end cannot be reached. Run Dijkstra's algorithm with a max-heap, multiplying instead of adding. Because multiplying by a number no larger than 1 never makes a chance bigger, the greedy order is safe, and the search runs in O(E log V).

By Published 9 min read

The problem in plain terms

There are n nodes numbered from 0. Each undirected edge joins two nodes and comes with a number between 0 and 1: the chance that crossing it succeeds. A route succeeds only if every edge on it succeeds, so its chance is the product of its edges' chances. Given a start and an end node, return the largest chance any route can have, or 0 if no route exists.

edge   chance
0 - 1   0.9
1 - 4   0.5
0 - 2   0.8
2 - 3   0.9
3 - 4   0.9
0 - 4   0.6

start = 0, end = 4  ->  0.648
Five nodes and six edges, made up for this page.

The direct edge from 0 to 4 has a chance of 0.6. Going through 1 gives 0.9 × 0.5 = 0.45. The longest route, 0 to 2 to 3 to 4, gives 0.8 × 0.9 × 0.9 = 0.648, which is the best. More edges can still mean a better chance if each edge is reliable enough.

What the interviewer is checking

This is a test of whether you understand why Dijkstra works, not just how to type it. Interviewers listen for you to say what property the cost needs (it must never improve as a route gets longer) and to check that multiplying by values in [0, 1] has it. They also watch for the heap direction, the handling of outdated heap entries, and the unreachable case. Mentioning the logarithm trick shows you can map an unfamiliar cost back onto a familiar algorithm.

A simpler start: relax every edge in rounds

Keep a best-known chance for each node, 1 for the start and 0 elsewhere. In each round, look at every edge in both directions and improve a node's chance if the other end times the edge chance beats it. A best route never repeats a node, so it uses at most n - 1 edges, and n - 1 rounds are enough. This is the Bellman-Ford idea. It is short and hard to get wrong, but it costs O(V · E), which is slow on large graphs. Stopping early when a round changes nothing helps in practice.

def max_probability_rounds(n, edges, chances, start, end):
    best = [0.0] * n
    best[start] = 1.0
    for _ in range(n - 1):  # a best route uses at most n - 1 edges
        changed = False
        for (a, b), p in zip(edges, chances):
            if best[a] * p > best[b]:
                best[b] = best[a] * p
                changed = True
            if best[b] * p > best[a]:
                best[a] = best[b] * p
                changed = True
        if not changed:
            break
    return best[end]
Python: relaxation rounds, O(V · E).

Dijkstra with a max-heap

Build an adjacency list. Put the start in a heap with chance 1. Repeatedly take the node with the highest chance from the heap; if it is the end, return that chance. Otherwise try each neighbor: if the current chance times the edge chance beats the neighbor's best, record it and push the neighbor. Entries that were beaten after they were pushed are skipped when they come out. The first time the end node is popped, no other route can beat it, because every route still in the heap already has a lower or equal chance and can only fall further.

import heapq

def max_probability(n, edges, chances, start, end):
    links = [[] for _ in range(n)]
    for (a, b), p in zip(edges, chances):
        links[a].append((b, p))
        links[b].append((a, p))
    best = [0.0] * n
    best[start] = 1.0
    heap = [(-1.0, start)]  # heapq is a min-heap, so store negatives
    while heap:
        neg, node = heapq.heappop(heap)
        chance = -neg
        if node == end:
            return chance
        if chance < best[node]:
            continue  # stale entry
        for nxt, p in links[node]:
            if chance * p > best[nxt]:
                best[nxt] = chance * p
                heapq.heappush(heap, (-best[nxt], nxt))
    return 0.0
Python: heapq is a min-heap, so chances are stored negated.
// Binary heap that keeps the largest [chance, node] on top.
class MaxHeap {
  constructor() { this.a = []; }
  get size() { return this.a.length; }
  push(item) {
    const a = this.a;
    a.push(item);
    for (let i = a.length - 1; i > 0;) {
      const p = (i - 1) >> 1;
      if (a[p][0] >= a[i][0]) break;
      [a[p], a[i]] = [a[i], a[p]];
      i = p;
    }
  }
  pop() {
    const a = this.a;
    const top = a[0];
    const last = a.pop();
    if (a.length > 0) {
      a[0] = last;
      for (let i = 0; ;) {
        const l = 2 * i + 1, r = l + 1;
        let m = i;
        if (l < a.length && a[l][0] > a[m][0]) m = l;
        if (r < a.length && a[r][0] > a[m][0]) m = r;
        if (m === i) break;
        [a[m], a[i]] = [a[i], a[m]];
        i = m;
      }
    }
    return top;
  }
}

function maxProbability(n, edges, chances, start, end) {
  const links = Array.from({ length: n }, () => []);
  edges.forEach(([a, b], i) => {
    links[a].push([b, chances[i]]);
    links[b].push([a, chances[i]]);
  });
  const best = new Array(n).fill(0);
  best[start] = 1;
  const heap = new MaxHeap();
  heap.push([1, start]);
  while (heap.size > 0) {
    const [chance, node] = heap.pop();
    if (node === end) return chance;
    if (chance < best[node]) continue; // superseded entry
    for (const [next, p] of links[node]) {
      if (chance * p > best[next]) {
        best[next] = chance * p;
        heap.push([best[next], next]);
      }
    }
  }
  return 0;
}
JavaScript: a binary heap that keeps the largest chance on top.

Heap order on the example

Node 0 comes off first with 1.0 and sets node 1 to 0.9, node 2 to 0.8 and node 4 to 0.6. Node 1 comes off next, but 0.9 × 0.5 = 0.45 does not beat 0.6 for node 4. Node 2 comes off and sets node 3 to 0.72. Node 3 comes off and improves node 4 to 0.648, pushing a new entry. That entry is now the largest in the heap, so node 4 is popped with 0.648 and returned. The older 0.6 entry for node 4 is never used.

The logarithm view gives the same answer: the log of a product is the sum of logs, and -log(p) is zero or positive for p between 0 and 1. Maximizing the product is minimizing the sum of -log(p), which is ordinary Dijkstra with non-negative weights. Edges with chance 0 become infinitely long and can simply be dropped. In code the direct multiplication is usually clearer, and the log form is better kept as the explanation.

Complexity

V nodes, E edges
ApproachTimeExtra space
Every simple routeExponentialO(V) for the recursion
Relaxation rounds (Bellman-Ford)O(V · E)O(V)
Dijkstra with a binary heapO(E log V), up to O(E log E) with duplicate entriesO(V + E)
V nodes, E edges. Scroll sideways on a small screen.

Edge cases

  • No route between start and end: return 0.
  • An edge with chance 0: it can never help, and the code never improves a node through it.
  • Edges with chance 1: products stay at 1, and ties are fine.
  • Two edges between the same pair: both are in the adjacency list, and the better one wins.
  • Very long routes with small chances: products can get tiny; floating-point results are compared with a tolerance in tests.

Mistakes that sink the solution

  • Using a min-heap without negating, which explores the least likely routes first.
  • Adding chances instead of multiplying them.
  • Breadth-first search by number of edges, which picks the 0.6 direct edge in the example.
  • Adding each edge in one direction only, although the graph is undirected.
  • Returning -1 for an unreachable end when the task asks for 0.

Follow-up questions

  • Return the route, not just the chance. Keep a parent for each node when you improve it and walk back from the end.
  • Some edges can make the chance go up (values above 1). The greedy argument breaks; you need relaxation rounds and a check for cycles that keep improving.
  • Many queries from the same start. Run Dijkstra once without stopping at the end and keep the best array.
  • Directed edges. Add each edge in one direction only; nothing else changes.

How to explain it

Fictional example

Justifying the greedy choice in a mock interview
Candidate
A route's chance is a product of numbers between 0 and 1, so making a route longer can only keep its chance the same or lower it. That is the same property Dijkstra needs from non-negative edge weights.
Candidate
So I use a max-heap: always expand the node with the best known chance, multiply through each edge, and push neighbors that improve. Outdated heap entries are skipped.
Candidate
When the end node is popped its chance is final. Unreachable means the heap empties first, and I return 0. It is O(E log V).

Path With Minimum Effort changes Dijkstra's combine step to a maximum. Find the City With the Smallest Number of Neighbors needs shortest distances between all pairs, and Bus Routes shows the unweighted case where plain waves are enough. More on the coding problems hub.

Practicing Dijkstra variants with Natively

The hard part of this problem is the argument, so it pays to say it out loud. In a practice session on Mac or Windows, Natively can read the graph from a screenshot, step through heap pops with you, and suggest code if you want a second version to compare. The session transcript is kept, so you can check afterward whether you explained why multiplying by chances keeps Dijkstra correct before writing a line. See the AI interview assistant page for details.

Questions people ask

How do you solve Path with Maximum Probability?

Run Dijkstra's algorithm with a max-heap: start at 1 for the start node, multiply by each edge's chance, push neighbors that improve, and return the chance when the end node is popped. Return 0 if it is never reached.

Why does Dijkstra work for Path with Maximum Probability?

Chances are between 0 and 1, so multiplying by another edge can only keep a route's chance the same or lower it. That is the property Dijkstra needs.

How does the log trick relate to Path with Maximum Probability?

Maximizing a product of chances is the same as minimizing the sum of -log(chance), which is non-negative, so it becomes ordinary shortest-path Dijkstra.

What is the time complexity of Path with Maximum Probability?

O(E log V) with a binary heap, compared with O(V · E) for relaxation rounds.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP