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^5
  • 0 <= len(edges) <= 2 * 10^5
  • Each channel [u, v, prob] satisfies 0 <= u, v < n and 0.0 <= prob <= 1.0
  • 0 <= start_node, end_node < n
  • Parallel channels and self-loops may appear in edges.
  • Return values within 1e-5 of the true reliability are accepted.

Step-by-step walkthrough

  1. Understand the problem and path reliability

    We have an undirected network of n computers labeled 0 to n - 1. Each edge [u, v, prob] is a two-way link whose transmission succeeds with probability prob (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.30
    

    Two boundary rules come directly from this definition:

    • A 0-edge path from a node to itself (start_node == end_node) succeeds automatically with probability 1.0.
    • If end_node cannot be reached (or every path to it crosses a 0.0 link), return 0.0.
  2. Why plain DFS and plain BFS both fall short

    A depth-first search (DFS) that tries every simple path from start_node to end_node gets the right answer, because visiting a node twice in a cycle only multiplies by extra numbers <= 1.0 and never helps. However, the number of simple paths in a graph can grow exponentially, which is far too slow for n = 10^5 nodes.

    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 node 2 in one hop with 0.30, missing the two-hop path 0 -> 1 -> 2 with 0.48.

  3. 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.0 can 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 standard heapq module implements a min-heap (smallest pops first), so we store negated probabilities (-prob, node): -0.8 is smaller than -0.5, so 0.8 pops before 0.5.

  4. Build the undirected adjacency list

    First, convert the edge list into an adjacency list graph, where graph[u] holds (neighbor, edge_prob) pairs for every link touching u.

    • Add both u -> v and v -> u because 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] and edge[1] with int(...) because edges has type List[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
    
  5. Pop the most reliable frontier node and skip stale entries

    Maintain best_prob[v], the best probability known so far from start_node to v. Initialize best_prob[start_node] = 1.0 and 0.0 everywhere else, and seed max_heap with (-1.0, start_node).

    When we pop (neg_prob, curr_node) from max_heap:

    1. Convert back with curr_prob = -neg_prob.
    2. Early exit: if curr_node == end_node, its reliability is final—return curr_prob immediately! (Notice this also handles start_node == end_node: the very first pop returns 1.0.)
    3. Skip stale entries: because Python's heapq cannot 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 in O(1) time.
  6. Relax neighbor edges with strict `>`

    For each (neighbor, edge_prob) of curr_node, compute candidate_prob = curr_prob * edge_prob. We update best_prob[neighbor] and push to the heap only when candidate_prob > best_prob[neighbor] (strictly greater).

    Why must this check be > instead of >=?

    • Cycles of 1.0 links: In 0 --(1.0)-- 1 --(1.0)-- 2 --(1.0)-- 0, using >= would re-push 1.0 around the cycle forever! With strict >, once a node reaches 1.0, another 1.0 route does not re-push it.
    • Zero-probability links: Because best_prob[neighbor] starts at 0.0, a dead link (edge_prob == 0.0) produces candidate_prob = 0.0, which fails 0.0 > 0.0 and 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 while loop finishes and max_heap is empty, no positive-probability path reached end_node, so we return 0.0.

  7. 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.)
    
  8. 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)) (or O((n + E) log n) on simple graphs). Allocating and filling the adjacency list takes O(n + E) time. Because a node's value is final the first time it pops from the max-heap and stale duplicates hit curr_prob < best_prob[curr_node], each node's adjacency list is scanned at most once, triggering at most 2E edge checks and at most E heap pushes/pops costing O(log(E + 1)) each.
  • Space: O(n + E). The adjacency list stores 2E directed entries across n buckets, best_prob stores n floats, and max_heap holds at most E + 1 entries at any time.

Edge cases

  • start_node == end_node: Immediately pops (-1.0, start_node) on the first iteration and returns 1.0, even if edges is empty or only has a weak self-loop [0, 0, 0.3].
  • Disconnected components or empty edges (with start_node != end_node): The heap empties without popping end_node and returns 0.0.
  • Zero-probability links: curr_prob * 0.0 = 0.0 never satisfies candidate_prob > best_prob[neighbor] (which starts at 0.0), so 0.0 links 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 by p <= 1.0 never beats best_prob[u], so self-loops never push onto the heap.
  • Cycles of 1.0 edges: Strict inequality > prevents equal 1.0 probabilities from being pushed around a cycle endlessly.

Common mistakes

  • Forgetting to negate probabilities in heapq. Python's heapq pops the smallest number first; pushing (prob, node) turns the search into minimum-probability-first and breaks early termination (0.3 would pop before 0.36 in 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; omitting v -> u misses paths that traverse an edge from v to u.
  • Using a dictionary graph[u][v] = prob for neighbors. Overwriting graph[u][v] when building the graph silently discards an earlier, higher-probability parallel edge if a weaker parallel edge appears later in edges.
  • Using >= instead of > during relaxation. On a cycle of 1.0-probability links, >= pushes (1.0, node) forever.

Alternative approaches

  • Log-space shortest path (-log(prob)): Since log(a * b) = log(a) + log(b) and -log(p) >= 0 for p in (0, 1], skipping p == 0 edges and assigning non-negative weight -math.log(p) turns maximum product into standard minimum-sum Dijkstra (exp(-min_dist)). It has the same O(n + E log(E + 1)) complexity and prevents underflow on very long paths, at the cost of slower log/exp calls per edge.
  • Bellman-Ford relaxation: Repeatedly relaxing all E edges n - 1 times (best[v] = max(best[v], best[u] * p)) is simple to code without a heap, but takes O(n * E) worst-case time—too slow for n = 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^-100 links gives 10^-400, causing floating-point underflow (when a positive number becomes smaller than a 64-bit float's minimum positive value of roughly 5 * 10^-324 and rounds down to 0.0, erasing differences between paths). To fix this, skip 0.0-probability edges and replace every positive probability p with a non-negative additive cost -math.log(p), because maximizing a product p_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_cost directly (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] * n alongside best_prob. Whenever relaxing edge curr_node -> neighbor strictly improves best_prob[neighbor], also record parent[neighbor] = curr_node. Once end_node pops from the heap, walk backward via node = parent[node] starting at end_node until -1 and reverse the collected list to produce [start_node, ..., end_node] (or return [] if end_node is 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 with w > 1.0 multiplies the score by w^2 > 1 forever, so the maximum reliability is infinite whenever such an edge lies in the positive-weight connected component connecting start_node and end_node! In a directed graph where walks may repeat nodes, converting positive weights to -log(w) turns w > 1.0 into negative costs, which the Bellman-Ford algorithm (an O(n * E) shortest-path method that relaxes all edges n - 1 times) 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

Similar questions

More Nutanix interview questions

All 2 Nutanix questions →