Path with Maximum Probability - Leetcode 1514 - Python

NeetCodeIO · Intermediate ·⚡ Algorithms & Data Structures ·3y ago

Key Takeaways

The video demonstrates how to find the path with maximum probability in an undirected weighted graph using Dijkstra's algorithm and a priority queue, implemented in Python.

Full Transcript

hey everyone welcome back and let's write some more neat code today so today let's solve the problem path with maximum probability we are given an undirected weighted graph of nodes which is of course represented with a list of edges they are undirected so we can go in either direction but the weight itself actually represents a probability in this case we're also given a starting node and an ending node in this case 0 is our starting node two is the ending node we want to find the path with the maximum probability of success going from zero and ending at two if no path exists then we return 0 if the path does exist we return the probability of success along that path the first thing you might want to try is a Brute Force solution why not just calculate everything single possible path from zero to the ending node among all of those paths we pick the one that has the max probability and then return the probability that's definitely a valid way to do this but it's not very efficient doing a rough time complexity analysis it's sort of going to be a backtracking approach doing it this way where every time we visit a node we're going to have a bunch of choices the total number of choices could be the total number of edges that we have in the graph let's say that's e we're going to keep going along a path let's assume that these are like particular paths that we're going to try to enumerate we're going to try to get every possible path in the graph so the length of a path is going to be V where V is the number of nodes in the graph now this is definitely an upper bound but it shows you that this is going to be exponential time complexity that's the important part roughly I think this is going to be e to the power of V though in most cases it's going to be much smaller than this but still this is going to be an exponential time complexity function but there is a better way and the hint to figuring that out is that the weights in this case are always going to be a value between 0 and 1. so as we travel along a path let's assume we go here and then we go here our total probability is never going to increase we started here with 0.5 are we ever going to find a number along this path that we can multiply this by that's going to increase this value no we're never going to because the value is between 0 to 1. the value is either going to stay the same or get smaller and that just has to do with the way probabilities are calculated for example if we have a probability of successfully traveling across this with 0.5 like a 50 probability and then we want to go here right after we we do that how do we find the total probability well this is just high school math we take these two and multiply them together and the value gets smaller instead of getting bigger so 50 times 50 is actually 25 that's the chance of success going along this path but notice how that's bigger than the other possibility which is to go in this Direction that's only a 20 chance which is 0.2 so what I'm getting at is that we can be greedy in this case when we start at zero we know which side would we rather go would we rather go this direction or this direction well we don't know for sure which path is going to lead us to a higher probability but we know we should probably try this path first because it has a higher probability 50 we know this 20 is never going to get higher but this 50 might get lower maybe it'll end at 25 percent like we saw but that's still going to be higher than this 20 so we can be greedy what's a good greedy algorithm we could run on this well it's a pretty famous shortest path algorithm it's called dixtra's algorithm we are going to use it instead of finding the shortest path we're going to find the maximum probability it's going to be very similar except instead of trying to minimize the distance we're going to try to maximize the probability I'll briefly go over how it's going to run in our case basically we're going to have a heap in our case it's actually going to need to be a Max Heap because we're trying to maximize the probability we're going to start at the source node 0. we're going to add its two neighbors here we know that one neighbor is the node one the probability of going along that path is going to be 20 we have a second neighbor 2 or actually that was two two is the neighbor here sorry if this is a little bit unreadable and we have another neighbor one over here and to travel to that node we have a 50 probability Dexter's algorithm is greedy so in this Max Heap we're gonna pop the value with the highest probability so the key that we're going to use in this case is going to be the probability one quick note in Python there aren't Max heaps by default there's only Min heaps so we can get around that by taking these weights and multiplying them to be negatives notice which one of these is smaller negative 0.5 is smaller than negative 0.2 so we would end up popping this first that's just something we have to do in Python unfortunately so in this case we're going to end up popping this guy we're trying to be greedy so then we're going to end up visiting Node 1 over here and now we're going to add its neighbors to the Heap as well in this case we're adding this node to twice to the Heap the second time we add it we want to know the probability of getting to this node traveling along this path which is going to be 0.5 the probability to reach 1 in the first place multiplied by the probability ability to reach 2 which is going to be 0.25 so we have this node here on the max Heap twice but the key is going to be the probability that's what we're going to use to figure out which one of them is the maximum and now we're going to pop one more time the maximum probability which is this so we pop it and we see we have reached the destination remember the ending goal in this case was the node two we've reached it and the first time we reach it we know that this is the maximum probability that we could possibly get which is 0.25 so that's what we would return in this case and this is more efficient in the worst case we're gonna have to visit every single node once like we're gonna have to pop from the max Heap once we might end up adding the same node multiple times but that's okay the max number of times we might add a node to the Heap is going to be V squared or at least that's the max size our Heap could be so V is the number of vertices V squared is much bigger than that but every time we pop from the Heap it's going to be log of the size of the heat now if you remember from math which you probably don't you probably don't necessarily need to but log V squared is actually we can take this value and put it over here it's actually 2 times log V and we know we don't care about constants so this is not a big deal popping from this is going to be log V we're going to have to do it in the worst case for every Edge in the graph which e is how we represent that but e is bounded by V squared so you can write this however you want a lot of people write dixtra's time complexity to be e Times log V I think V squared is also correct but this is just an upper bound this is probably the most precise way that people write it but clearly this is better than an exponential time complexity okay now let's code it up so the first thing I'm going to quickly skip is just building our adjacency list this isn't something super fancy you usually have to do it for graph problems where we're just given a list of edges so in Python I'm creating a map where the default value is going to be an empty list then we're going to go through every Edge in the input we're going to get the source node and the destination node though it doesn't really matter because these nodes are undirected but I'm going to say for this Source node I want to append to its list of neighbors the destination node we also want to be able to keep track of the probability for every single edge so we add two values we add the destination node and the probability of reaching that node and vice versa we take the destination node and append to it the source node and the probability of reaching that Source node this default dict and setting it to a list here just means that if we use a key like this source and we try to append to it before we even inserted a list in the first place this won't throw an error it'll just automatically initialize this to an empty list so that we can append to it so this just removes the need for us to add an extra if statement here now for dixtra's algorithm we are going to initialize a priority queue in Python that's just an array and we're going to have a pair of values actually the key I'm going to set to be negative one the reason it's negative is because in Python this is going to be a Min Heap but we can simulate it to be a Max Heat by using negative key values and the reason it's one is because we initially just want to assume our probability is one because when we calculate the probability we're just going to start multiplying the real probabilities one is a neutral value it won't mess up the calculation if we set it to zero then that would be bad because anytime we multiply a probability by zero it's still going to be zero that's not going to give us the right answer but 1 is a neutral value that we can use it won't mess up our calculation the starting node of course is going to be a parameter start that's passed in up above and that's what's going to be the only node in our priority queue initially we don't want to end up visiting the same node twice ISO we're going to have a hash set to not do that technically it's possible we could pop the same node from the Heap queue multiple times but then we won't end up adding any of its neighbors while the priority queue is non-empty we're gonna pop from it we're gonna pop two values of probability and the current node and to pop from them in Heap in Python we can just say Heap Q dot Heap pop from the priority queue this is our pair of values as soon as we pop we want to mark that node as being visited so that we don't visit it multiple times we also want to check have we already reached the destination if we have then we can go ahead and return the probability it takes to reach that node which is what we added to the Min Heap and what we popped from them and Heap up above but remember it was a negative value that's what we're going to be adding to the heaps to make it positive we're going to just multiply it by negative one before we return it though if we don't find the ending node then we want to go through all the neighbors of the current node and add them to the Heap so we're going to say neighbor and Edge probability in the adjacency list of the current node remember we added pairs of values so we're going to be popping those pairs the first value was the node the second value was the probability that's what we have here and this probability was just the edge probability for just a single edge what we're going to say now is as long as this neighbor has not already been visited then we can push it to the Heap queue even if it's already been pushed to the Heap because maybe this is a shorter path or AKA a more maximum probability to reach that node we're going to say to the Heap Q push this pair of values first of all we want to add the probability we know that's the first value that's going to go in our Heap because that's going to be used as the key value for the Heap how do we calculate the probability of reaching this neighbor going through this current node well the probability to reach that current node was this probability so prob multiplied by the probability of traversing The Edge which luckily we have right here times Edge prob and that's going to be the probability now the second value we also want to make sure to add the node itself because we want to be able to pop that as well so we're going to say neighbor so this is the pair of values we're pushing to the Heap this is what's going to be used as the key that is actually the entire code if we do find a solution we're going to return it right here and this is actually always going to be negative because we started with a negative 1 here and Edge prob is always going to be positive because we never multiplied those edges by negative one when we actually added them and those were all positive values that we were passed in every time we append or push to the Heap the probability is always going to be negative if we never find a solution we have to make sure to return 0 outside of the loop now let's run the code to make sure that it works and as you can see yes it does and it's pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neatco.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon

Original Description

🚀 https://neetcode.io/ - A better way to prepare for Coding Interviews 🥷 Discord: https://discord.gg/ddjKRXPqtk 🐦 Twitter: https://twitter.com/neetcode1 🐮 Support the channel: https://www.patreon.com/NEETcode ⭐ BLIND-75 PLAYLIST: https://www.youtube.com/watch?v=KLlXCFG5TnA&list=PLot-Xpze53ldVwtstag2TL4HQhAnC8ATf 💡 DYNAMIC PROGRAMMING PLAYLIST: https://www.youtube.com/watch?v=73r3KWiEvyk&list=PLot-Xpze53lcvx_tjrr_m2lgD2NsRHlNO&index=1 Problem Link: https://leetcode.com/problems/path-with-maximum-probability/ 0:00 - Read the problem 1:20 - Drawing Explanation 7:45 - Coding Explanation leetcode 1514 #neetcode #leetcode #python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeetCodeIO · NeetCodeIO · 27 of 60

1 Leetcode 149 - Maximum Points on a Line - Python
Leetcode 149 - Maximum Points on a Line - Python
NeetCodeIO
2 Design Linked List - Leetcode 707 - Python
Design Linked List - Leetcode 707 - Python
NeetCodeIO
3 Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
NeetCodeIO
4 Design Browser History - Leetcode 1472 - Python
Design Browser History - Leetcode 1472 - Python
NeetCodeIO
5 Number of Good Paths - Leetcode 2421 - Python
Number of Good Paths - Leetcode 2421 - Python
NeetCodeIO
6 Flip String to Monotone Increasing - Leetcode 926 - Python
Flip String to Monotone Increasing - Leetcode 926 - Python
NeetCodeIO
7 Maximum Sum Circular Subarray - Leetcode 918 - Python
Maximum Sum Circular Subarray - Leetcode 918 - Python
NeetCodeIO
8 Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
NeetCodeIO
9 Concatenated Words - Leetcode 472 - Python
Concatenated Words - Leetcode 472 - Python
NeetCodeIO
10 Data Stream as Disjoint Intervals - Leetcode 352 - Python
Data Stream as Disjoint Intervals - Leetcode 352 - Python
NeetCodeIO
11 LFU Cache - Leetcode 460 - Python
LFU Cache - Leetcode 460 - Python
NeetCodeIO
12 N-th Tribonacci Number - Leetcode 1137
N-th Tribonacci Number - Leetcode 1137
NeetCodeIO
13 Best Team with no Conflicts - Leetcode 1626 - Python
Best Team with no Conflicts - Leetcode 1626 - Python
NeetCodeIO
14 Greatest Common Divisor of Strings - Leetcode 1071 - Python
Greatest Common Divisor of Strings - Leetcode 1071 - Python
NeetCodeIO
15 Shortest Path in a Binary Matrix - Leetcode 1091 - Python
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
NeetCodeIO
16 Insert into a Binary Search Tree - Leetcode 701 - Python
Insert into a Binary Search Tree - Leetcode 701 - Python
NeetCodeIO
17 Delete Node in a BST - Leetcode 450 - Python
Delete Node in a BST - Leetcode 450 - Python
NeetCodeIO
18 Shuffle the Array (Constant Space) - Leetcode 1470 - Python
Shuffle the Array (Constant Space) - Leetcode 1470 - Python
NeetCodeIO
19 Fruits into Basket - Leetcode 904 - Python
Fruits into Basket - Leetcode 904 - Python
NeetCodeIO
20 Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
NeetCodeIO
21 Naming a Company - Leetcode 2306 - Python
Naming a Company - Leetcode 2306 - Python
NeetCodeIO
22 As Far from Land as Possible - Leetcode 1162 - Python
As Far from Land as Possible - Leetcode 1162 - Python
NeetCodeIO
23 Shortest Path with Alternating Colors - Leetcode 1129 - Python
Shortest Path with Alternating Colors - Leetcode 1129 - Python
NeetCodeIO
24 Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
NeetCodeIO
25 Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
NeetCodeIO
26 Contains Duplicate II - Leetcode 219 - Python
Contains Duplicate II - Leetcode 219 - Python
NeetCodeIO
Path with Maximum Probability - Leetcode 1514 - Python
Path with Maximum Probability - Leetcode 1514 - Python
NeetCodeIO
28 Add to Array-Form of Integer - Leetcode 989 - Python
Add to Array-Form of Integer - Leetcode 989 - Python
NeetCodeIO
29 Unique Paths II - Leetcode 63 - Python
Unique Paths II - Leetcode 63 - Python
NeetCodeIO
30 Minimum Distance between BST Nodes - Leetcode 783 - Python
Minimum Distance between BST Nodes - Leetcode 783 - Python
NeetCodeIO
31 Design Hashmap - Leetcode 706 - Python
Design Hashmap - Leetcode 706 - Python
NeetCodeIO
32 Range Sum Query Immutable - Leetcode 303 - Python
Range Sum Query Immutable - Leetcode 303 - Python
NeetCodeIO
33 Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
NeetCodeIO
34 Middle of the Linked List - Leetcode 876 - Python
Middle of the Linked List - Leetcode 876 - Python
NeetCodeIO
35 Course Schedule IV - Leetcode 1462 - Python
Course Schedule IV - Leetcode 1462 - Python
NeetCodeIO
36 Single Element in a Sorted Array - Leetcode 540 - Python
Single Element in a Sorted Array - Leetcode 540 - Python
NeetCodeIO
37 Capacity to Ship Packages - Leetcode 1011 - Python
Capacity to Ship Packages - Leetcode 1011 - Python
NeetCodeIO
38 IPO - Leetcode 502 - Python
IPO - Leetcode 502 - Python
NeetCodeIO
39 Minimize Deviation in Array - Leetcode 1675 - Python
Minimize Deviation in Array - Leetcode 1675 - Python
NeetCodeIO
40 Longest Turbulent Array - Leetcode 978 - Python
Longest Turbulent Array - Leetcode 978 - Python
NeetCodeIO
41 Last Stone Weight II - Leetcode 1049 - Python
Last Stone Weight II - Leetcode 1049 - Python
NeetCodeIO
42 Construct Quad Tree - Leetcode 427 - Python
Construct Quad Tree - Leetcode 427 - Python
NeetCodeIO
43 Find Duplicate Subtrees - Leetcode 652 - Python
Find Duplicate Subtrees - Leetcode 652 - Python
NeetCodeIO
44 Sort an Array - Leetcode 912 - Python
Sort an Array - Leetcode 912 - Python
NeetCodeIO
45 Ones and Zeroes - Leetcode 474 - Python
Ones and Zeroes - Leetcode 474 - Python
NeetCodeIO
46 Remove Duplicates from Sorted Array II - Leetcode 80 - Python
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
NeetCodeIO
47 Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
NeetCodeIO
48 Concatenation of Array - Leetcode 1929 - Python
Concatenation of Array - Leetcode 1929 - Python
NeetCodeIO
49 Symmetric Tree - Leetcode 101 - Python
Symmetric Tree - Leetcode 101 - Python
NeetCodeIO
50 Check Completeness of a Binary Tree - Leetcode 958 - Python
Check Completeness of a Binary Tree - Leetcode 958 - Python
NeetCodeIO
51 Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
NeetCodeIO
52 Find Peak Element - Leetcode 162 - Python
Find Peak Element - Leetcode 162 - Python
NeetCodeIO
53 Accounts Merge - Leetcode 721 - Python
Accounts Merge - Leetcode 721 - Python
NeetCodeIO
54 Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
NeetCodeIO
55 Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
NeetCodeIO
56 Number of Zero-Filled Subarrays - Leetcode 2348 - Python
Number of Zero-Filled Subarrays - Leetcode 2348 - Python
NeetCodeIO
57 Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
NeetCodeIO
58 Sqrt(x) - Leetcode 69 - Python
Sqrt(x) - Leetcode 69 - Python
NeetCodeIO
59 Successful Pairs of Spells and Potions - Leetcode 2300 - Python
Successful Pairs of Spells and Potions - Leetcode 2300 - Python
NeetCodeIO
60 Optimal Partition of String - Leetcode 2405 - Python
Optimal Partition of String - Leetcode 2405 - Python
NeetCodeIO

This video teaches how to find the path with maximum probability in an undirected weighted graph using Dijkstra's algorithm and a priority queue. The algorithm is modified to maximize the probability instead of minimizing the distance, and a Max Heap is used to store nodes with their probabilities.

Key Takeaways
  1. Calculate all possible paths from the starting node to the ending node
  2. Use Dijkstra's algorithm to find the maximum probability path
  3. Implement a priority queue to store nodes with their probabilities
  4. Pop the node with the highest probability from the priority queue
  5. Add neighbors to the priority queue with their probabilities
  6. Multiply weights to get negative values for Min Heap
  7. Pop from the priority queue to get the maximum probability path
💡 The algorithm is modified to maximize the probability instead of minimizing the distance, and a Max Heap is used to store nodes with their probabilities.

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python

Chapters (3)

Read the problem
1:20 Drawing Explanation
7:45 Coding Explanation
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →