Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1514: Path with Maximum Probability

In this guide, we solve Leetcode #1514 Path with Maximum Probability in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Graph, Array, Shortest Path, Heap (Priority Queue)

Intuition

We need to repeatedly access the smallest or largest element as the input changes.

A heap provides fast insertions and removals while keeping order.

Approach

Push candidates into the heap as you scan, and pop when you need the best element.

Keep the heap size bounded if the problem requires a top-k structure.

Steps:

  • Push candidates into a heap.
  • Pop the best candidate when needed.
  • Maintain heap size or invariants.

Example

Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 Output: 0.25000 Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.

Python Solution

class Solution: def maxProbability( self, n: int, edges: List[List[int]], succProb: List[float], start_node: int, end_node: int, ) -> float: g: List[List[Tuple[int, float]]] = [[] for _ in range(n)] for (a, b), p in zip(edges, succProb): g[a].append((b, p)) g[b].append((a, p)) pq = [(-1, start_node)] dist = [0] * n dist[start_node] = 1 while pq: w, a = heappop(pq) w = -w if dist[a] > w: continue for b, p in g[a]: if (t := w * p) > dist[b]: dist[b] = t heappush(pq, (-t, b)) return dist[end_node]

Complexity

The time complexity is O(m×log⁡m)O(m \times \log m)O(m×logm), and the space complexity is O(m)O(m)O(m). The space complexity is O(m)O(m)O(m).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy