#1514

Path with Maximum Probability

Medium
ArrayGraph TheoryHeap (Priority Queue)Shortest PathGraph TraversalPriority QueueDijkstra's Algorithm
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(E log V)
Space
O(1)
O(V)
💡

Intuition

Time O(E log V)Space O(V)

The optimal solution uses a priority queue (max-heap) to explore the graph, similar to Dijkstra's algorithm, but instead of minimizing distances, we maximize probabilities. This approach is efficient and handles larger graphs well.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a graph representation using an adjacency list.
  2. 2Step 2: Use a max-heap to explore nodes, starting from the start node with a probability of 1.
  3. 3Step 3: For each node, update the maximum probability for its neighbors and push them into the heap if a higher probability path is found.
solution.py26 lines
1# Full working Python code
2import heapq
3from collections import defaultdict
4
5def maxProbability(n, edges, succProb, start, end):
6    graph = defaultdict(list)
7    for (a, b), prob in zip(edges, succProb):
8        graph[a].append((b, prob))
9        graph[b].append((a, prob))
10
11    max_prob = [0] * n
12    max_prob[start] = 1.0
13    heap = [(-1.0, start)]  # max-heap (using negative for max)
14
15    while heap:
16        prob, node = heapq.heappop(heap)
17        prob = -prob  # revert back to positive
18        if node == end:
19            return prob
20        for neighbor, edge_prob in graph[node]:
21            new_prob = prob * edge_prob
22            if new_prob > max_prob[neighbor]:
23                max_prob[neighbor] = new_prob
24                heapq.heappush(heap, (-new_prob, neighbor))
25
26    return 0.0

Complexity note: The time complexity is O(E log V) because we process each edge and use a priority queue to manage the nodes, where E is the number of edges and V is the number of vertices. The space complexity is O(V) due to the storage of the graph and the max probabilities.

  • 1Understanding how to represent graphs is crucial.
  • 2Using priority queues can significantly optimize pathfinding problems.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.