1. Home
  2. Explore
  3. Computer Science
  4. Understanding Recursion

Study methods

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

Understanding Recursion

Transcript

When learning about recursion, it can seem  like you're always going back to the beginning.   In this course, the simple engineer will help  you understand recursion using animations,   thought processes, and more. Hey, guys, and  welcome to another video brought to you by   the simple engineer. In today's video, we are  going to delve deep into the depths of recursion,   and strengthen your algorithmic mental model  around this programming paradigm will do so by looking at a variety of different examples  and animations. So let's get right into it.

The first question that we have to answer about  recursion is what even is recursion? And I think   the best way to talk about it is through this  analogy, and let's imagine that you're sitting in   line waiting to withdraw money out of an ATM. And  for the sake of this example, let's assume that   this right here is you and you have this question  this underlying question. And you want to know how many people are standing in front of you in  this line. And this kind of brute force, iterative   version of you says, Well, what I can do is I  could step out of line, I could run to the front,   and I can maybe, maybe count one by one. And maybe  I store these counts in some auxilary, you know,   notebook that I have some external variable that  you can imagine, and then you run down this line,   and you get back and you say, Okay, I got my  answer. But I did a lot of work. And we want

to kind of switch this paradigm, we want to think,  how can I be lazy? What's the least amount of work   that I can do, and sort of break this problem down  in some sort of sub structure? And so what I do   well, I tap on this girl's shoulder in front of  me, and I asked her a very simple question, I say,   hey, what number are you? And she turns around  and looks at me and says, you know, I'm sorry, I don't really know. But what I'll do is I'll ask  the woman in front of me. And what happens is,   this process kind of continues, and it continues  up until we hit some stopping condition. And this   condition that we get stopped at is when we hit  this woman, and she taps on this guy's shoulder.   And he says, she says, hey, what number are you in  line? And he gives this response. And he's number

one. And this is interesting, right? Because this  is kind of the stopping condition to this sort of   problem that we were solving. And what she does,  if she takes that number, and she says, Well,   if he was number one, then I'm basically  one plus one, because I count myself.   And this guy says, Well, if she was number  two, that I'm one plus whatever she was,   and this idea unravels backwards to the original  asker. And this woman basically says to the guy, hey, there were, you know, 10 people  in front of me, I count myself.   And now I'm at 11. And it turns out, that we can  model this problem with this simple blueprint,   we ask the first question, what's the least  amount of work that I can do? How do I break   this problem down into some sub problem?  And the second question that I have is,   when would the process complete? Like, what's  my stopping condition. And in this case,

it's when we hit the first person in line, which  is the gentleman withdrawing money from the ATM, it just so happens that we can actually write  this problem in a very simplified, minimal,   beautiful piece of code. And the function that  we have is just this get my position in line. And   we have this kind of abstraction of a person  that we have. And notice the return values in   integer. And, again, if we think back to those  two questions that we have for this blueprint, we say if the next person in line is null,  then we must be the first person in line.

Right? That's kind of this base case, imagine  nobody is in line, well, then you're probably   the first person in line. Now, if we don't satisfy  this conditional, then what do we do, we do just   a little bit of work, we say, I'm going to count  myself as somebody that contributes to the number   of people in line. And I'm going to add this  kind of recursive call, and I'm calling myself. And this is the interesting property  of recursion, we're calling our self.   But the parameter that we condition on actually  further progresses us to the problem that we're   trying to solve. And so I'm not I'm not passing  the same person object into the function again,   I'm actually passing a person that progresses me a  little bit closer to the question that I'm asking,   which is, how many people are in front of me. And  this is really all recursion is about is how can

I take some large problem and break it down into  a bunch of subproblems such that each invocation   of my method gets me a little bit closer to the  problem that I'm trying to solve? Let's think   about another example. Let's take back to the the  school days where you're writing a bunch of essays   and typically this process, at least for me, is  you know, you writing So you submitted to your   professor and he says, Hey, you know, that essay  was terrible, I want you to go make revisions. And the essay gets passed back to the student.  And this process can actually continue over and   over and over again, you write an essay, you  make revisions, you submit it, it gets denied,   and you rinse and repeat. And you do this  until the professor says, Okay, that was good,   I'm going to put it into my briefcase, and start  grading it. And it just so happens, this, again,   is this kind of recursive strategy that can be  developed. If we look at a simple piece of code.

And what are we doing, we're really, we look  at an essay, we revise the essay, we read it,   we get feedback on it, we apply changes to it.  And then notice, we just call ourselves again,   right. And there's a single base case  kind of hidden in here. And we do it   until the essay is complete. And notice  that each invocation is the same essay   object. But what we've done is we've inched  our way a little bit closer to that goal, that goal of no longer needing revisions  on the essay. So the whole process again,   just to re emphasize is that we do a little bit of  work on each invocation of our method call Intel,   we hit some base case, some stopping condition  that says, hey, you no longer need to continue.

So again, like what is recursion, recursion is  nothing more than a method that calls itself   and to be more precise, it's usually a method  that maybe returns a value, maybe it doesn't.   But it's conditioned on some parameter, such that  when you hit some conditional at some point in   time, you can actually stop recursing, some base  case, right. And we consider this piece the base   case, this is the stopping condition, such that  we no longer grow the number of recursive calls

that we're storing in memory. And this piece down  here, this is the recursive call. This is where I,   you know, I do some unit of work, some small sub  problem that inches me or progresses me closer   to the goal or question I'm trying to  answer. Before we dive into the technical   intricacies of recursion, it's important  that we discuss some of the trade offs.   Why would we want to use recursion? And  why would we want to avoid recursion. And I think there are valid examples for both.  And it really comes down to the situation.

The first pro that I'll give is that it really  bridges the gap between elegance and complexity,   we will look at a variety of different  problems where we're traversing   complex data structures like trees and graphs.  And it really boils down to three or four lines of   code. And that is vastly different than doing  something like that, in this kind of imperative   approach, where we're, we're looking at things  with a lot of loops and a lot of variables. And that can get really messy really quickly, with  data structures that are inherently recursive.

Now, on the downside, you know, adding a bunch of   method calls on the call stack incurs some  CPU overhead, right, there is some slowness,   with calling methods in your code compared  to iterating through a loop. And that, again,   is another trade off you need to make it can be a  time or space trade off that you need to consider. Now, I touched on this briefly, but again, like  recursion can reduce the need for complex loops,   and auxiliary data structures. recursion has  this sort of implicit stack, which is a data   structure commonly used in a lot of algorithms.  And so having that sort of implicit stack and   kind of self manage looping construct, it's  given to you as a part of recursive calls,   you can exploit that property to really simplify  your code and focus on the problem you're solving.

Now, the con for that is as you're  growing the amount of method invocations   in your computer memory, you can actually run out  of memory. And we'll look at a lot of examples as   to why this is, and we'll, we'll start to explore  this, this idea of a Stack Overflow exception. And   this is where we start to run out of  the pre allocated buffer of memory   that we have for our program, which can  actually cause your program to crash. There are a lot of pros when it comes to recursion  when talking about optimization, reducing time   complexity. And that's what this idea of memos  zation, and we'll look at some examples of   memorization and caching, to help speed up  redundant calls. And that's a beautiful property   of recursion. Now, the con again, just like any  piece of code, is that if recursion is overused,   you can get into this sort of habit where  you start to develop really complex code,

if it's not well instructed,  and you want to make sure that   and what we'll get a lot better at this  as we go through this This tutorial   is when you look at problems, you want to  kind of ask yourself, Is this a good use case?   For recursion? Can I really break it down into  subproblems that make sense for recursion?   If you cannot, then you may get into this con  where you have unnecessarily complex code. Now, the final thing, as I had  mentioned before, is recursion   works really well for recursively defined  data structures, JSON objects, trees, graphs,   things that allow you to basically focus on  one tiny unit of the data structure at a time.   And it just so happens we'll look at a bunch of  different examples as to why this holds true. But   this is just a small set of pros and cons, things  to consider when thinking about using recursion.

This brings us to a topic that I think is  often overlooked when teaching recursion,   which I think is one of the fundamental  concepts that you really need to grasp   to understand what people  call quote unquote, magical   about recursion. It's just magic with how  it works. And after we look at this example,   we'll start to realize how logical recursion is  and why it's not necessarily such a magical thing. Let's imagine that you go to work one day, and  the first thing that you want to do is check your   email. And whilst checking your email, you get  interrupted by your boss, and your boss says, Hey,   I need you to go attend some meeting. And  you have to actually deviate from your task.   So you don't finish checking your email, you get  interrupted. And before you can check your email,   now you need to attend this meeting. Now, let's  say your boss, well walk into this meeting,

your boss interrupts you again. And he  says, Hey, our investors are visiting,   I would love for you to go to this board meeting  and impress them with all your knowledge. And   so again, we'll walk into this meeting, you get  interrupted, you have to go impress the investors.   Right, that's your next task. And so before you  can attend the meeting, before you can check   your email, you need to impress these investors.  And finally, your boss, he interrupts you again. And he says, Hey, you know, I'm sorry. But I need  you to go help Jake with his code, his code is   failing. And we need to push to production. So now  you have to basically avoid the investor meeting,   avoid the initial meeting, you can't check your  email until you help j code. Once you help him,   this thing kind of gets popped off your to do  list, you know, you go to the board meeting,   you attend this original meeting. And  then finally, you can check your email.

And you may be asking, like, why is this ever at  all relevant to recursion. And it just so happens   that this sort of idea is exactly how the call  stack works when we're talking about invoking   methods within our programs. Let's take a  look at this simple program here. Notice   we have three method calls. And they're kind of  chained together. The first one returns a string,   but it has a dependency on B, B returns  a string, but it has a dependency on C.

And c just returns a string. So nothing fancy at  all. Now, the call stack is going to be this sort   of abstraction that our operating system leverages  to store method invocations within our program.   It allows us to understand what memory addresses  we return data to, and it stores local variable   information, like what are the parameters  that were passed into me. So if we execute a,   the first thing that goes on to the call stack  is this sort of idea known as a stack frame.

And it basically says, Hey, I want to call  Hello, and I want to concatenate the result of B. But in order for me to concatenate the result of  B, I need to actually now call B. So that pushes B   onto the call stack. Now I'm in the same scenario,  where I want to now return from B, but I have a   dependency on C. So now I call C and put that  on the call stack. And notice this is the same   sort of process that we looked at in the  previous analogy. I cannot return or pop   these things off the stack until I kind of go in  the order in which these things were called. So I returned friends, right. And now friends  replaces that see invocation. And so now   this has been fully evaluated. And so now since  B is fully evaluated, I can return that value   to the B method invocation. And now that  B stack frame gets popped off the stack.

And it's only at this point that I have now  evaluated that entire chain of method calls.   So now I can return this string  value. And get my expected output. Now you may be asking, like why still? Why  is this relevant to recursive thinking.   And let's look at an example. Let's look at a  call stack when we call these recursive calls,   right? This is just a program that  calls itself and it'll execute forever,   right? So the first time I invoke a will now  I need to invoke a, but it calls a again.

And it just keeps happening, right?  There's no stopping condition. And finally,   there's going to be this point, this point  in time where I try and invoke a again, and I get a, I get an error, and  that error is a Stack Overflow.   And this exception happens when we exceed the pre  allocated buffer of memory that our program has.   Right, we basically have run out of  memory, we've exceeded the stack,   and our invocations have overflowed,  and we can no longer handle it. And this is the whole thing with recursion, why  we need a base case, we need to return a value.   So just like we saw previously, for methods  that aren't recursive, we noticed that frames   still grow and grow and grow. And the only  way for those frames to shrink in size   is for them to return some value for them to  stop invoking methods. And the same holds true   with recursion. The only difference is, we have  some sort of base case something that says, hey,

this is the one thing that I want to condition  on to avoid us from further recursing. I want to start off the first technical component  of this presentation looking at recursion with   strings. And this is going to give us a really  good idea of manipulating input parameters on   the call stack recursively. And the first problem  I want to look at is this idea of string reversal.   And so what we do is we have an input string  like the symbol engineer. And the idea is the   output would be the input in the reverse order,  right? And so the question is, how do we how do

we build a really concise recursive function that  gives us something like this. And as we look,   as we look at the skeleton structure for this  code, we of course, are going to have some sort of   input, right? So the input is going to be some  string, and the output is going to be the reverse   version of that. And so we always ask kind of  these two questions. The first is, what is the   base case? And this is really asking, when can I  no longer continue within my algorithm? And the next line of code is going to be all about what's  the smallest amount of work I can contribute?   So in this case, it's going to be basically  between each invocation, what's the small   unit that I can actually modify or manipulate  to progress a little bit closer to the goal?

So let's look at the first question. The first  question is saying, When can I no longer continue? And I think I think when you think about this sort  of scenario, there are two schools of thought. And when I when I like to construct base cases,  I typically think if I were to just pass in a   very small input, like what is the smallest  input that I could just pass in to start   to this function, where I would need to basically  immediately return. And there could be two schools   of thought with this approach, right? And the  two schools of thought could be, well, one letter   reversed is itself, right. And that could be a  really, really good base case for string reversal.

But we want to be even lazier. Like what is the  laziest, like the least amount of work that I   could even consider thinking about. And that would  be the empty string, the empty string reversed,   is again, just the empty string. And so if I  passed in the empty string to this function,   and it would only make sense  to get the empty string back. And so if we, if we modify the code, and we  look at this, we just have a simple base case   where we evaluate if the input string is the empty  string, then let's just return the empty string.

But now we need to consider how do I even  get to that point? What's the smallest amount   of work that I can contribute? Right? And  that's the question that we're asking here.   I need to do something that whittles down the  decision space within each recursive call. And so we kind of asked this question, what's the  smallest unit that I can deal with in a string? A   string is just a bunch of characters, right?  And so maybe I can modify a single character.   And this is where we get to this question. Let  me pick a single character out of this string.   And maybe where I position it will allow it to be  concatenated from the call stack in the reverse   order. And it turns out when we when we write  this code, we get a recursive call where we, we take that first character from the input string  and we concatenate After the recursive call,

and you may be looking at this and you say, Okay,  well, the input parameter has changed. And it's   changed because we've actually shrunken down the  decision space, we've shrunk in that input string,   because our entire goal is to get closer to that  base case, right. And so we've taken everything   directly after the first character to the end.  And the idea is that if we do this enough times, we can shrink our search space on each invocation  and get the goal, which is the reverse string. So this first piece is all is all focused on  shrinking the problem space. And the second piece   is reflecting really the work that we're doing to  contribute closer to the goal. And I think it's   worthwhile to analyze what is happening on the  call stack. So let's say that we pass in Hello.

And we don't hit the base case, on line two, we  immediately go to line six, which is basically   the recursive invocation with the shrunken down  substring. And then we concatenate the H. And just   as we had discussed with call stacks, we can't pop  this off the call stack until that recursive call   has also completed, which adds an  additional stack frame to the call stack. And you notice, again, we don't hit the base  case, and we shrink down that input string,   but we concatenate the first character. And we  keep doing this. And it's nice, because I don't   need to keep track of the H, I don't need to  keep track of the E. It's all self managed for   me in the stack frame on the call stack. And so  I invoke reverse string again. And now I get Oh.

And now watches this gets fairly  interesting, because as I pass in,   oh, I get to a point where my input string has  been whittled down to just the empty string.   And it just so happens that for this use  case, this is the base case. So I return   the empty string. So that reverse  string gets evaluated the empty string   from this base case, and I end up just  returning the empty string plus Oh. And now this recursive call gets evaluated. And  now I add L. And this just becomes o l, right.   And so now I can return this. And  this gets popped off the call stack.

And now you can see that I'm basically returning  these values to the stack frame that preceded me.   And popping things off the call stack.  This function gets evaluated in ADS II.   So I return it and pop this off the call  stack. This function gets evaluated to o Ll E.   So I return it, it gets evaluated. And then  this gets popped off the call stack. And as   you can see, this is the goal, right? This is the  reverse string. And it's the power of the call stack the power of these recursive calls that  allow us to return values back down the stack.   And this is a very good property that  we can exploit when using recursion.

Let's look at palindromes, palindromes are  these unique words, where we can basically   spell the same word forward and backward.  Let's look at this word. The mechanical   way that we kind of analyze if a word is a  palindrome or not, is we look at both ends. And we basically say okay, do these letters match?  Yes, they do. So we shrink in Word, we say do   these letters match? Yes, they do. So we shrink in  Word. And now this is just one character. And it   proves that we've we've matched successfully.  So this indeed would be a palindrome.

Now let's look at a snippet of code to see how we  could think about something like this recursively. Now, obviously, we're going to have a  Boolean function, because it's either Yes,   it's a palindrome or No, it's not. And  we're going to evaluate some input string. And of course, the first thing we always consider  is what is this base case, the thing that stops us   from recursing? Now, think back to what  I had said in the previous example,   I always like to consider my base cases, what  is the smallest input that I could just pass   into this function? And it turns out very  often not very often, for string recursion,   you can typically whittle down your search space  and evaluate the input length. So if you passed

in a palindrome that was of size zero, then  that's a palindrome, right? Because there's   there's nothing that proves it's not a palindrome.  There are no characters to compare against.   And in the same vein, if we pass in just a single  character, with a single character, both forward   and backward is the same character. So that's also  a palindrome. So these are really good use cases,   or base cases to evaluate this conditional,  which is whether or not a string is a palindrome. But let's continue we need to  consider the small amount of work   that we can do. And in the animation that we just  looked at, you notice that we had two pointers,   one on the left and one on the right, and we  were comparing those strings, those characters,   we're saying they need to be the same. If they're  not the same at any point in time, then we've   violated the property of a palindrome. And if we  violate the property of palindrome, then we just

go to this false. This is kind of this fallback  base case. So at any point in the algorithm, if   the characters don't match up at their respective  opposite indices, then we can terminate,   we return false and the false gets propagated  through the call stack. And the initial color   function would return the false. But if that's not  the case, then we get to this interesting thing,   where we call this recursive call, and it whittles  down or sub our substring. So let's look at the call stack to understand what's happening. We  pass in race car as an input string. And this   of course, is a palindrome you can see race  car forward and backwards, it's just race car.

And the first thing we do is we evaluate  this, this conditional this base case,   is the length zero or one? Well, it's definitely  not. So we continue. And now we compare the   first character and the last character for  this input string. And if they're equal,   then we just call ourselves again,  but we shrink that input string.   And since these since R and R are equal, we  add another stack frame to the call stack. And we've shrunken down our input string,  we again, look at the base case, we don't   satisfy it. So we compare the first and the last  character. And we notice in this in this case,   they're also equal. So we call ourselves again,  right, and we don't pop the stack frame off the   call stack, because we still have more work  to do. And so we shrink down our input string, we still haven't satisfied the  base case. And our characters   at the first and last position are still the  same. So we do just a little bit more work.

And now we're at the last character. And  we've already come to this conclusion that   if the input length is zero or  one, then we just return true.   So for this one particular subproblem, this one  particular element, this is indeed a palindrome.   So what do we do, we say, yes, this was a  palindrome and we pop it off the call stack. And since we return true, and all of these other  conditionals have been satisfied, that we can just   propagate through the true Boolean down the call  stack. So we return true here and pop this off.

We go to the next stack frame and return  true here and pop this off. And now we   get to the final stack frame, which evaluates  to true. And this gets popped off the stack. Now I want to look at recursion with numbers.  And the thing that you'll start to realize as   we go through these sorts of problems, is that  the same blueprint holds true for all of them. And the first problem I want to look  at is this idea of converting decimal   base 10 values to binary, which is a base two  number format, ones and zeros. So the question is,   how can we convert a number like  25 into its binary counterpart.

And it turns out, there's a very mechanical way  of doing this. So let's take the number 233.   And the formula here, as we'll come to find  is we can do a division by two and this is   basically doing the floor operator. So it gets  us an integer instead of a floating point value.   And we get we get an output, which is 116. And  we have a remainder, and that remainder is one. And the mechanical process that we can  follow to convert decimal to binary is   we take the results of this operation,  which is 116. And we divide that by two.

And we just keep evaluating, and this is 58,  remainder zero, and then we take 58. And we   divide that by two, and this is 29, remainder  zero. And we basically just keep taking the   result in the output and dividing it by two. And  notice we're keeping track of the remainders here. And the interesting property by doing these  operations gets us to a point where we can   take all of these remainders. So notice, we've  gotten to this base case, which is zero. And that   kind of halts this progression. So now we're  done. And if we take all of these remainders,   in the order that they were basically pushed onto  the stack, we can evaluate them and this is the   result in binary string for 233. And the question  is, how can we Okay, this this mechanical process, you know, very formulaic? How can we  convert it into some recursive operation?

Let's take a look at some of this code. Now,  notice, we said the first thing is we took 233   divided by two, we got some output The remainder  was one. And so there are actually many ways   of doing this problem. And we're going to keep  it really simple. So notice we're dealing with   strings. As the result outputs, we're going  to be concatenating strings basically. And so what we consider here is we we think  about that base case, right? If I hit zero,   then there's no longer reason for me to  divide further, right, I return my result.

Now, if I have not hit zero yet, it means that I  still have more division to do. And so the first   thing that we do is we get that remainder. So  when we look at 233, divided by two, we want to   store that remainder because that represents  one of the binary digits that we care about,   basically tells us if the value is  even or odd. And this is the binary,   this is the remainder that will contribute to  the result. And so that's why we store this in the result. And notice, we just prepend this  to the result. And now what I do is I again, just   call find binary and I shrink my problem space  by half. And I just propagate the result through.

Now let's let's actually look at the call  stack. By coding this. And seeing what it   looks like I want to take the code that we  were just looking at, but look at it from   the perspective of the call stack and understand  how these stack frames are building up over time. Now, there are many ways to code this fine binary  function. And a lot of people do it returning an   integer. And that's completely fine. And if you  want to do it that way, you can actually follow   along with any modification of this and analyze  the call stack with me. So as we run in debug,   the call stack is going to show up down here. So  these are all the stack frames that we can watch   grow. And the variables on the current stack  frame will show up under here in local. And so as we dive into this function, you notice that  this is the first stack frame for find binary.

And in order for this to complete,  we need to return some value. We haven't hit our base case yet. So we jump into  our work. And we just make another recursive call.   So the first stack frame can't pop off yet,  because we're going to invoke ourselves again.   And once we do that, you notice  that we add another stack frame. And also notice that the input parameters have  changed. We've shrunken down our decision space,   and we've appended the first digit to our binary  result. We haven't hit our base case yet. And we   continue. And again, we do a recursive operation.  And our decision space keeps shrinking. And this   is the same mechanical process that we saw in the  animation, we divide by two and log the remainder, we divide by two and log the remainder. And we  do this until we hit some sort of base condition.   Right. And as we shrink down our problem  space, notice we get to this point where   the decimal is one. And that still is  not our base case. So we go through,

we get the result. And this binary string  is looking pretty good. In on the final   recursive call, you notice the decimal is  now zero. And this is a really good case now,   because now we can just return. So we  come in here and we return this value. And this value comes in and says okay, find binary  for that invocation returned this result. And so   now we're just saying, okay, continue. And notice  as I step through, the stack frames have grown.   But now they should shrink off the call stack. So  I step through. And notice they've all shrunken   down, so all of them have returned, they've all  returned a value. And now once I step over here, we noticed that the binary  value has been evaluated,   you can come into this debug  console and look at it.

And this is the resulting binary string. And so  it's good to look at how the call stack is working   to understand. Okay, how many stack frames do we  build up to get to our result? And how do they   unravel once we hit our base case here, we've just  straight up propagated the result down through   all of the stack frames, and all of them just  return the same thing. And we'll look at a lot of different examples where all the stack frames kind  of work together. And they wait for the result to   do a little bit more work. And so there's a lot  of different versions of this. The next problem   that I want to look at with numbers is the sum of  natural numbers. And the idea of this problem is   you take an input number like 10, and then you sum  all the values up to 10. And what we do here is we actually just add them all up, and we get some  output and the output in this case would be 55.

And the question is how can we build some  succinct function that Does this recursively Now let's look at a little snippet of code and try  to understand what's happening behind the scenes. So recursive summation, again, we take in an input  value. And the first question we need to ask is,   what is the smallest input value that I could  pass in. So if I pass in one, for example,   the sum of one to one is just itself. One,  right. And so that's a good, that's a good place   for the base case. And again, keep in mind, we  are simplifying these functions. So you know,   edge cases, we're not really focused on that.  Right, now we're focused on the core goal,

which is building a succinct function. So  if I pass in one, I would return one. Now,   if I pass in a larger number, like 55, I still  have a lot of work to do, I need to add up   all the proceeding numbers up to 55 from one. And  so what I can do is I can take whatever value I am   currently. And I can add it to myself again,  but subtracting one from that numbers, right.   So it shrinks me closer to this base case. Let's  again, look at some code and understand how the call stack is working with this sort of code. So  I've taken the same code from the slide. And now   we want to look at the call stack and understand  what's happening as we make these recursive calls.

The first thing that we'll look at is the number  five, so we want to add all values from one to   five. Let's put a breakpoint here and debug into  the call stack. So as I dive into this operation,   we first evaluate the base case, which hasn't  been hit yet. And so now what I want to do is   I want to take five, and I want to add it to  another recursive call, but that recursion   is shrinking down the input space again. And  so as I dive in, notice this input number change. So I make the recursive call, and  the input number has shrunken down to four,   and another stack frame has been added to the  call stack. And so we keep evaluating has the   conditional been hit? No, it has not. So I  come in here and it shrinks down to three.

And I keep doing this, and I come in here. I  come in here. And now the input number is one has the base case been hit yet? Yes, it has. And  so if I dive into this, you notice that we return   one here. And this one returns this  value to the stack frame right below it. And so notice that as I continue, that stack  frame gets popped off. And you can see that the   invocation of this method returned one here. And  so now what I'm doing is I'm taking two plus one, and I'm returning this value and  this value is going to continuously   unravel through these stack frames. So  notice, all of these get popped off.   And here's the final invocation, the input  number is 10 here. And as we continue, this is evaluating for recursive summation of 10.

And so now again, for 10, we get down to a base  case. And that base case is one. And if we look,   so I'll put a breakpoint here. And we continue, we  can see that we have the results of 15 and 55. And   these get printed out. And so again, this is just  an example to show as we're looking at the stack   frames, how a stack frame can return a value to  its previous stack frame to finish the operation. And that's the key here for recursion. And we'll  keep doing this for a lot of the problems that   we look at to get familiarized with how the call  stack is working, and how the stack frames grow.

I want to talk about divide and conquer  algorithms, which are really great demonstrations   of recursion. And the blueprint that we think  about for dividing conquer holds through so   we you know, still divide a large  problem into several small problems. But divide and conquer is all about we divide  them into subproblems. We independently solve   them. And then we actually merge the  results to solve some holistic problem,   right? We merge them together and say, Hey,  this is the solution. And they are typically   recursive. And let's look at the first one,  which is binary search. And the entire purpose   of binary search is we look at a sorted list of  numbers. And the key point here is they're sorted.

And let's call this array. And the first  thing that we say is we say alright,   I'm going to start with the left and right  index, so the far left index is zero and the   far right index is the length of the array minus  one. And the whole purpose of binary search is to   find a value we want to find a value in this  array. So we know that zero is less than the   length of the array. So we can Have not hit  our base case and we calculate the midpoint. So the midpoint is the left and right index added  together and divided by two. And so we check, we   say, okay, is that midpoint? The answer that we're  looking for? So that's another sort of base case,   have we hit or found the number 10? Here? And the  answer is no. So we ask one of two questions, the   first question that we ask is, is the number that  we're looking for on the left half of the array,   or is the number that we're looking  for on the right half of the array.

And remember, we just found the midpoint, so  we're considering everything to the left and   the midpoint and everything to the right of the  midpoint because the input data is sorted. Now,   if it's on the left half, which is what we're  looking at here, then we completely discard   the right half. And notice, the way that we do  that is we change the bounds of the problem.   So the left half stays the same. So our  starting point on the left stays the same, but we only consider up to the midpoint minus one.  And so that is our ability to shrink our decision   space and completely discard the right half in  each recursion, or each recursive invocation.

Now, if we get to this other evaluation, this  is basically saying the value we're looking for   is on the right half. And what this allows us to  do is we only consider our starting point to be   the midpoint plus one all the way to the  end. So we completely discard the left half   for the rest of this problem. And  this indeed, is also a recursive call.   So look at the first stack frame in the  call stack to the right, we start with zero, our upper bound index for the right variable is  nine. And the number we're searching for is 10.

So here's our midpoint, this is  three. And we asked this question,   Is this the value that we're looking for?  Is this 10? And the answer is no, it's not. So what we can do is we can discard the  entire left half of the search space because   10 is greater than the midpoint. And it turns out,  we add another stack frame to the call stack and   notice how the parameters have changed. Now for  the left, the starting bound, which is the left   is five, which is the index where four is,  and the upper bound is nine, which is the   original length of the array that we're working  with. And again, we calculate the midpoint,

the midpoint on this sub array is nine, and we  say is 10, greater than nine or less than nine.   And of course, we know 10 is greater than nine.  And so what we can do is completely discard   the left half of that sub array and continue. And  we add another stack frame. And the stack frame,   the start bound is eight in the upper bound is  nine. And we again, recalculate the midpoint. And the midpoint at this point actually turns  out on line seven, we've hit this base case,   the base case here is that we've found  the number that we're looking for. And   this is the solution. And so what  we can do is just return this value.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent