Maximum End-to-End Path Reliability
Hard · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
An undirected communication topology consists of n endpoints numbered 0 through n - 1. Each element [u, v, prob] in edges describes a two-way channel between endpoints u and v whose independent packet-delivery rate is prob (0.0 <= prob <= 1.0).
Because every hop along a route must succeed independently, the end-to-end reliability of a route equals the product of prob across all traversed channels. A trivial zero-hop route from an endpoint to itself (start_node == end_node) has reliability 1.0.
Implement max_probability(n, edges, start_node, end_node) to compute the highest end-to-end reliability from start_node to end_node. Return 0.0 if end_node cannot be reached. Handle parallel channels between the same pair of endpoints, self-loops, cycles, zero-reliability channels, and disconnected subgraphs.
def max_probability(n: int, edges: List[List[float]], start_node: int, end_node: int) -> float:
Examples
Example 1
Input:
n = 4
edges = [[0, 3, 0.3], [0, 1, 0.8], [1, 3, 0.4], [1, 2, 0.9], [2, 3, 0.5]]
start_node = 0, end_node = 3
Output:
0.36
Walk-through: Direct channel 0 -> 3 gives 0.3, two-hop route 0 -> 1 -> 3 gives 0.8 * 0.4 = 0.32, and three-hop route 0 -> 1 -> 2 -> 3 gives 0.8 * 0.9 * 0.5 = 0.36, which is highest.
Example 2
Input:
n = 4
edges = [[0, 1, 0.75], [2, 3, 0.9]]
start_node = 0, end_node = 3
Output:
0.0
Walk-through: Endpoints {0, 1} and {2, 3} belong to disconnected components, so no route links 0 to 3.
Example 3
Input:
n = 3
edges = [[0, 1, 0.4], [0, 1, 0.8], [1, 2, 0.5]]
start_node = 0, end_node = 2
Output:
0.4
Walk-through: Taking the stronger parallel channel between 0 and 1 (0.8) followed by 1 -> 2 (0.5) yields 0.8 * 0.5 = 0.4.
Constraints
1 <= n <= 10^50 <= len(edges) <= 2 * 10^5- Each channel
[u, v, prob]satisfies0 <= u, v < nand0.0 <= prob <= 1.0 0 <= start_node, end_node < n- Parallel channels and self-loops may appear in
edges. - Return values within
1e-5of the true reliability are accepted.
Step-by-step walkthrough
Understand the problem and path reliability
We have an undirected network of
ncomputers labeled0ton - 1. Each edge[u, v, prob]is a two-way link whose transmission succeeds with probabilityprob(0.0 <= prob <= 1.0).For a packet to cross a multi-hop path, every link along that path must succeed, so the reliability of a path is the product of its edge probabilities:
(0.8) (0.6) 0 --------- 1 --------- 2 Path 0 -> 1 -> 2: 0.8 * 0.6 = 0.48 (winner) \ / \-------(0.3)-------/ Path 0 -> 2: 0.30Two boundary rules come directly from this definition:
- A 0-edge path from a node to itself (
start_node == end_node) succeeds automatically with probability1.0. - If
end_nodecannot be reached (or every path to it crosses a0.0link), return0.0.
- A 0-edge path from a node to itself (
Why plain DFS and plain BFS both fall short
A depth-first search (DFS) that tries every simple path from
start_nodetoend_nodegets the right answer, because visiting a node twice in a cycle only multiplies by extra numbers<= 1.0and never helps. However, the number of simple paths in a graph can grow exponentially, which is far too slow forn = 10^5nodes.A plain breadth-first search (BFS) is fast (
O(n + E)), because it locks in each node the first time it sees it—meaning fewest hops. Unfortunately, fewest hops does not mean highest reliability: in the diagram above, BFS reaches node2in one hop with0.30, missing the two-hop path0 -> 1 -> 2with0.48.Key idea: greedy Dijkstra with a max-heap
Think about why Dijkstra's shortest-path algorithm works when edge lengths are
>= 0: adding another road can never make a trip shorter, so the closest unvisited node on the frontier is guaranteed to have its final shortest distance.Here, the exact same monotonic rule holds in reverse! Every edge probability lies in
[0.0, 1.0], so multiplying a path's probability by another edge can never make that path more reliable:curr_prob * edge_prob <= curr_prob (because 0.0 <= edge_prob <= 1.0)So if we always expand the unexplored node with the highest probability found so far, could a detour through other waiting nodes ever beat it? No—every other waiting node in our queue already has a probability
<= curr_prob, and multiplying by more edges<= 1.0can only shrink it further!To always pop the largest probability in
O(log E)time, we need a max-heap (a priority queue that pops the maximum first). Python's standardheapqmodule implements a min-heap (smallest pops first), so we store negated probabilities(-prob, node):-0.8is smaller than-0.5, so0.8pops before0.5.Build the undirected adjacency list
First, convert the edge list into an adjacency list
graph, wheregraph[u]holds(neighbor, edge_prob)pairs for every link touchingu.- Add both
u -> vandv -> ubecause links are bidirectional. - Keep parallel edges as separate entries in
graph[u]—our search will naturally check all of them and keep the largest product. - Convert
edge[0]andedge[1]withint(...)becauseedgeshas typeList[List[float]].
def build_graph(n: int, edges: List[List[float]]) -> List[List[Tuple[int, float]]]: # graph[u]: list of (neighbor, edge_prob) pairs, e.g. graph[0] = [(3, 0.3), (1, 0.8)]. graph: List[List[Tuple[int, float]]] = [[] for _ in range(n)] for edge in edges: # Cast node IDs with int(...) because edges is typed as List[List[float]]. u = int(edge[0]) v = int(edge[1]) edge_prob = float(edge[2]) # Links are bidirectional, so record both directions; parallel edges stay as separate items. graph[u].append((v, edge_prob)) graph[v].append((u, edge_prob)) return graph- Add both
Pop the most reliable frontier node and skip stale entries
Maintain
best_prob[v], the best probability known so far fromstart_nodetov. Initializebest_prob[start_node] = 1.0and0.0everywhere else, and seedmax_heapwith(-1.0, start_node).When we pop
(neg_prob, curr_node)frommax_heap:- Convert back with
curr_prob = -neg_prob. - Early exit: if
curr_node == end_node, its reliability is final—returncurr_probimmediately! (Notice this also handlesstart_node == end_node: the very first pop returns1.0.) - Skip stale entries: because Python's
heapqcannot update an existing entry's priority in place, finding a better route to a node pushes a second entry onto the heap. When the older, weaker entry eventually pops later,curr_prob < best_prob[curr_node]catches it so we skip it inO(1)time.
- Convert back with
Relax neighbor edges with strict `>`
For each
(neighbor, edge_prob)ofcurr_node, computecandidate_prob = curr_prob * edge_prob. We updatebest_prob[neighbor]and push to the heap only whencandidate_prob > best_prob[neighbor](strictly greater).Why must this check be
>instead of>=?- Cycles of
1.0links: In0 --(1.0)-- 1 --(1.0)-- 2 --(1.0)-- 0, using>=would re-push1.0around the cycle forever! With strict>, once a node reaches1.0, another1.0route does not re-push it. - Zero-probability links: Because
best_prob[neighbor]starts at0.0, a dead link (edge_prob == 0.0) producescandidate_prob = 0.0, which fails0.0 > 0.0and is never pushed.
for neighbor, edge_prob in graph[curr_node]: candidate_prob = curr_prob * edge_prob # Strict '>' is essential: it prevents infinite loops around cycles of 1.0 links # and ignores 0.0-probability links since best_prob[neighbor] starts at 0.0. if candidate_prob > best_prob[neighbor]: best_prob[neighbor] = candidate_prob heapq.heappush(max_heap, (-candidate_prob, neighbor))If the
whileloop finishes andmax_heapis empty, no positive-probability path reachedend_node, so we return0.0.- Cycles of
Trace through Example 1
Let's trace
n = 4,edges = [[0, 3, 0.3], [0, 1, 0.8], [1, 3, 0.4], [1, 2, 0.9], [2, 3, 0.5]],start_node = 0,end_node = 3:Initial state: best_prob = [1.0, 0.0, 0.0, 0.0] max_heap = [(-1.0, 0)] Step 1: Pop (-1.0, 0) -> curr_node = 0, curr_prob = 1.0 - neighbor 3 (edge 0.3): 1.0 * 0.3 = 0.3 > 0.0 -> best_prob[3] = 0.3, push (-0.3, 3) - neighbor 1 (edge 0.8): 1.0 * 0.8 = 0.8 > 0.0 -> best_prob[1] = 0.8, push (-0.8, 1) Step 2: Pop (-0.8, 1) -> curr_node = 1, curr_prob = 0.8 (0.8 pops ahead of 0.3!) - neighbor 3 (edge 0.4): 0.8 * 0.4 = 0.32 > 0.3 -> best_prob[3] = 0.32, push (-0.32, 3) - neighbor 2 (edge 0.9): 0.8 * 0.9 = 0.72 > 0.0 -> best_prob[2] = 0.72, push (-0.72, 2) Step 3: Pop (-0.72, 2) -> curr_node = 2, curr_prob = 0.72 (0.72 pops ahead of 0.32!) - neighbor 3 (edge 0.5): 0.72 * 0.5 = 0.36 > 0.32 -> best_prob[3] = 0.36, push (-0.36, 3) Step 4: Pop (-0.36, 3) -> curr_node = 3, curr_prob = 0.36 - curr_node == end_node (3) -> return 0.36! (Stale entries (-0.32, 3) and (-0.3, 3) remain in the heap and never need to be popped.)Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import heapq def build_graph(n: int, edges: List[List[float]]) -> List[List[Tuple[int, float]]]: # graph[u]: list of (neighbor, edge_prob) pairs, e.g. graph[0] = [(3, 0.3), (1, 0.8)]. graph: List[List[Tuple[int, float]]] = [[] for _ in range(n)] for edge in edges: # Cast node IDs with int(...) because edges is typed as List[List[float]]. u = int(edge[0]) v = int(edge[1]) edge_prob = float(edge[2]) # Links are bidirectional, so record both directions; parallel edges stay as separate items. graph[u].append((v, edge_prob)) graph[v].append((u, edge_prob)) return graph def max_probability(n: int, edges: List[List[float]], start_node: int, end_node: int) -> float: graph = build_graph(n, edges) # best_prob[v] stores the highest end-to-end probability known so far from start_node to v. # Reaching start_node uses 0 edges, so its reliability starts at 1.0. best_prob: List[float] = [0.0] * n best_prob[start_node] = 1.0 # max_heap stores (-probability, node) so Python's min-heap pops the highest probability first. max_heap: List[Tuple[float, int]] = [(-1.0, start_node)] while max_heap: neg_prob, curr_node = heapq.heappop(max_heap) curr_prob = -neg_prob # Because every edge probability is in [0.0, 1.0], extending any remaining path in the # heap can never increase its probability, so the first time end_node pops is optimal. if curr_node == end_node: return curr_prob # Skip stale heap entries left behind when a better route to curr_node was pushed later. if curr_prob < best_prob[curr_node]: continue # Phase 2: try extending the path from curr_node across each incident link. for neighbor, edge_prob in graph[curr_node]: candidate_prob = curr_prob * edge_prob # Strict '>' is essential: it prevents infinite loops around cycles of 1.0 links # and ignores 0.0-probability links since best_prob[neighbor] starts at 0.0. if candidate_prob > best_prob[neighbor]: best_prob[neighbor] = candidate_prob heapq.heappush(max_heap, (-candidate_prob, neighbor)) # The heap emptied without ever reaching end_node with positive probability. return 0.0✅ Submit now — all tests should pass.
Intuition & how it works
Picture sending water through a network of leaky pipes, where an 0.8 pipe delivers 80% of the water entering it and a second 0.5 pipe delivers half of what arrives (0.8 * 0.5 = 0.40). Because every pipe delivers at most 100% (0.0 <= prob <= 1.0), adding more pipes to a route can only keep the flow the same or shrink it—never boost it. That exact property lets us adapt Dijkstra's algorithm (a greedy graph search that repeatedly finalizes the best frontier node when extending a path can never improve its score): we store the network in an adjacency list (per-node lists of (neighbor, probability) pairs) and expand nodes using a max-heap (a priority queue that always pops the largest probability first, built from Python's min-heap heapq by negating probabilities).
Searching every simple path with depth-first search fails because the number of paths grows exponentially with n, timing out completely on 10^5 nodes. On the other hand, plain breadth-first search locks in a node the first time it is reached (fewest edges), which fails whenever a multi-hop route of reliable links beats a single unreliable shortcut. Trying to update every edge repeatedly across n - 1 passes also takes O(n * E) time, which is tens of billions of steps for n = 10^5 and E = 2 * 10^5.
Let's see how the max-heap search solves Example 1 (edges = [[0, 3, 0.3], [0, 1, 0.8], [1, 3, 0.4], [1, 2, 0.9], [2, 3, 0.5]]) from 0 to 3 via edge relaxation (checking whether going through the current node improves a neighbor's best known score):
Start: best_prob = [1.0, 0.0, 0.0, 0.0], heap = [(1.0, node 0)]
Pop (1.0, 0): relax 0->3 to 0.3, 0->1 to 0.8
Pop (0.8, 1): relax 1->3 to 0.32 > 0.3, 1->2 to 0.72
Pop (0.72, 2): relax 2->3 to 0.36 > 0.32
Pop (0.36, 3): target popped first -> return 0.36
Because 0.8 and 0.72 popped before 0.3 and 0.32, nodes 1 and 2 upgraded node 3 to 0.36 before node 3 was finalized.
Complexity
Let n be the number of nodes and E be the number of edges.
- Time:
O(n + E log(E + 1))(orO((n + E) log n)on simple graphs). Allocating and filling the adjacency list takesO(n + E)time. Because a node's value is final the first time it pops from the max-heap and stale duplicates hitcurr_prob < best_prob[curr_node], each node's adjacency list is scanned at most once, triggering at most2Eedge checks and at mostEheap pushes/pops costingO(log(E + 1))each. - Space:
O(n + E). The adjacency list stores2Edirected entries acrossnbuckets,best_probstoresnfloats, andmax_heapholds at mostE + 1entries at any time.
Edge cases
start_node == end_node: Immediately pops(-1.0, start_node)on the first iteration and returns1.0, even ifedgesis empty or only has a weak self-loop[0, 0, 0.3].- Disconnected components or empty
edges(withstart_node != end_node): The heap empties without poppingend_nodeand returns0.0. - Zero-probability links:
curr_prob * 0.0 = 0.0never satisfiescandidate_prob > best_prob[neighbor](which starts at0.0), so0.0links are safely ignored while positive detours still succeed. - Parallel edges: Keeping all parallel edges in
graph[u]lets the largest probability win naturally during relaxation. - Self-loops (
[u, u, p]): Multiplying byp <= 1.0never beatsbest_prob[u], so self-loops never push onto the heap. - Cycles of
1.0edges: Strict inequality>prevents equal1.0probabilities from being pushed around a cycle endlessly.
Common mistakes
- Forgetting to negate probabilities in
heapq. Python'sheapqpops the smallest number first; pushing(prob, node)turns the search into minimum-probability-first and breaks early termination (0.3would pop before0.36in Example 1). - Marking nodes visited when pushing instead of when popping. Locking a node on first sight mimics BFS and misses better multi-hop paths discovered later.
- Adding only one direction
graph[u].append((v, prob)). Network links are undirected; omittingv -> umisses paths that traverse an edge fromvtou. - Using a dictionary
graph[u][v] = probfor neighbors. Overwritinggraph[u][v]when building the graph silently discards an earlier, higher-probability parallel edge if a weaker parallel edge appears later inedges. - Using
>=instead of>during relaxation. On a cycle of1.0-probability links,>=pushes(1.0, node)forever.
Alternative approaches
- Log-space shortest path (
-log(prob)): Sincelog(a * b) = log(a) + log(b)and-log(p) >= 0forpin(0, 1], skippingp == 0edges and assigning non-negative weight-math.log(p)turns maximum product into standard minimum-sum Dijkstra (exp(-min_dist)). It has the sameO(n + E log(E + 1))complexity and prevents underflow on very long paths, at the cost of slowerlog/expcalls per edge. - Bellman-Ford relaxation: Repeatedly relaxing all
Eedgesn - 1times (best[v] = max(best[v], best[u] * p)) is simple to code without a heap, but takesO(n * E)worst-case time—too slow forn = 10^5.
Follow-up questions
- If link probabilities can be as tiny as 10^-100 so multiplying several hops underflows 64-bit floats to 0.0, how would you reformulate the search? Multiplying four
10^-100links gives10^-400, causing floating-point underflow (when a positive number becomes smaller than a 64-bit float's minimum positive value of roughly5 * 10^-324and rounds down to0.0, erasing differences between paths). To fix this, skip0.0-probability edges and replace every positive probabilitypwith a non-negative additive cost-math.log(p), because maximizing a productp_1 * p_2 * ...is mathematically identical to minimizing the sum-log(p_1) + -log(p_2) + .... Run standard min-heap Dijkstra on those additive costs and return the optimal log-probability-min_costdirectly (only exponentiating if the final value is large enough not to underflow). - What extra state would you record if the caller needed the exact sequence of vertices along the most reliable route rather than just its probability? Maintain an array
parent = [-1] * nalongsidebest_prob. Whenever relaxing edgecurr_node -> neighborstrictly improvesbest_prob[neighbor], also recordparent[neighbor] = curr_node. Onceend_nodepops from the heap, walk backward vianode = parent[node]starting atend_nodeuntil-1and reverse the collected list to produce[start_node, ..., end_node](or return[]ifend_nodeis never reached). - Suppose edge multipliers could exceed 1.0—why does greedy max-heap finalization break down, and how would you solve or detect unbounded paths instead? Greedy early finalization breaks because a currently weaker path could later cross an amplifying edge (
w > 1.0) and overtake a node we already popped and froze. In an undirected graph where repeated edges are allowed, bouncing back and forth across a single edge withw > 1.0multiplies the score byw^2 > 1forever, so the maximum reliability is infinite whenever such an edge lies in the positive-weight connected component connectingstart_nodeandend_node! In a directed graph where walks may repeat nodes, converting positive weights to-log(w)turnsw > 1.0into negative costs, which the Bellman-Ford algorithm (anO(n * E)shortest-path method that relaxes all edgesn - 1times) solves while detecting reachable positive-gain cycles (product > 1); if simple paths without repeated nodes are required, the problem is NP-hard (generalizing Longest Simple Path).
Follow-up questions
- If link probabilities can be as tiny as 10^-100 so multiplying several hops underflows 64-bit floats to 0.0, how would you reformulate the search?
- What extra state would you record if the caller needed the exact sequence of vertices along the most reliable route rather than just its probability?
- Suppose edge multipliers could exceed 1.0—why does greedy max-heap finalization break down, and how would you solve or detect unbounded paths instead?
Similar questions
- Earliest Peak Concurrent RAM Window
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One