Graph Algorithms Interview Course
Transcript
This course will help you learn what you need to implement graph algorithms and use them to solve coding challenges. Alvin's dynamic programming course is one of the most popular courses on our channel. And now he's back to teach you graph algorithms. Hey, programmers, I'm Alvin from Structy. Welcome to our course on graphs. And in particular, this is going to be about graphs for your technical interviews. Of course, graphs are a very common topic when it comes to those technical interviews. And in particular, what I want to emphasize throughout this course, is the handful of patterns that come up time and time again, on those technical interviews. in just about two and a half hours, I'm going to give you all the tools you need to basically cover I'd say about 80% of all graph problems. And so what I have in store for this course, well, I think the key to victory for your data structures
and algorithms, and especially your graphs is to visualize things, right. So we're going to do is trace through a lot of different algorithms, and be sure to understand them at a high level. And that means going through different animations here, I think graphs have a pretty bad rap for being a difficult topic. Because to a beginner, you can have very, very different narratives around a problem, and not really understand. They're all really based on a graph premise. So we're going to realize that a bunch of different things can be understood as graphs. So when it comes to the prerequisites of this course, I'm going to assume that you know nothing about graphs. But you do know how to code, right, so I'm going to have the expectation that you understand some recursion. So as you work through the course, and learn about different graph patterns, we're going to use those patterns to solve
some very classic interview problems about graphs, right. And I'm going to give you plenty of opportunity to practice these patterns in different problems that we will be ready whenever you have them on a technical interview. What I love about the topic of graphs is just using a handful of different algorithms, you can cover the majority of graph problems, right. For every graph problem that we cover, we're going to split it up into two sections, section one is going to be about the approach for the video. So we're going to go over the strategy and overall theory, and be sure to sketch out a nice meaningful picture. We're also going to talk about the complexity of the algorithm in the approach video. Following every approach, we're also going to implement the code of course, I'm going to be writing all of my code in JavaScript, you'll be able to follow along in any language that you like.
So that means occasionally I'll be switching to my code editor where you of course can follow along. We're also going to be sure provide links in description as well as links on screen. That way you can formerly you read the prompts for every problem, as well as look at the different test cases. Alright, I think that's enough introduction. For now, let's hop right into the course. Alright, programmers. So let's jump right into the course, I want to start by giving you some background about your graphs, we're going to go over the graph basics that you need to start attacking problems in a technical interview. So first off, what is a graph? A graph is really just a collection of nodes and edges. So with respect to nodes, you can visualize them as typically just some circles with some data inside of them. So I'll put some letter values in my nodes over here.
And when we refer to edges, that would be just any connections between nodes. So for example, if there was a connection between A and C, it would look something like this, right? What I can formally say is there's an edge between A and C, I can create many edges between any nodes I want within this graph. Another word you might hear out in the wild when it comes to describing nodes, as you might hear the word vertex being used, right, they're really the same thing. In this course, I'll stick to the word node. And an edge is just a connection between a pair of nodes. And that's really all a graph is at a high level, where things get interesting is how we can use this graph framework to actually solve a problem, right. So if you think of these nodes as just things and the edges as relationships, a graph is grid describing the relationship between things. For example,
we can say that the nodes here are cities and edges would be roads connecting cities are in a similar way, maybe our nodes here are courses, and then the edges represent prerequisites. And so in the future, we're going to use graphs as a way to illustrate and frame some narrative problem. Let's talk about this graph. In particular, here, I really have drawn a directed graph. And that's because I have some arrowheads along the edges. That would be a comparison to an undirected graph. So here, I have really the same structure, except I don't have any arrowheads on the edges here. And that means that there is no directionality to it right. If I look at the directed graph, let's say I was at the node A, well, then I can travel to B or C, let's say I move to C. However, once I'm at C, I cannot travel to a, I can only travel to E, right? That's because I have to obey the direction
of the arrow heads here. By take a look at my undirected graph, let's say I was currently situated at the scene over here, that I do have the option of traveling to either a or E, right? So if I traveled to a, that's all good, I can even travel back to C. So think of as an undirected graph as a two way street. For now we'll just continue on with our directed version. Let me also introduce some useful terminology we can use when talking about the nodes in our graph. If I was currently situated at this a node, I can refer to B and C as neighbor nodes. Alright, so a neighbor node is really any know that's accessible through an edge, of course, obeying the direction of the edge. In other words, if I was currently situated at the sea node, that I only have one neighbor of E, right, if I'm at the sea, you know, then I won't consider a neighbor. Awesome. When you visualize graph algorithms,
you should really sketch a picture that looks just like this, right literally drop nodes as circles and arrows as your edges here. However, when it comes to how we implement this algorithm in some code, we're gonna have to represent it in a more programmatic way. Right? So in my brain, I think of this image of like nodes and arrows between them. However, in my program, I'm going to use typically an adjacency list, it's probably our preferred way to represent and graph information, right. So depending on the programming language of choice we're going to use typically, we would use some hash map data structure to represent an adjacency list. Really, we're looking forward to using some constant time, I'll look up data structure that has a key value pair mapping, right. So if you're in JavaScript, they'll be an object, if you're in Python, they'll be a dictionary. If you're in a language like
Java, or C, you'll be using an unordered map. Looking at this hash map, I have drawn or this adjacency list, the keys of this adjacency list are going to be every node in my graph, right, so I just have all of the node values A through F laid out as the keys. However, if you look at the corresponding values, the values are actually going to be an array, right? So if I look at this very first entry, it says that I have a node of a and then in the array of populated all of the neighbors have a that is a has two neighbors have BNC. That's why I have this correspondence within my adjacency list. That holds true for every entry within my adjacency lists. So for example, let's say look at the entry for e. So I go to the spot and make j c list where the key is E, it only has a one outgoing edge to be. That's why the array for he only has be inside of it. One thing to also note is even if a
node has no neighbors, it should still appear as a key within my adjacency list. For example, if you look at the D, node D has no outgoing edges. That's why its neighbor array is empty. However, it should still at least appear as a key within my adjacency lists, right, that way, you can still know that the D node exists. So at the start of the course, will usually be taking in adjacency list as the information to represent a graph, right. But as we sketch through things on the whiteboard, we should be visualizing them using a nice picture like this. Awesome. So let's actually jump into our first pair of algorithms. To me, the must know algorithm for a graph is really going to be to do some sort of traversal on it. Why don't we start by talking about a depth first traversal, something you may have heard of before, right, now we're going to talk about the depth first traversal algorithm
that operates on a graph. So let's start by understanding at a high level what order a depth first traversal would give you. So let's say I had some starting node, and I'm gonna choose a as my starting node, right, so I'm gonna color it here in yellow. If I was following a depth first traversal. Now that I've, you know, chosen as my starting point, I can either hit B or C. Next, I'm just gonna commit to using B. So let's say I had the sequence so far have a comma b. And at this point, if I was truly following a depth first traversal, I must go deeper to the D node. In other words, I don't go to the C node yet. Cool, that would be a true depth first traversal, right. At this point, now that I've bottomed out at D, D is a dead end, right? I can't travel to F from D, because that would be disobeying the arrowhead. And so now I can move to that other neighbor of C. And from here, the algorithm
would continue, right, I go from C to E, and then e to B. And technically, I would have to double traverse some nodes like B and D over here. So overall, in this yellow coloring, I have colored the full region that a depth first traversal would explore starting at a notice that if you started at a it would be impossible to reach F. And that's kind of normal, right? That's kind of why we use these traversal algorithms that can tell you whether or not you can travel between some nodes. And we'll see that literal problem later on. Right? So you're probably wondering, you know, exactly how do we implement this, but for now, I just want to stay focused on the order that we got, right. So just regarding our depth first traversal, we remember the first three iterations of the algorithm, we hit the sequence of a B, D, right, that's indicative of a depth first traversal. Now
let's compare that to the breadth first Marion. So I'm going to lay down the same exact graph, we're also going to start a traversal at the a node, but this time follow a breadth first order. So I have a first and let's say, you know, I chose B as my next node when it comes to breadth first traversal. It doesn't matter like which, you know, initial neighbor you choose, so I'm just gonna choose B. But now that I've chosen B, if I was following a true breadth first traversal, I must hit c next, right. And that's the main difference between our depth first and breadth first reversals for the same graph, my depth first would start a B, D, whereas my breadth first would start a, b, c. And so you're probably wondering, is there any importance between this nuance right? When would I prefer depth first over breadth first, or vice versa? Either a depth first or breadth first traversal would explore
the same exact nodes within a graph. However, it would explore them in a different order, right? And this is more obvious to see when we have a larger graph with way more edges. And so let's look at how he depth first traversal explores again, but this time on a much larger graph, let's take a look at this one. So I'm going to choose some random node as a starting point, let's say I chose this node in yellow, that was doing a depth first traversal, what I'm going to do is, you know, pick a direction and travel in that same direction as far as possible before switching directions. So let's say I move to the right, at this point, I would have to continue moving toward the right, until I can't move to the right any longer, at which point, I have to choose some new directions, let's say it was downward. I'll keep doing that until I can't move downward anymore. And so I'd have to move to the left
now, now I'd keep chasing this single path in a very deep direction. So that's behavior indicative of a depth first traversal, right, you're exploring one direction as far as possible before switching directions. Let's compare that to a breadth first traversal. So let's say start at the same node in pink, if I was following a breadth first traversal, it would look something like this. From the starting point, I would explore all of the immediate neighbors of this node, kind of in a circle like this. Now I just keep applying that behavior. So as you notice about the breadth first traversal, is it'll tend to explore you know, all directions evenly, right, instead of just favoring One Direction all the way through. That's really the only difference between a depth first and breadth first traversal. Later on the course, I'll bring up explicit problems where you might prefer one over the other. All right,
but for now, what I want to do is give you all the background you need. So you can actually build this algorithm will kind of talk about things at a high level, consider this the pseudocode, then, of course, we'll express it in some JavaScript code later on. So when it comes to actually implementing in code, these two algorithms, the key is to understand that a depth first traversal uses a stack, and a breadth first traversal uses a queue, recall that a stack is something where you add to the top and remove from the top as well, or is it Q is something where you add to the back and remove from the front, and it gives you two very different orderings. That's really the only difference between these two algorithms. So let's start by tracing through our depth first traversal, of course, using a stack, so I'm going to use a slightly different graph. And to visualize my stack,
I'm going to use this bar to represent the bottom of my stack, obviously, for me, at least I think of a stack as some vertical data structure. Cool. So let's say I just arbitrarily chose a as my starting node to perform my depth first traversal, right, in the long run, just want to print out all different node values within this graph. So what I'm gonna do is I'm gonna take my starting node of a, and I'm just gonna immediately initialize it onto my stack. So right now as the only thing on my stack, it's also at the top of my stack. And now I can enter the flow of the main algorithm here, because I have a stack, what I can only do is remove the top of my stack. So that means I pop off a from the stack, and consider the a node, my current node being looked at, right? At this point, let's say I print out a to my console. And from here, what I want to do is consider A's
neighbors, right. So if I look at the C node, what I should do is just push c to the stack, then also push B to the stack, right. And it doesn't matter like in which order you push these neighbors. If I want it to hit B first, then I'm going to push them second, right? Awesome. That would end like my first iteration of this depth first traversal. Cool. So at this point, I can look at my stack, and my stack still has some data on it. So I should do is again, pop the top of my stack. So I'm going to pop and be off my stack. And that becomes my current, I'm also going to print it out. At this point, I look at B's neighbors, B has one neighbor of D and so I push d to the top of the stack. Notice that because I have a stack D ends up on top of the C, right. And so now when I get to another iteration, when I pop the top of my stack, I look at the D node as my current, right,
and I can print out D. And this feels good because so far, my print order would be a BD, notice that I kind of pursued that single path deeply following a BD. But I have to look at DS neighbors, I can take f and just push f to the top of my stack. next iteration, my stack is still on empty. So I should do is pop the top F is now my current, I can print out F, but f has no neighbors. So F isn't going to push anything else to the top of the stack. Right? At this point, I get to this next pass, and I pop the top of my stack. And that means C is now my current, I can print out CS value. And then I can look at Sue's neighbors. And I just push e to the top of my stack. On this last iteration, I popped up on my stack, he is now my current I print out he since he has no neighbors, I don't push anything else to the top of my stack. And at this point, I've reached the
state where my stack is empty. And that means my algorithm is done right that means you explored as far as possible within your graph. Notice that it might not necessarily be the case that you're able to hit every node of the graph. And this particular example it was possible though, awesome. So let's redo that trace using Our breadth first algorithm, which means we just adjust things slightly. And we use a queue order. Remember that a queue is a first in first out data structure, meaning things enter to the back, and then they leave from the front. And so let's say I use this arrow to represent the directionality of my queue, right. And I start the algorithm in the same way for my breadth first traversal. Let's say I want it to begin at node A. So I just initialize my queue with a cool, so I start by removing the front of my queue. So a becomes my current node, I can print
out a as well. And now I consider A's neighbors, right. So I consider B and C. If I wanted to travel to B before C, then I should push B to my queue first, right, so I add B to the back of my queue, right. And I should also add c to the back of my queue, right. And that would actually end my first iteration. So now I look at my queue still has some stuff on it. So I removed the front of my queue, that means B becomes my current. Of course, I print out B. Now I consider B's neighbors. So I just look at the D node, and I push d to the back of the queue, since D enters through the back and ends up behind the C, and that's really important behavior. next iteration, I removed the front of my queue. So my current is now see, right, I can print out see, and then look at sees neighbors of just E and I add e to the back of the queue, which means that in the order of my queue, he ends up
behind the my next iteration, I removed D from the queue, and I print out the edits neighbor of F to the back of my queue. next iteration, I removed e from the front of my queue, print it out. Since he has no neighbors, he is not going to add anything else to the back of the queue. And of course, finally, f leaves the front of my queue, I print out F, F has no neighbors, at which point now my queue is totally empty. And since our queue is empty, that would be the end of our algorithm. Alright, and that's all there is to our depth first and breadth first algorithms, they're going to be the nice baseline code that we use to solve many different graph problems. I think that's enough theory. For now, what I want to do is now switch to my code editor, where you can actually implement these in JavaScript, hey, programmers, here I am in my editor, what I want to do is now show you
how to implement those depth first and breadth first algorithms. So we'll start with the depth first. And my goal is really just to build a function that will print out all of my values in the graph, according to a depth first traversal, right, we're going to define this function depth first print, making an arrow function in JavaScript, it's going to take in the graph, which is going to be given as a nice adjacency list. And this is actually the same graph. Now last example we traced out, I'm also going to need to specify some starting node here, I'll call it a source node, we're going to begin the traversal. Starting at that node. Cool. And so we know inherent to a depth first traversal is going to be a stack. So I'll show you how to implement this iteratively, which means you need an explicit stack. For me in JavaScript, that's as simple as just using a JavaScript array,
right? I'll make it empty at the start. And I can use this array as a stack, if I just commit to using operations that manipulate the same end of the array. In other words, if I just use push and pop, that will always manipulate the end of the array, right? removing and adding to the end of that array. What I want to actually be sure to do is I want to initialize the stack with my starting node, that is with my source node. Remember that like a node here is really just designated by some character. Cool. And when it comes to designing like the main loop for the algorithm here, do you want to keep running the algorithm while the stack is not empty? In other words, wall stack dot length is bigger than zero, that I have to keep running. That's very reminiscent to what we expressed on the whiteboard. So when it comes to performing like a single iteration of this depth first, what I want
to do is remove the top of my stack. So if I do stack dot pop, that will remove the last item of an array, in this case like the top of my stack, and also return it to me. So I'm going to save that to a variable, I'll call it my current. And so this point would actually be a great opportunity to just print out that current. So I'll console dot log current, right? So looking at, you know, this example over here, since I initialize a stack to contain just the source note of a, on the very first iteration, this while loop, I would of course, pop out a, then I would print it out, right. And from that point, what I want to do is consider A's neighbors of B and C. So if I want to look at like the array associated with a, I can just key into my graph, right, cuz my graph is an object right now. So if I say graph, square bracket, current, right, if current is a, that means graph, square
bracket current would give me back this array. I want to iterate through every node or every neighbor in that array. So I'm going to nest a loop here. And I say for let neighbor of that array. So if you're familiar in JavaScript, if you just use a for of loop, they'll iterate an order through an array. So now I'm hitting a neighbor as B and neighbors see. What I want to do with those neighbors is simply Push them to the top of my stack. So that will just be stacked up, push and push this neighbor. Awesome, I'm going to be sure to push every single neighbor that has. So sometimes I'll have two neighbors. Other times I'll have one neighbor, or even no neighbors. That's really all there is to implementing a nice baseline depth first print. Something that I do want to point out, my favorite way to implement this algorithm is to consider like processing your node, when it leaves the stack,
not when it enters the stack. In other words, I usually write like my print statement, right after something is popped. And the thing that I pop is exactly what I print. Right. So let's go ahead and give this a run, see what we get. It looks like in my terminal, I got the order of AC e b df, which you'll notice is slightly different from what I expected from over here. However, this would be also a valid depth first traversal, we have to bear in mind is you know, depending on like the arbitrary order of values within the same neighbor's array, you could tend a different direction at first, right? Most important thing I look for when it comes to verifying a depth first is to make sure that I you know, chase the same direction before switching directions, right. So since I started out with a C, so I go a and then to a C over here, the next move would be going to E and that's exactly
what happened in my code, right. And then once I hit E is actually a dead end. So then I can go on to my other lateral neighbor like B, right. And so I can contrive the same order expected here, if I just flipped this right. And so I put c followed by B. I'll give that around. They're both valid. depth first traversals. See what we got now. Cool, now I get the exact order of A, B, D, F, C. And really think about why that is, right. So let's say that I just popped out a from my stack. So I printed out a that's nothing fancy, right. And then from there, I start iterating through the array that's associated with a right, so on the first iteration, I iterate through C, right? If I push C on the stack, let's say this is the bottom my stack, by pushing on the stack, it's right here. Then followed by that I pushed B on the stack. Now B is on top. Since B is on top, I know like the next top level iteration,
this while loop, I would remove B and that's going to be the next note I visit. And so they're really both depth for sure Russell's. Nice. So two things to note, you're definitely going to use a stack to implement depth reversal. And you can use the stack in a few different ways. Right? So here I'm using like an explicit like array as a stack. And I'm implementing this using some iterative code, right. So using a few loops, right, what you can also do is implement depth first recursively, because I know any recursion uses the underlying call stack. So let me show you how to implement that as well. And when it comes to, you know, having all these different tools in your arsenal, I would definitely practice both the iterative and recursive flavors. We'll see that later on in this course. So let's say I wanted to solve the same problem. But now recursively, it's actually going to be less code. So I'm
going to have the same sort of arguments, I'm going to have the graph which is the adjacency list as well as a source node, consider like the source node as like your current location. So if I'm at some node, maybe the first thing I should do is just print out myself, right, print out this node, so I'll do is console dot log, this source node. And that feels good just from the get because when we actually do a top level call to this recursive function, they're passing in a as the source node. So I do want to begin a as a first note in my print, and then from there, I need to look at AES neighbors. Well, if you want to look at as neighbors like before, just key into the graph, adjacency list using that node, right, and this would give me an array of CNB. Now I just iterate through that array. So I'll say for let neighbor of that array. And at this point, what I want to do is now
do the recursion, right, so I make a recursive call on each of these neighbors. So for me, that means just called depth first print, you give the same graph, right, the graph object doesn't change, but you should change like the source node. Now you want to pass in that neighbor as the source node. And you're going to make a recursive call for every neighbor in that array. And this would actually be all we need. Let's go ahead and just run this version. divider run over here. Looks like now we get the order AC E, B, D, F. And that's really again, another type of depth first print, right, not exactly this order, because this time we chased c first, right, we went a C, I want to get exactly this ordering and my recursion, then I would have to put in B first, really same sort of pattern. Now let's get that into the run. Good AB de FC. One thing I want to bring up about this recursive
first is it has no explicit base case, meaning there's no obvious like, if statement that just like returns like you'd typically see in most recursion. That's because in this problem I have an implicit base case when a node like he is a dead end. All right, let's say my current source coming in is he, well, then when I iterate in this for loop, I'm iterating through this empty array, I mean to have zero iterations. If you have zero iterations, then you never make a recursive call. Right? That's the same thing as having a base case, right? A base case is really just a scenario where we don't have a recursive call. So that's how this code still works. Alright, so now you know how to implement depth first in two ways, right, iterated and recursively. And they both use definitely a stack. Let me now show you how to implement your breadth first, right as well comment
out some of this code. Now we'll do a nice breath first, give myself some room over here. So for a breadth first, we want to solve the swan iteratively. And it's really only possible iteratively, right. So I know a breadth first traversal demands a queue, if you try to like implement a breadth first traversal using some recursion, and under the hood, there's some stack data structure, that's going to fight against the queue order that you want, right? So for breadth first traversal, you're always typically going to be writing some iterative code. So some loops, right? Let me define this, I'll say breadth first print, take in the full graph, adjacency list, as well as the source node, I want to initialize my queue. With that source note, again, the queue here is just going to be an array in JavaScript. So I'll say const q equals an array that begins with just the source node.
Awesome. And I'm going to use this queue by just committing to two specific methods on my arrays in JavaScript. So if I use array dot shift that removes the first element of an array. If I do array dot push that adds to the last position of an Array. And using those two methods in combination would give me a nice cue, right, add to one end and remove from the other end. So like before, we're gonna have a while loop, we're gonna iterate while our queue is not empty. And so while queue dot length is bigger than zero, nice. And same thing as our iterative, you know, at first, you want to start by just removing the front of your queue. So I'll say q dot shift, that will remove the first element as well as return it to me. So I can save in a variable, I like to call it current, just like the whiteboard, right? And from there, maybe I'll print it out. So console
dot log, this current node. And from here, just consider your neighbors, right. So if I key into my graph, using this current node, that gives me an array of its neighbors, I want to loop through each of those neighbors. So I can say four will say let neighbor of that array. And for that neighbor, I want to add them to the back of my queue. So for me, that would mean simply q dot push, I'm going to go ahead and push that neighbor. Awesome. So I remove from the front, and I add to the back. So that looks pretty good. Let's go ahead and give it a run. And actually, before I do that, I'm going to change the order of this, put the CNB. Again, doesn't really matter the relative order for neighbors, I just want this exact output, and we'll talk about why that is right. Give that a run. So I get ACB EDF just like I expected ACB EDF, right. So let's say you're on the first
iteration of this breadth first print, I know that I would have just removed a because I initialized a on the queue, right? So my current is a and I print out a and then from there, I start iterating through this array, right. So on the first iteration, I have C, that means I put c into my queue, right? And then afterwards, I put B, if you put C and then B, that means C is at the front of the queue, which is why on the second iteration, I have C first, right? So that's how you can manipulate potentially the lateral order of a breadth first print. Awesome. That's all there is to this traversal algorithm, what I really want emphasizes, especially if you look at the apples to apples iterative code, you compare depth first or breadth first, it's almost identical code. You're really just changing how you access items in your array, right? You either pop or push or you shift and push
harder than that the whole like structure of this code is identical, right? All right. So that's our introduction on depth first and breadth first for our graphs. In the next section, we're going to start to solve a problem, right, which will be really fun. I'm just utilizing this code as our baseline tool. And then that section also promised that start doing the analysis for bego of these algorithms. So let's jump back to that whiteboard. Hey, programmers, welcome back, right, and let's go over the approach for this has path problem. So in this problem, we're gonna take in an adjacency list representing a graph for this problem, and really all graph problems, you definitely want to visualize this one with a picture. And so what we'll do is we'll interpret each key of this adjacency list as representing a distinct node. And if I look at any particular list, I can see that this f node should point
to G and I. And they do tell us in this problem that I have a directed graph. So I'm going to draw arrowheads on these edges here. So F points to G, as well as f points tie. And I'll create similar edges based on the information in the given graph. So we end up with an image like this, until they tell us that this is a directed graph that explains the arrowheads, but they also tell us that this graph is a cyclic. So if you're unfamiliar, a cyclic just means No cycles, that kind of begs the question, what is a cycle in a graph. So a cycle would be a some path through nodes, where I can end up where I want started. In other words, if I started at the a node over here that I can go to B, then from there, I can go to C, then back to a, and so on and so forth. So if I did a traversal, on the Sigma graph, I would get an infinite loop. And what they're saying is, our graph input
is guaranteed to be directed. So it has arrowheads, but also a cyclic, so we don't have to consider any infinite cycles here. That being said, In this problem, we also want to take in not only the graph information, but also a source and destination node, we want to do is return true or false indicating whether or not we can travel from the source node to the destination node. In other words, is there a path that exists between those two nodes? For this problem, you can use either a depth first or breadth first search to actually solve the problem here, I'll trace through in this approach video, just the depth first search. But in the walkthrough, I'll be sure to code it up both ways. So let's say started at my source node, I know that if I was doing a depth first traversal, I can either choose the IRG, let's say happen to choose to G next. Now I have no choice, right? If I'm doing truly a depth
first, I should go deeper to the H. So then I hit this H. And as I traverse through these different nodes, I need to ask myself if my current node is equal to my destination. So far, that hasn't been true. At this point, I bottomed out with my h node, I can't travel any deeper. So now I can move laterally to a node like I, at this point from I can either move to a K or a G, let's say by luck, I just happen to go to the G, this would actually bring me down a path I've explored previously, which we can optimize later on, but wouldn't be too much of a big deal. Eventually, if I continued this depth first search through the graph, I would end up at a node that matches my destination, at which point I can return true signifying that there must be some path from F to k, just doing a depth first search. And as we do this depth first search, it's really important that you obey the directions
of your arrows. So I should never try to travel upstream. So that was a scenario where we were able to find a path from source of destination. That's why we return true. Let's reset and say that now, I should return false. Alright, so let's say my source was J. So I start at J. And I'm trying to get to my destination of F. If I start a depth first traversal, here, sorry, my j node traveled to the AI node. At this point, I can hit either the G, okay, let's say I happen to hit the k, this point of bottom now. So now I can move to the G. And then from there to the H. And at this point, there's actually nowhere else I can go, right. So if I finish my traversal through the graph, using either a depth first or breadth first and I never hit my destination, then I can just return false, right? It must be the case that there is no such path from my source to my destination. When it comes
to implementing the depth first and breadth first reversals on this graph, it's going to be exactly what we're used to, you can either use a stack and solve it recursively. Or you can do it iteratively. And use a queue in which case you'd be doing the breadth first traversal. We talked about the complexity of this, let's say that n is the number of nodes of our graph, a common thing that you can also do with these graph problems is define e as the number of edges here and edges refers to a connection between two nodes, basically just the arrows. So if we use these two terms of number nodes and number edges, we would have a time complexity of our V o of the number of edges as because we would have to travel through every single edge of our graph. Here, the space complexity would be based on the number of nodes, right? If I solved it, recursively, or even iteratively, with some sort of a depth
first stack, then the worst case, I would have to have every single node on the stack, right? Likewise, if I saw the eternity with a breadth first I would have every single node on the queue. So that's just one way we can define the terms for analyzing the time and space of this graph. Typically, for graph problems, another acceptable way to analyze the time and space of your algorithm is to just use a single variable and just define n as the number of nodes. That's because if you say n is the number of nodes, then we can also say that n squared would be the number of edges, or that big O. It's about the worst case. So let's imagine the worst case graph. Let's say I just had these nodes of ABC. Well, if I wanted to create as many edges as possible, how would I just create a single edge? Well, an edge is just a connection between two nodes. So you could just really
draw an edge for every pair of nodes in your graph, something like this. And that's why we can say that n squared is the number of edges of any particular graph. And so if you just wanted to use n to define the complexity here, then you could say that your time is going to be O of n squared, and your space complexity would still be O of n. Do know that these are both two valid ways for defining the complexity for a very typical graph problems. That being said, I think this is pretty straightforward. Let's hop into the walkthrough video while we're actually implement both a depth first and breadth first solution for these. I'll see you there. Hey, programmers, Alvin here, right now. Let's go over Ah, JavaScript solution for this has path problem. And so we'll jump right in, we're gonna start by solving this one using a depth first traversal, which I know requires some underlying stack data structure,
I'll just implement that using recursion. So I can leverage the call stack to get my ordering. And so I'm gonna solve this recursively, I'm gonna consider my source argument as like my current position during the traversal. And so I can have a base case in check. All right, if my source is equal to my destination, that I must have found the thing I'm looking for. So just return true. This base case signifies that I found my destination. So there must exist a path. And so I return true, always paying attention to the type that they want us to return for this function. Let's say it's not true, well, they need to keep looking. So what I should do is consider my current node, which is source, consider its neighbors. If I key into my adjacency list, I know that this is going to be an object. So I key into it using my source, that would give me an array of all of its neighbors. So for example,

Ask anything
We've read this whole study set, so questions about it get the best answers.