1. Home
  2. Explore
  3. Computer Science
  4. Dynamic Programming Course Intro

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Dynamic Programming Course Intro

Transcript

Hey programmers, I'm Alvin l come to our course on dynamic programming. So dynamic programming is one of my most favorite topics to teach. But unfortunately, I feel like dynamic programming also has a reputation for being a very difficult topic. That being said, I think dynamic programming can be very intuitive. If we actually take a nice gradual progression through the material, right? A lot of students have this habit of just trying to attempt a pretty hard dynamic programming problems, without going through the necessary steps of really understanding the material, right? It goes without saying, if you want to do well on those data structure and algorithm interviews, you definitely need to know dynamic programming. So I hope to give you all the background knowledge, you need to really crush those types of problems. Now, that being said, What problems are we going to solve throughout the course? Here

are a few examples. So one question I can ask you is to calculate the fourth number on the Fibonacci sequence seems like a very easy problem, can also ask you to count the number of different ways to move through a six by nine grid, or something different, like given a set of coins? How can we make 27 cents in the least number of coins? A final example would be given a set of substrings? What are the possible ways to construct a string potent pot? And all of these questions really fall under the umbrella of dynamic programming. And this is really why I think the topic has such a bad reputation or being very difficult, because the problems ranged so much, right? It looks like these problems are totally different. And there may not be any underlying mechanics that we can use to tackle all of them. But the short answer is, we really can if we have the correct way of

thinking about these problems. That being said, let's go over the overall format of this course, in this course, I think our key to victory is going to be to really visualize all of these algorithms, right? So we're going to spend a lot of time drawing things on the whiteboard, as well as visualizing things with animations. To me all the heavy lifting on an algorithm interview is really done when you come up with that picture, right? When you describe that process, and then translating it into some code is really the easy part. Right? The hard part is designing the algorithm in the first place, right? So we're going to draw out of things to make sure we understand the structure of the problem, as well as coming up with a solution. And then once we're really happy with that pen and paper process, then we'll hop into my editor, and we'll solve it in some code, we'll probably have to go

back and forth, until we end up with an algorithm that runs in an efficient amount of time, right. So it goes without saying, we're also going to analyze the time and space complexity of all of our solutions. I'll be writing my code in JavaScript, but you'll find it very easy to translate our solutions into the language of your choice. So in this course, on dynamic programming, we're going to divide the material into two main parts. Part one is going to be about memoization. And then Part two is going to be about tabulation. And don't sweat it if you have no idea what those two terms refer to, don't worry, we'll reach all of that material step by step together, I think you're going to realize if we actually learn these things in all very logical progression, we're almost like discovering these algorithms. And I don't just have to tell us what the algorithms are. So in terms of prerequisites,

I won't assume you know anything about dynamic programming, but I will assume that you understand a little basic recursion, as well as some basics of complexity analysis, right. So you're sort of familiar with big O notation. And I'm sure that we'll be able to review some of that notation as we move along. So I think with all that out of the way, and no further ado, let's hop into the course. Alright, so where should we start? Well, I want us to really ease into this new topic. And so what we'll do is we'll start by attacking a problem that you probably seen in the past that is I want to solve a Fibonacci problem. And so for us, we'll have a particular phrasing of the Fibonacci problem. What I want to do is write a function fib of n that takes in a number as an argument, and I need to return the nth number of the Fibonacci sequence. And just to review, how does the sequence

work? Well, the first and second number of the sequence is just one. And then at any point in time to generate the next number of the sequence, you can just sum the previous two. So for example, these are the first few numbers of the Fibonacci sequence, right starts 112358, and so on. What I'm saying is your number needs to take in like a position of the sequence. In other words, if I asked you for the seventh Fibonacci number, you need to return the answer 13, right? Because the seventh bonacci number is 13. And how do we actually calculate that 13? Well, logically, it's just a sum of the previous two elements, that is five plus eight gives me the 13. So very, very classic function here. And to really get us going for what we do later on in the lesson, I'm going to require us to solve this one recursively, right, it's really going to be at the heart of a topic for today. Why

don't we kick things off by quickly implementing the classic recursive implementation of a Fibonacci function, probably in this function a few times in your programming career, usually one of the earliest examples of recursion that we face. So we'll just lay out the classical notation here. So I want to take in a number and and I want to return the number of the Fibonacci sequence. Like we expect, the base case is just about, you know, the first two numbers of the sequence. In other words, if I'm given some n, that's less than or equal to two, then what I should do is just returned one. And I'm reading this because hey, the first two numbers of Fibonacci sequence are exactly one. But in the recursive case, in general, what I can do is just return the sum of the Fibonacci number right before the one I'm asking for, as well as the Fibonacci number two before the one I'm asking for,

right? Again, the kind of baked in recursive nature Fibonacci is to calculate some Fibonacci number, you can take the sum of the previous two numbers in the sequence right. Now, of course, we should test our code for some correctness, what I'll do is call a few examples of this fib function. So I'll try fib of six, seven, and eight. And I shouldn't get the answers of 813 and 21, respectively, right. So let's give this a go. I'll run this in some JavaScript. There we have it right. 813 and 21. So this is a very, very classic implementation of Fibonacci, you've probably seen this many times before. And we did solve it recursively. And really, what I want to do is give some a larger number to this fib function. So what if I asked for, let's say, I don't know, the 15th Fibonacci numbers seems like something reasonable to ask for. So if I give this code a shot, it looks like the first three calls

of bonacci do work fine, right, I get 813 and 21. But the fourth call is actually still running, right, my program actually hasn't finished. And this is a big issue with this type of implementation with Fibonacci. So obviously, this Fibonacci function needs some work. Let's go ahead and head to the drawing board. Alright, so it's apparent that our Fibonacci function is correct. And that returns a proper result. However, if we give it a large enough value of n, it's pretty slow. That is our function has correctness but lacks some efficiency. In the long run, we definitely want to improve this implementation of a recursive Fibonacci. But to do that, it's really important that we identify exactly where there's even room for improvement. And to do that, I think we should draw some things. This is something I think students actually need to work on. Students have this habit of trying to like

picture everything in their mind. And that works for some easier problems. However, when we want to tackle more complex problems, if we just try to capture all this information, just mentally without drawing it on, like pen and paper, or marker and whiteboard, or chalk and chalkboard, you're going to really lose track of the finer details in these structures. So I want us to be very, very methodical, and we're going to draw really how you should visualize a problem like Fibonacci. And so over to my drawing, let's say that I wanted to trace through what happens when we call a fib with the number seven. That is I'm asking for the seventh number in the Fibonacci sequence, I know that in the long run, I should get back to 13. Right. 13 is the seventh number in the sequence. So I'll keep that goal in mind. But over to my drawing, let's say I called fib of seven, I'll denote that by really

drawing a circle with my value for n inside. So I think about this call to fib of seven, what is it going to do? Well, I know that seven is not the base case, right? Seven is not less than or equal to two. So this call is going to branch out into some more recursive calls. In particular, on its left hand side, I'm going to call n minus one, which is six. On the right hand side, I'm going to do n minus two, which is five. And at this point, I carry over the same logic for the other nodes have the structure, right, if I look at the six node, if I'm routed right there, then that will have a left child of minus one, so five, it will also have a right child of minus two. So four, you can start to see a pattern where really this recursive structure just visualizes as a tree, which is really neat. I hop over to this five node, it will have some children, right, minus one

on slept minus two on its right. And we will actually just continue this process for most of these nodes. But let's say we pause right here. So you'll notice that these notes that have pointed to in red, they're actually the base case, right? For those nodes, I have values of two or one. And I know that those function calls will return immediately. More importantly, that means they don't branch into any further calls. So I don't want to start flushing out the tree of those nodes. Instead, I look at things that are not the base case, right? That is these nodes in yellow. So I'll continue to flush out this tree, but not branch out further for the base cases. So at this point, I built out my entire tree, and I stopped fleshing out the tree whenever we had a base case scenario. So this is actually the full recursive tree. Remember that the numbers inside of the nodes here represent the end that we passed in. That being said,

if we have this visualization, how does this tree really calculate the Fibonacci answer? Right, so let's start to break it down over here. Let's say I looked at some note, in particular, this base case note of two, right? I know that this note is a base case, so it's going to return the value of one according to my base case, when we say return, that really just means return to your caller right return to your parent. So this note of two is going to return one to its parent of three. In the same way, this node on the right hand side of one is also a base case, two will return one, both of those values that are returning, they go back to the parent of three, and three is actually going to add those two values up. One plus one is two. And this makes a lot of sense because we know that the third Fibonacci number is two. So we can continue this process. Okay, this node over here. This

is also a base case. So it returns one. And now the parent node of four is going to sum up both of its children values. Two plus one is three. And that makes sense in itself, because the fourth Fibonacci number is three. So you probably got the picture. Now let's speed things up. For all of these base cases, I know that they're going to return one to their parent. And for all parent nodes that have both of their children ready, that is both of their children returned, they're just going to add up those values. And this process just continues all the way up the tree, right? Just adding our left and right children. To get the answer that we should return the very top of our tree at the root of our tree, we get the final result of 13, which makes a lot of sense, because at the start, we said that, hey, the seventh Fibonacci number is indeed 13. So now that we have a robust understanding

of how to visualize this fib function, what do we actually know about its speed? What do we know about time complexity. And so you may have heard offhand people mentioned that a classic recursive implementation of fib is going to be two to the n in time complexity. And that is the case however, you really understand the reason why. So hidden in this picture is the reason why Fibonacci for us is going to be two to the n in terms of its time complexity. However, something that's kind of unfortunate about this drawing is it's asymmetric. And that's, I think, a big reason why students have a really hard time convincing themselves that a function like this has a two to the n power time complexity. So here's what we'll do, why don't we warm up and kind of go through some basic understanding of time complexity? And I promise we'll answer that Fibonacci question. So let's do a little warm up. Let's

say that I gave you this foo function, notice that it's different from our fib function, right? It's similar in that recursive, this function is kind of arbitrary, it actually doesn't calculate or solve any particular problem. So if I wanted to visualize how this foo function behaves, let's draw it out. Let's say I initially call it the top level foo of five. I know five is not a base case. So it's going to call upon n minus one, or it's going to call upon for four calls three, three calls to two calls one, and then here, we've actually bottomed out at a base case. If you look at the number of calls I made, I basically made exactly five function calls. Which makes sense, because in terms of our base case, where do we stop once we hit a number less than or equal to one and every recursive step, we just subtract one from our current value of n. So overall, I have five calls here.

But if I generalize that, for any arbitrary input, I know that in the long run, I'm going to have about n different function calls recursively. And so for that reason, the time complexity of this is really just O of n time, right? I have to evaluate O of n different function calls. While we're at it, why don't we take a look at the space complexity? Well, you may have heard in past that when we analyze the space complexity of our recursive functions, we should include any of the additional stack space that our function calls take up right, when we make a recursive call, we add that to the call stack, and those must be tracked by our computer. And so since we have about five or n different function calls added to the stack, before we hit our base case, you can see that the space complexity of this code is also O of n space, overall, we're looking at O of n time and open space for

this function. Pretty straightforward stuff, right? Let's look at another more involved function. So let's say I gave you now this bar function, it's another arbitrary function, it's very, very similar to foo, what you should notice is, the only difference is when we make a recursive call, we do an n minus two instead of an n minus one. So how does that actually change the time complexity of this function? So let's say I wanted to trace through this and I made a top level call to bar of six, I know six is gonna call upon four four is gonna call upon to, to call zero and zero actually hits a base case. So this is very similar to our last example, except we kind of see that from one call to the next, we kind of take a bigger step in time, right. And so in a way, we can say that we're moving twice as far upon every recursive call. And this would actually half the number of recursive

calls we need overall. So I guess we might be tempted to say that the time complexity of this one is N over two time, but a keen observer would note that according to our bego, you know, understanding, we can remove any multiplicative constants when we have a time complexity, so N over two is the same as one half times n. So this simplifies nicely, it's just an O of n time complexity. Using the same exact argument, we can also say that the space complexity from the stack is also open space. All right, so let's take a lay of the land, I showed you two functions that are very similar, they really only differ in how they made their recursive calls, right? One did minus one, the other did minus two. But in the grand scheme of things, we saw that they had an identical complexity class, right? We have O of n time and O of n space for both of these functions. So after these

two examples, you may be able to see the reason I wanted to bring them up, right, maybe you're actually ready to make the logical leap and make some conclusion about our classic Fibonacci recursive function. That being said, I don't want to skip any steps. I want to be super methodical, I think, if we pay the cost of understanding fib right now, and I mean, truly, like Absolutely. Understanding fib. It's really going to pay off later on in the lesson when I slam me with some much harder problems. So let's be nice and methodical over here. Let's take a look at some other functions. Let's say I gave you this did function now. very particular Right, we'll pay it no mind. What do we notice about this did function? Well, it has two recursive calls now right inside of every single call. And they both do an n minus one. How should we visualize this one? Well, it's kind of similar to I

guess, our initial fib drawing and shape, where if we start with some initial call, let's say five, five is going to branch to exactly two children, right? Because five is not yet the base case. And for this did function, it does a minus one on its left, and also it's a right child, right. So the next level is just for next levels, just threes than twos, then just ones which would actually hit our base case over here. This is a really nice, like, beautifully symmetric tree, right? Okay, so this is a visualization for our dib function. But what does it tell us about the time complexity of it? Something you'll hear me say a lot in this lesson is when we tackle a quote, unquote, new problem, or a new pattern we're really trying to do is just leverage our past experience, right? So when I look at this tree structure, I'm trying to notice anything familiar, right? Is there some strand

over here that I can grasp that to really feel comfortable and kind of extend my previous learnings, right? Where can I find our base inside of this drawing? Boop, right here. So if I look at this path, I've highlighted in yellow, it's really just the path starting at the root node going down to some base case here, I just designated the leftmost path. And what's really nice about this structure is just referring to the notes in yellow. It's a linear structure that we saw before, right? If I start at the root, it just goes 5432. And one. And so I know that in general, based on my initial input of n, like the length of this path that has a number of nodes highlighted in yellow, there's going to be about n different nodes. If I kind of adapt that language for like the tree, I can also say that the height of this tree is n. So the height of a tree is really just the distance from the root

node all the way to the far this leaf, in this case, that just means the distance from our top level called Five, all the way down to a base case, which is going to be exactly five here. Something you may also hear in passing is we can say that the number of levels in this tree is also n, this term is pretty straightforward, right? When we say the number of levels, a level is just a collection of nodes that are the same distance away from the root. So for example, here in yellow, I have highlighted level zero, this is level one, this is level two, this is level three, and so on. But if I rewind things a bit, I look at the very, very top level, there's one node here, on the next level, there's two nodes. On the next level, there's four nodes, then eight nodes, then 16 nodes, see the pattern? So let's try to generalize that. So I know no matter what, whenever we call some top

level argument for dib, we know that we're going to have one node at the top level. But to get the number of nodes on the next level, we'll just multiply that by two. And the level after that would also multiply by two and multiply to again further levels after that. And I do this a total of n different times, right? Because I know that the height of the tree, or the number of levels in this tree is exactly n. And so what conclusion Can we make over here, we're basically saying that to get the total number of nodes, or the total number of calls a recursive function would make, you would just take the number two, and multiply it by itself about n times over. And that is really the definition of an exponent, right? This is the same as two to the nth power. So we can say that this tree structure, this recursive function has a two to the N, time complexity. Awesome. So we identified

this dip function is having a two to the n time complexity. But what do we know about the space complexity over here, I think a common mistake I've seen people make is kind of automatically assumed that the space complexity of a recursive function will be the same as the time complexity. And that might be a reasonable trap to fall into, because we know that in the long run, we're gonna have to evaluate two to the n function calls. And so I guess that means you have to put two to the n function calls on the stack. But there's actually some nuance to this, the time complexity of this is not the same as space complexity. So let's jump in. Let's say that we made our top level call to dibba five, we know that that is added to the stack in the same way five calls for so it's that the stack, we add a stack frame for every call that we make down until just the base case, right. So at this point, I

reached a scenario where I have a base case, and I'd have about five stack frames on my call stack. And the important insight is when we actually hit this base case that I have highlighted the left one over here, it actually will return when something returns when a function returns, its stack frame is actually removed or popped from the stack. And at this point, only after I have returned from that left one, what I actually add the right one to the stack to be explored. And this process continues. Notice that any point in time the most number of stack frames that we use up, it's exactly five, right, it's not as if we throw all of these function calls on the stack at once. And because we have such a nice tree visual, we know that the number of stack frames that we're ever going to use is really just the height of the tree, right, so the height of the tree is n like we said before, that

means our maximum stack depth is also n. So we have in space complexity coming from the call stack. So overall, for a dip function, we're looking at two to the n time complexity, but only and space complexity. Alright, so let's look at one more function. See, I gave you this very similar lib function. Notice that in its recursive calls, it does an n minus two. So by now you should be able to visualize what structure like this would look like, say we initially called lib with a value of eight, what would the full tree look like? Well, it would just look like this. Notice that it's still a tree, right where every node branches to two children. But this time, we go by twos, right, so if I look for some familiar ground here, I've noticed that from one node to the next, I do one minus two. And this occurs all the way down to a base case. So we already know that, hey, we can

identify this tree as having a height of about N over two. So I guess that means that the time complexity is going to be two to the N over two power, right, because from one level of the tree to the next, we double the number of nodes. So that's that two times two times two repeating pattern for the number of levels and our number of levels is N over two, right? However, we can actually simplify this time complexity, you can take that n over to in the exponent and simplify that to just an N. So overall, we're looking at a two to the n time complexity. And using our same arguments from last time, we know that the space complexity for this from the stack is also going to be N over two, which simplifies nicely to N space complexity. So we see that overall for our loop function, we're looking at a two to the n time, but no space complexity. Alright, so now it's time to look at the big picture, we looked at two toy functions of

dibben lib. And we saw that the only difference in how they made the recursive calls, right did did a minus one and lived in a minus two. And we saw that despite their differences, both functions had an exponential two to the n time complexity, and a linear and space complexity. That being said, Where does our original Fibonacci function fit in this picture? Well, you can imagine that kind of falls right in between, we know that for our fib function, it has two recursive calls for the first recursive call, it makes it does n minus one like did did. But its second recursive call this n minus two like lib. So in a sense, it's kind of like smack in the middle, right? If you let me abuse the notation a little bit, and just talking about the time complexity, we can kind of say that the complexity of fib is somewhere between dibben lib, but we've already plugged in some values, right? You

know, that, hey, the lower bound that as Deb has to to the end, and the upper bound, that is lib has to at the end as well. So that means that our fib function must have exactly two to the n time complexity as well, right? All three of these functions have an exponential time complexity. Awesome. So that was a really complete analysis of why we have this fib function, it's evident that it has a two to the n time complexity and an N space complexity. Right now, the bottleneck that we're experiencing is, of course, the time complexity, right two to the n overall, is not undesirable complexity. But do we really have a nice feel for what this really implies? So let's take a look at this to to the end. So what's the implication of this? Well, you could kind of imagine that, hey, if I asked for the 50th Fibonacci number, that would take you know, roughly two to the fifth power number of steps. And so if you

punch this exponent into a calculator, you're gonna end up with a result like this, this is roughly a 16 digit number. So you should have a vi for you know, this being a very, very, very large quantity. But I think that, you know, to really understand the gravity of what we're really saying here, if we expand this number, that quantity is exactly this. That's over one quadrillion 125 trillion, which is really, really interesting, right? Because we just asked our Fibonacci function for just you know, something relatively modest, right, the 50th Fibonacci number, and it's gonna take quite literally a quadrillion steps to do that. And of course, we can probably do better. So let's work on making this faster. So if I recognize that the bottleneck for this fib function is the time complexity, I know that that comes from the number of recursive calls that I make. So what I want

to do is look for any patterns that I see in the recursive nature of this problem, let's see a quick snapshot of what the recursion for fib of seven would look like, we know that it looks like this tree just like we saw before. So take a moment, look at this tree, do you notice any interesting patterns within it? Well, one thing that I noticed is I can see this subtree rooted at three, there, I have two on the left and one on the right. And if I look at that subtree, I can actually see it in many different places in this tree, right? This subtree rooted at three appears in a bunch of different places, it's very duplicate. In a similar way, I can look at other sub trees, let's say I root myself at four, and see that duplicate four sub tree all over the place. And it's even carries over for larger values of n like fib of five. So I see that this tree has a lot of duplicate sub trees, right? And I want to now draw a

connection between this diagram and what happens in my code. I know that if I route myself in any of these sub trees of five, I know that each sub tree is trying to answer the question. Hey, what's the fifth Fibonacci number? I know that the Fibonacci number never changes, right? If I calculate it once on the left hand side, then the answer I should get back on the right hand side shouldn't differ at all. And so what I want to do is possibly reuse these calculations right? If I calculate the Fibonacci number over here, then I should just store that because later on it might be useful when need to recalculate it over here. I would basically get rid of a lot of the tree, I wouldn't have to travel down this entire recursive tree rooted at five. This pattern of overlapping subproblems is known as dynamic programming. And so for us dynamic program is going to be any instance

where we have some larger problem, in this case, Fibonacci. And we can decompose it into smaller instances of the same problem, we also have an overlapping structure. So for us, right, now, I see that I have to calculate now let's say fib of five, twice over to calculate the larger a fib of seven a solution. And something we're going to be doing a lot in this lesson is really trying to visualize problems in terms of like their recursive nature. So we're going to be drawing a lot of trees. And what I'm always going to do is try to really recognize, hey, what pattern in this tree is duplicate, right? If I do some duplicate work, if I do some duplicate drawing that I know I can optimize that out later on. But that being said, let's go ahead and get to the punch line on this fib function and work on optimizing this solution. Alright, now let me discuss the plan, I think we're

ready to actually implement some code that will actually carry that plan out. Here I have our classic bonacci implementation, this was the one that we ran earlier. And it's definitely too slow, right has an exponential time complexity. So I know that overall, when I want to do is kind of capture a duplicate subproblems, I want to store any results that I get that way, if I have to recalculate those subproblems. Later on, I can just use my stored data. And so the trick here, it's a very common programming pattern, we're going to implement some memorization. memorization is actually one of the overarching strategies we can use to solve any dynamic programming problems. And so just look at the name like why is it called memoization? Well, this refers to like, memo, right? So if I have like a memo, and let's say, like real life, it's really just like a reminder for myself. So using memoization,

I'm looking to do is store some duplicate subproblems. That way, I can just get those results later on. I think a really neat way to implement memorization in JavaScript, as well as many languages is to use some sort of a fast access data structure usually be like your hash map equivalent in the programming language of your choice. For us, that'll be a JavaScript object. And so our plan is to use some JavaScript object. And so what do I want the keys to be, so the keys in the object are going to be the argument to our function, right. And then the value will be the return value, that we have a nice napping for a argument to the function that is a function call, as well as its return value, right. And so what I can do for my existing function is, I kind of just bake in some optional arguments. So my favorite strategy is to do this, and assign a memo to be an empty object. So if

you're unfamiliar with this syntax, in JavaScript, it's pretty useful. What I'm saying is, if I were to call our fib function, and not pass in a second argument, by default, it will create this memo, as containing a new JavaScript object that is empty, of course, right? So it's gonna be useful that way, whoever is actually testing, my code doesn't have to deal with setting up any memo object. So well, I prefer this strategy over here. And what I want to do is treat it as if that, hey, this memo is going to store n as the key and values are going to be just the return values for this function. So what we're going to see us doing a lot in this lesson is at the start, we're going to first check for existence inside of our memo. So let's say that we're somewhere in the middle of recursion, the first thing I should do is kind of add an additional base case and say, Hey, is my current

argument n inside of the memo, and if it is, then I can just get the stored value from that memo. And I'm done. So I'm going to do an early return here, I'm going to return the value that corresponds to that memos key, right, I'm just using the original argument and as a key in my memo, and this condition is really just some classic JavaScript syntax, I'm just checking if some key is inside of a JavaScript object. So really quick, maybe just to warm us up, if you haven't seen that syntax before. So let's say I had some object and had some properties inside and we had a name of Alvin, that's me, then it had a favorite color of like gray. And what I can do is check for an existence of a key in that object. So JavaScript keys are mostly strings, right? So I can check Hey, his name in the object. That's true, is the fav color in the object, make sure

I spell it right. That is also true, I can check for a key that's not there, like I don't know, his location and the object that is false. And so here, I'm just using that same pattern, but for and right, which is going to be a number, technically, it'd be converted into a string key, which would still totally work here. Awesome. So I have my memo fetching logic, right? I check, Hey, is this argument in the memo, but if it's not, I'm gonna have to actually manually do the calculation, which is okay, because I know I need to do a subtree at least once. So what I'll do is I'm going to take the exact return value, right, so this is my return value in the original brute force. What I want to do is actually store that entire result inside of my memo and the key is course and write, the key you use to access is always just what your argument is. And I want to complete the original return.

So I can just go ahead and return what I just put in that memo. So I'm not really changing any return values, or I'm returning exactly the expression that I returned before. But now I'm actually also saving that value inside of the memo object. What I want to do is make sure that all of these recursive function calls are accessing the same memo. So what I'll do is I'll pass in that object to both of these calls are really important pattern here is, I know that I only receive a new top level metal object, whenever I make a top level call, that's a fit, right, because I'm not passing in a second argument over here. However, if I look at my recursive calls, I do pass in explicit second arguments. And so they're actually going to receive the same memo object, and it would be like passed by reference, right, because when you pass a JavaScript object to a function, you actually

receive kind of that exact object, right, you don't receive a copy of it, which is really neat. So basically, I'm giving my function calls a way to sort of communicate to each other, they all have some sort of global information to reference across all the recursive trees. So this is looking good. Again, I just want to emphasize I only added a new argument over here, I added a new base case on line five, then I added my memo storing logic on line seven, but I didn't change any of the functional logic here. Let's go ahead and run these test cases. And we'll see how our code is doing now. So moment of truth, I'm going to run this file. And notice how blazing fast our program was, I still get the results of 813 and 21. And the 50th Fibonacci number is indeed have this very large number. And it basically executed almost instantly. So let's go ahead and head back to the drawing board. And really understand

you know, what happens when we execute this sort of code. Alright, so it looks like we implemented the improved version of Fibonacci by memorizing it. And it's clear by running the program that we definitely had an impact on the time complexity. However, I really don't want us to understand you know how the structure of the recursion tree changes, once we implemented this memoized version of the code. So let's say I want to step through an example of Fibonacci. And let's say I pass in a number six. So really, what I'm looking for here is to get back eight, because the six number of the bonacci sequence is indeed eight. So we know that we're going to have a tree that looks like this, right? This is a tree that would really be the full recursive nature. So this is how the tree would look like if I did not optimize it. And what impact do we have by actually adding this memo object?

Alright, so let's start tracing through this, I know that when I call fib of six at the top level, an important thing to know is I'm not going to pass in some memo object. So by default, my code says it will initialize it to an empty object. And the really important aspect of this is I'm going to create a new object just for the top level call. But then that same object is going to be passed down to my recursive calls, right noticing line five. And so I'm going to travel down my left hand path, right, six calls five, five calls for four calls three, and three calls to, and right now I've hit a base case. So I know that this note of two is going to return one. So that's kind of business as usual, right? In the same way, now I need to evaluate this other note of one, which is also base case, it also returns one. And at this point, my parent of three is actually ready to compute

the sum of its children, right. So one plus one just gives me two. So I just add up those values. And now three is returning two. However, looking at line five of my code, not only is this node going to return to to its parent, it's also going to store it in the memo object, right? So the key insight is, at this point, I would add a key to my memo of three, whose value is to basically in my memo, I kind of read as if I'm saying, hey, the third Fibonacci number is two, right? That in itself is logical. So I can just continue this pattern right? Now I start to evaluate what happens when I'm at this note of t, which is also a base case, it returns one. Now my call to four is ready to compute, right? It's going to take the sum of its both children. So it's going to do two plus one gives me three. But of course, it's also going to store that inside of the memo, right? It's going to cash that

result out to be used later on. So that means I make the N my key and I make the return value, the value, right, so I'm going to have four points to three inside of my mental object. And now here's the beauty of this memoized solution. At this point, I need to compute what happens for fib of three. However, this is actually going to hit one of the new base cases I added, right? I know that three is in the memo object looking at line two of my code, right? It's in the memo object. And so I just immediately return the stored value. And so this call to fib of three is just going to return the stored value of two. And if I do that, I won't have to travel down the full, you know, recursive subtree rooted at three, right? I don't need to travel to these nodes at all. So I already used some stored value in my memo. At this point five is ready to return right five will take The summer

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent