Transcript
Use with ChatGPT / Claude Auto-scroll A
the following content is provided under a Creative Commons license your support will help MIT open courseware continue to offer highquality educational resources for free to make a donation or view additional materials from hundreds of MIT courses visit MITopencourseware at
ocw.mit.edu last time we started talking about complexity and I want to quickly remind you what we're doing because we're going to talk some more about that today and when I say complexity it was the question of can weestimate the amount of resources typically time that we're going to need to get an algorithm to solve a problem of a particular size and we talked about that both in terms of estimating how much time is it goingto take and using it to go the other direction and think about how design choices in an algorithm have implications for the cost it's going to be associated with that so we introduced the idea of uh what wecalled Big O notation orders of growth a way of measuring complexity and we started talking about different classes of algorithms so today I'm going to quickly recap those basic ideas and what we're going to do is we're going
to see examples of standard classes of algorithms with the idea that you're going to want to begin to recognize when an algorithm is in that class so very quick recap I've already said part of this we want tohave a mechanism a method for being able to estimate or Reason about how much time do we think an algorithm is going to take to solve a problem of a particular size and especially as we increase the sizeof the input to the algorithm what does that do in terms of the increase in the amount of time that we need some ways we don't care about exact versions in a second we're going to see the definitionof this but what we care about is that notion of how does it grow as we increase the problem size and while we're going to focus in going if you like in the forward direction as I said a
lot of the interest is actually thinking about what you might think of as the backwards or reverse Direction how does a choice in algorithm design impact efficiency of the algorithm and really what we want you to do isto begin to recognize standard patterns that if you make a particular choice this fits in a class of algorithms you've seen before and I know in essence how much time what the cost is going to be as Ido that all right so just a recap as it says on the top we talked about orders of growth the idea is we want to be able to evaluate programs efficiency when the input is very big we talkedabout timing things just with a timer we suggested that unfortunately conflates the algorithm with the implementation with the particular machine we want to get rid of those latter two and just focus on the algorithm so we're going to
talk about counting operations but in a very general sense so we're going to express what we call the growth of the program's runtime as the input size grows very large and because we're only interested not in the exactnumber but in if you like the growth of that we're going to focus on putting an upper bound on the growth an expression that grows at least as fast as what the cost of the algorithm is now youcould just cheat and pick a really big upper bound that doesn't help us very much so in general we're going to try and use as tight and upper bound as we can what's the class of algorithm it fallsin but as we've seen before we care about the order of growth not being exact so something grows as 2 to the N plus 5n I don't care about the 5n because when n gets big that 2 to
the end is the really big factor and therefore we're going to look at the largest factors when we think about that seen some examples we're going to do a bunch more examples today to fill those in and oneof the things that we want to now do is say with that IDE IDE in mind there are classes of complexity of algorithms so some sense the best ones are way up here o of one order one constantit says cost doesn't change as I changed the size of the input it's great it's always going to be the same cost order log n says the cost grows logarithmically with the size of the input it's a slowgrowth and I'm going to remind you that in a second we saw lots of examples of linear running time we're going to see a few more today what we call log linear polom and exponential and the thing I
want to remind you is that ideally oops sorry we'd like our algorithms to be as close to the top of this categorization as we can this is actually described in increasing order of complexity something that takes the sameamount of time no matter how big the input is unless that amount of time is a couple of centuries seems like a really good algorithm to have something that grows linearly is not bad something that grows as we'veseen down here exponentially tends to say this is going to be painful and in fact you can see that graphically I'm just remind you here something this constant says if I draw out the amount of time it takesas a function of the size of the input it doesn't change logarithmic glows sorry grows very slowly linear will grow obviously in a linear way and I actually misspoke last time I know it's rare for a professor to
ever admit they misspeak but I did because I said linear is if you double the size of the input it's going to double the amount of time it takes actually that's an incorrect statement really what I should havesaid was the increment if I go from say 10 to 100 the increase in in time is going to be the same as the increment if I go from 100 to a th000 might be more than double dependingon what the constant is but that growth is linear if you want to think of it take the derivative of time with respect to input size it's just going to be a constant it's not going to change withinand of course when we get down to here things like exponential it grows really fast and just as a last recap again I want to be towards the top of that there was my little chart just showing you
things that grow constant log linear log linear quadratic and exponential if I go from n of 10 to 100 to a th to a million you see why I want to be at the top of that chart somethingup here that grows logi rically the amount of time grows very slowly as I increase the input down here well like it says good luck it's going to grow up really quickly as I as I move up inthat scale I want to be at the top of this chart if I can okay with that in mind what I'm going to do today is show you examples filling in most of this chart we've already seen someexamples we've seen examples of linear we've seen examples of quadratic I'm going to just remind you this what I want to do is show you how you can begin to recognize the choice of an algorithm in terms of
where it lies so algorithms that are constant complexity they're kind of boring they tend to be pretty simple because this says this code is going to run in the basically the same amount of time independent of the sizeof the input now notice the bottom thing here it doesn't say you can't you that try again it doesn't say you couldn't have a loop or a recursive call you could it's just that that Loop cannot depend onthe size of the input so there aren't many interesting algorithms here we're going to see pieces of code that fit into this when we do our analysis but something that's constant complexity says independent of the size of theinput right a little more interesting not a little a lot more interesting are algorithms that are logarithmic in their complexity says they're going to grow with the logarithm of the size of the input you saw an example much
earlier in the term when Anna showed you bsection search was searching for a number with a particular property I want to show you another example both to let you recognize the form of the algorithm but especially to showyou how we can reason about the growth and that's another trick called binary search or again it's a version of bsection search suppose I give you a list list of numbers integers and I want to know if aparticular element is in that list we saw last time you could just walk down the list just iterate through the entire list looking to see if it's there in the worst case which is what we worry about it'sgoing to be linear you're going to have to look at every element to the in the list till you get to the end so complexity was linear in that case and then we said suppose we know that the
list is sorted it's ordered from smallest to largest and we saw simple algorithm says again walk down the list checking to see if it's there but when you get to an element that's bigger than the thing you're lookingat you can just stop there's no reason to look at the rest of of the list they've all got to be bigger than the thing you're searching for practically in the average case that's going to be faster thanjust looking at an unsorted list but the complexity is still linear because in the worst case I've got to go all the way through the list before I do the thing is not there okay so even sequential searchin an ordered list is still linear can we do better and the answer is sure so here's how we do better I'm going to take that list I'm going to assume it's sorted and I'm going to pick an
index that divides the list in half just pick the midpoint in the list and I'm going to check that value I'm when I ask is the element in the list at that point the thing I'm looking for ifit is great I'm done if I'm not that lucky I'm then going to ask is it larger or smaller than the thing I'm looking for and based on that I'm either going to search the front half or theback half of the list oh that's nice okay because if you think about it in something that was just a linear algorithm at each step I reduced the size of the problem by one I went from a problemof size n to a problem of size n minus one to a problem of size n minus 2 here I'm taking a problem of size n I'm reducing it to n/2 in one step because I can throw half
the list away so this is a version of divide and conquer things we've seen before I'm breaking it down into smaller versions of the problem so let's look at that and then we let's write some code and thenlet's analyze it so suppose I have a list of size n right there are n elements in there I'm going to look at the middle one say is it the thing I'm looking for if it's not is itbigger than or less than the thing I'm looking for and in this case let's assume that in fact the thing I'm looking for is smaller than that element great I'm going to throw away half the list now Ionly have to look at the lower half of the list I'll do do the same thing I'll look at the element in the middle here and I'll say is it the thing I'm looking for if not is it
bigger than or smaller than the thing I'm looking for okay I'm down to n over two elements after I do that I throw away half the list again in this case I'm assuming that the thing I'm looking foris bigger than that middle point until I find that at each step I'm looking at the middle element and I'm either throwing away the left half or the right half of that list so after I step I'm downto a list of size n/ 2 to the I now what's the worst case the worst case is the elements not in the list I'm going to have to keep doing this until I get down to just alist of one element and at that point if I notot the thing I'm looking for I know I'm done and I can stop different pattern notice how I'm cutting down the size of the problem by two so I
can ask before we look at the code what's the complexity of this how many steps do I have to go through in the worst case and I know I'm going to be done looking at the list when n/ 2 to the I is equal to one meaning there's only one element left that I'm still looking at and I can solve that it says I'm going to have to take at most I equal to log nsteps right so logarithmically I'm cutting this down and so the complexity of the recursion we haven't talked about the code yet but in terms of the number of steps I have to do in the worst case is justlogarithm in the length of the list that's nice it's a lot better than looking at everything inside the list and in fact you can see it right I don't look at everything inside the list here I'm throwing half
of things away at a time okay so let's look at some code to do that bsection search I'm going to give it a list of numbers I'm going to give it something I'm looking for we can walk throughthis code hopefully it's something that you're going to be able to recognize pretty clearly says if the list is empty there's nothing there thing I'm looking for can't be there I return false if there's exactly one element inthe list then I just check it if that thing's the thing I'm looking for return true otherwise return false I'm just going to return the value there otherwise find the midpoint notice the integer division here find the midpointin that list and check it in particular say if the thing at the midpoint is bigger than the thing I'm looking for then I'm going to return a recursive call to this function only looking at the first half
of the list I'm just slicing into it otherwise I'll do the same thing on the second half of the list nice this is implementing exactly what I said we could actually try it I'll do that in a secondif I remember but let's think about complexity here that's constant right doesn't depend on the size of the list that's constant doesn't depend on the size of the list that's constant sounds good what about that well it lookslike it should be constant right other than the number of times I have to go through here remember I know I'm going to have order login recursive calls I'm looking at what's the cost to set it up itlooks like it should be constant so does that but I'm going to claim it's not anybody see why it's not you can look at the slides you've already printed out right there I'm actually copying the list right when
I slice into the list like that it makes a copy of the list oh crud I was about to say something different but I won't because this is going to cost me a little bit as I think aboutthe work so let's look at that a little more carefully I've got order login search calls we just deduced that I've just repeated it here right on each call I'm reducing the size of the list in half soit goes from n to n over2 to n over4 to n over 8 to n over 16 I'll be done in the worst case when I get down to having only a list of size one that takes logn steps because n/2 to the log n is n / n which is one but to set up the search for each cell I've got to copy the list and the list starts out n long so in principle
I've got order and work to do to set up the recursive call and so by the things we saw last time I've got order log in for the number of recursive calls Times order and work inside of eachcall and that's order n log in so it's not what I wanted now if you're thinking about this carefully you'll realize on each step I'm not actually copying the whole list I'm copying half the list and then aquarter of the list and then an eighth of the list so if I was actually really careful I'm not going to do the math here in fact what we'll see and if you like you in your copious sparetime you can go off and work this through what you'll discover is that you're actually doing order and work to do the copying but that's still a problem because then I got something that's order n plus log n
and the N is going to dominate so this is still linear sounds like I led you down a primrose path here can we fix this sure because we could do the following we could say when I want tolook at that list do I need to copy everything what about if instead I said here's the beginning and the end of the list when I test the middle I'll move one of the pointers to the middle ofthe list when I test the middle again I'll move another pointer in so in other words I can test the middle and based on that I could say I only need to search this part of the list justkeep track of that point and that point in the list and when I test the middle again same idea now I'm not actually copying the list I am simply keeping track of where are the pieces of the list
that bound my search ha right I'm still reducing the size of the problem by factor of two at each step that's great all I need to do now though is just keep track of which portion of the listI'm searching I'm going to avoid copying the list so the number of recursive calls a game will be logarithmic let's see if that actually fixes my problem a little bit of code not as bad as it looks I'vegot an internal function here then I'm going to come back to but let's look at what happens in this case I'm going to say again if there's nothing in the list just return false element can't possibly be thereotherwise call this function with the list the element for whom I'm searching and the beginning and end of the list so zero at one end length of n l minus one at the other end it's just that idea
of I'm keeping track of the two pieces okay now let's look at what this does says here's the low part of the list the high part of the list initially it's zero and length of list minus one itsays if they are the same oh cool then I've got a list of length one just test to see if it's the thing I'm looking for if they're not find the midpoint and the midpoint is just the averageof low plus High integer division by two think about it if it's zero and N midpoint is n /2 but if it's for example n two and N midpoint is 3/4 n so that mid picks the middle pointif it's the thing I'm looking for great I'm done otherwise check to see is the thing at the middle bigger than or less than the thing I'm looking for and based on that I'm going to skip this one
for a second I'm either going to search everything from the low point up to the middle point or from the Middle Point up to the high point and the last piece here is if in fact the low pointand the Middle Point are the same I got a list to size one there's nothing left to do I'm done okay I know it's a lot of code I would invite you just to walk through it but Iwant to take you back again to just simply this point and say Here's what we're doing we're starting off with pointers at the beginning and end of the list we're testing the Middle Point on based on that we'retake call giving a call where now the pointer is to the beginning and the middle of the list simply passing it down and same as I go through all of these pieces so that code now gives me what
I'd like because here in the previous case I had a cost the cost was to copy the list in this case it's constant because what am I doing I'm passing in three values and what does it take tocompute those values it's a constant amount of work because I'm Simply Computing mid right there just with an arithmetic operation and that means order log n steps because I keep reducing the problem in half and the cost ateach point is constant and this is as a consequence a really nice example of a logarithmic complexity function now if you think about it I'm cheating slightly second time today because we said we really don't care about theimplementation we want to get a sense of the complexity of the algorithm and that's generally true but here is a place in which the implementation actually has an impact on that complexity and I want to be conscious of
that as I make these decisions but again logarithmic in terms of number of steps constant work for each step because I'm just passing in values and as a consequence the over algorithm is log notice one other thing Isaid I want you to see characteristics of algorithms that tell you something about the complexity of that algorithm something that's iterative and reduces the problem by size one each time from n to n minus1 to n minus 2linear something that reduces the size of the problem in half or in thirds or in quarters each time logarithmic generally unless I've got a hidden cost somewhere here's another little example just to give you sense of log Iwant to convert an integer to a string I know I can just call Str STR on it but how we do that inside of the machine well here's a nice little algorithm for it I'm going to set up
something I call digits it's just a string of all the digits if the thing I'm trying to convert is zero I just return the string zero otherwise let's run through a little Loop where I take that integer dividedby 10 the remainder of that what is that oh that's the zeroth or the one order the first order bit and I'm going to index into digits to find that and I'm going to add it on to astring that I'm doing and I'll divide I by 10 so this has given an integer I want to convert it to a string I divide the integer by 10 take the remainder that gives me the zero or theif you like the ones element I index into the string and I record it and then I add it to what I get by dividing I by 10 and doing the same thing so I'll just walk down each
of the digits converting it into a stringwhat I care about is the order of growth here this is all constant all I want to worry about here is how many times do I go through the loop and inside of the loop this is just constantit doesn't depend on the size of the integer so how many times do I go through the loop well how many times can I divide I by 10 and that's log of I right so it's not I itselfit's not the size of the in integer it's the number of digits in the integer and here's another nice example of log I'll point you again right here I'm reducing the size of the problem by a constant factorin this case by 10 each time nice characteristic of a logarithmic algorithm okay we got constant we've got log what about linear we saw it last time right something like searching a list in sequence was an example of
something that was linear in fact most of the examples we saw last time were things with iterative loops so for example fact written iteratively factorial right n * n-1 * n-2 all the way down to one I setproduct to one I go for a loop where I goes from one up to n minus one or just below n minus one incrementally multiplying product by I and restoring that back away again we know that this Loophere how many how many times do I go through it I go through it n times the cost inside the loop they're three steps changing I I'm multiplying product time I I'm storing that value back in product andas we saw that constant doesn't matter this is linear so n times around the loop constant costs each time order n what about recursive I could write fact recursively I actually prefer it this way right 's less than
or equal to one return one otherwise multiply n by whatever I get by calling this on N minus one the cost inside the loop is just constant I'm doing one subtraction one a multiplication how many times do Igo through it again n times because I got to go from n to n minus1 to n minus 2 so again this is linear now if you were to time it you'd probably see a difference my guess isI'm sure Professor G will correct me if I get it wrong is that the factorial one probably takes a a little more time because you got to set up the frame for the recursive call but in terms ofwhat we care about they're the same they're both linear they're order in and so interestingly both iterative and recursive factorial have same order of growth again I want you to notice what's the key here reducing the size of
the problem by one is indicative generally of something that's going to have linear growth I say in general if it's a loop inside of a loop as we saw it might be a little bigger but this is generallylinear constant log linear log linear that is n log n we're going to see this next time I'm simply going to push it ahead which invites you to come back on Wednesday and see this it's actually something that'sa really powerful algorithm it's going to be really useful we're going to look at something called merge sort which is a very common sorting algorithm and has that property being log linear so we'll come back to this nexttime how about polinomial well we saw this last time as well this commonly occurs when we have nested Loops or where we have nested recursive function calls nested Loop meaning I'm looping over some variable and inside of there
I've got another loop and what we saw is the outer loop if it's a standard iterative thing will be linear but inside of the loop I'm doing a linear amount of work each time so it becomes n *n so order n^ 2 okay exponential these are things sorry yes I did that right I'm going to go back to it exponential these are things that we'd like to stay away from but sometimes we can't and acommon characteristic here is when we've got a recursive function where there's more than one recursive call inside the problem remember towers of Hanoi that wonderful demonstration I did I was tempted to bring it back because it's always funto get a little bit of Applause when I do it but I won't do it this time but remember we looked at that problem of solving the towers of Hano how do I move a stack of sizen of
differ Siz discs from one peg to another where I can only move the top disc onto another one I can't cover up a smaller disc want to remind you we saw there was a wonderful recursive solution to thatit said move a stack of size n minus one onto the spare Peg move the bottom one and then move that stack over onto the thing were headed towards okay what's the complexity of that well I'm going toshow you a trick for figuring that out it's called a recurrence relation for a very deliberate reason but it'll give us a little handy way to think about what's the order of growth here so I'm going to letT subn denote the time it takes to move a tower of size n and I want to get an expression for how much time is that going to take what do I know I know that's 2 * T
the n - one right I got to move a stack of size one less onto the spare Peg and then one to move that bottom thing over and then whatever it takes me to move a stack of sizen minus one over to that Peg okay so how does that help me well let's play the same game what's T of n minus one oh that's 2 T of n minus 2 + one just substituting in I'musing exactly the same relationship here here all right let's just do a little math on that that's 4 T nus 2 + 2 + 1 and you're still going okay who cares well let's do the same thing onemore time T of n minus 2 that's 2 T of n minus 3 + one oh see the pattern you can start to see it emerge here right each time I reduce this I'm adding another Power of Two
And I'm increasing the coefficient out front and so in fact after K steps I'll have 1 + 2 + 4 all the way up to 2 the K minus 1 plus 2 K * T subn minus K hopefullyyou can see it if you just look this expression is capturing all of those up there I'm just pulling it out each time when am I done when this is size zero when K is equal to n andso that's when I get that expressionif this is going by too fast just walk it through yourself later on but I'm literally just using this expression to do the reduction until I see the pattern right what's that well if you're a course 18 majoryou've seen it before if you haven't here's a nice little trick let me let a equal that sum 2 the n- 1 plus 2 the N minus 2 all the way down to one let me multiply both the
left and the right side by two that gives me 2 a is equal to 2 the n + 2 the N - 1 all the way down to two I'm just taking each of the terms multiplying them bytwo now subtract this from that and on the left side you get a and on the right side you get that term these all cancel out minus one geometric series cool so that sum is just 2 to theN minus one and if I plug that back in there ah I've got my order growth exponential two to the end okay I was a math physics undergr I like these kinds of things but I wanted you tosee how we can reason through it because this is letting us see the growth what I want you to pull away from this is notice the characteristic in towers of Hanoi we're going to do another example in a
second the characteristic was at the recursive step I had not one but two recursive calls and that is characteris istic of something with exponential growth which I just saw here two to the end that by the way I'llremind you the story of towers have towers of Hanoi right when the priests in that Temple mve the entire stack from one peg to another we all reach nirvana and and and the world ends n is equal to64 here go figure out what two to the 64 is and if you're doing one move per second which they will I think we're certainly going to be here a while before the the universe ends and we reachnirvana probably several times over we are in newv we're at MIT you're right John but we're worrying about the rest of the world so okay we'll keep moving on Nirvana will be next week when they do the quiz
John so we'll keep moving quickly all right I want to show you one more example it's a cool problem for math but mostly to see that characteristic of exponential growth and then we're going to pull all of thistogether this is something called the power set so if I have a set of of things but let's assume I have a set of integers with no repeats so 1 through n 1 2 3 4 for example Iwant to generate the collection of all possible subsets so subset with no elements with one element with two elements with three elements all the way up to n elements so for example if my set is 1 through 4then the power set would be the empty set with no elements in it all of the instances with one element all of them with two all of them with three and all of them with four I'd like to
write code to generate this it's actually a handy problem in number Theory or in set theory by the way the order doesn't matter I could do it this way but this would be a perfectly reasonable way of generatingit as well and I'm going to come back to that in a second as we think about solving this the question is how would I go about finding all of these I'm going to use well we could stopand say you can imagine writing a big itive Loop you start with n and you decide do I include it or not and then you to go to n minus one do I include it or not and youcould think about writing a big loop that would generate all of these actually a bunch of nested Loops but there's a nice recursive solution and I want to encourage you to think that ways so here's the way I'm
going to do it what do we do when we said we want to think recursively we say let's assume we can solve a smaller size problem if I want to generate the power set of all the integers from1 to n I'm going to assume that I can generate the power set of integers from 1 to n minus1 if I have that solution then I can construct the solution to the bigger problem really easily wow wellall of the things that were in that solution to the smaller problem have to be part of the solution to the bigger problem they're all subsets of 1 to n because they're all subsets of 1 to n minusone so I'm going to add all those in and then I'm going to say let's take each one of those and add n to each of those subsets because that gives me all the rest of the solutions I've
got all the ways to to find Solutions without N I get all the ways to find Solutions with n that may sound like a lot of gobble to Google let me show you the example there is the powerset of the empty set it's just the empty set to get the power set of one I include that and I include a version of everything there with one added to it there's the power set of one nowgiven that how do I get the power set of two well both of those are certainly things I want and for each one of them let me just add two and if you look at that right that's theset of all ways of getting nothing one two or both of them and you get the idea now having that solution I can get the solution for three because all of those have to belong and I simply add
three to each one of those oh that's cool right all right you don't have to be a math geek to admit it's cool it is kind of cool because it says GE got a solution to the Sal smallerproblem generating the next piece is a natural step you can also see the size of that sets doubling each time because to get to four I'm going to add everything into all of those pieces really nice recursive descriptionlet's write some code so I also hand that out to you but here's the coat and I'm going to walk through it carefully and then we're going to analyze it but it's actually for me a beautiful piece ofcoat I did not write it by the way John did but it's a beautiful piece of code I want to generate all the subsets to the power set of some list of elements here's how I'm going to do
it I'm going to set up some internal variable called res okay and then what am I going to do actually I don't know why I put res in there I don't need it but we'll come back to thatif the list is empty length of the list is zero I'm going to just return that solution and this is not a typo what is that funky thing there it is a list of one element which is theempty list which I need because the solution in this case is a set with nothing in it so there is the thing I return in the base case otherwise what do I do I take all the elements ofthe list except the last one and I call it recursively I generate all of the subsets of that perfect I'm going to call that smaller I then take the last element and I make a list of just the
last element and what did I say I need to do I need all of these guys plus I need all of them where I add that element in oh nice I'll set up new as a variable here andI'll Loop over all of the elements from the smaller problem where I basically add that list to that list and I put it into new that's simply taking all of the solutions of subsets of up to n minusone and creating a new set of subsets where n is included in every one of them and now I take this and I take that I pen them or concatenate them rather shouldn't say pen them concatenate them togetherand return it that's a crisp piece of code and I'm sorry John I have no idea where I put resz up there I don't think I need that anywhere in this code I won't blame it on John it
was my recopying of the code sorry maybe right look I know I'm flaming at you I get to do it I'm tenur as I've said multiple times in this course that's a cool piece of code imagine trying towrite it with a bunch of Loops iterating over IND Seas good luck you can do it maybe beyond the is actually no it won't that's way too hard to ask but it's a cool piece of code because Ican look at it and say what's the solution solve the smaller problem and then given that take every one of the things in that smaller problem add that element into it and put the two pieces together wonderful okaywith that in mind let's see if we can figure out the complexity of this up here that's constant that's okay right there I've got the recursive call so I know first of all that this is going to call
itself end times right because each stage reduces the size of the problem by one so if I'm trying to get the power set of n I'm going to have to do it to get n minus one and thenn minus 2 so I know the recursion of gen subsets to gen subsets this is going to go around end times that's not so bad but right down here I've got to figure out what's the cost of thisthis right this is constant that's setting up as constant that's constant but there I've got another loop and the loop depends on how big smaller is and smaller is a bad choice of term here because it's going togrow on me but let's think about it by the way I'm assuming a pend is constant time which generally it is the time I need to solve this problem includes the time to solve the smaller problem that recursive
call I know that's going to be linear but I also need the time it takes to make the copy of all the things in that smaller version so how big is that oh crud number two number of thingsin the power set grows is a factor of two right if I got something you know one through three I've got all the things with nothing in it all the things with one in it all the things withtwo things in it all the things with three things in it that's eight and each time around I'm doubling the size of it so for a set of size K there are two to the K cases and thatsays that this Loop right here is going to be growing exponentially because I got to go down that entire list to find all of the pieces so what's the overall complexity I'm going to play the same game let's
let T suben capture the time it takes to solve the problem of size n just temporarily I'm going to let s subn denote the size of the solution for a problem of size n how big is that thingsmaller and what do I know the amount of time it takes me to solve the problem of size n is the amount of time it takes me to solve the slightly smaller problem that's the recursive call to gensubsets plus the amount of time it takes me to run over that Loop looking at everything is smaller and adding in a new version plus some constanty which is just the number of constant operations the constant steps insidethat Loop okay and if I go back to it t subn is cost here T subn minus one is the cost there s suben is the size of this and then I got 1 two 3 four five constant
steps so C is probably five in this case so what can I say there's the relationship because I know s m minus1 is 2 the N minus1 there are 2 to the N minus one elements inside of thathow do I deal with this let's play the same game what's T subn minus1 that's T of nus 2 + 2 the nus 2 + C and I could keep doing this you can see what the pattern isgoing to look like I'm going to have K * C constant steps for each reduction I'm going to get another Power of Two And I'm going to reduce this overall term after K steps to T the N minusK when am I done when that's down to something of size zero and there's the expression and what you can see is what I wanted you to see order in or sorry order two to the end is exponential
in the size of the problem what's the characteristic something that has a recursive call sorry multiple recursive calls at each step is likely to lead to exponential but that can also be buried inside of how I grow thesize of the problem and that was the case here there's only one recursive call but that Loop grows in size each time around so the complexity is exponential I'm going to pull this together I said one of thethings I'd like you to start to recognize is what are the characteristics of a choice and algorithm that leads to a particular complexity class and you now have some of them if the code doesn't depend on the sizeof the problem that's constant and in fact we've been using that as we look at pieces of the code if we can reduce the problem I said in this case by half each time by some constant factor from
n to n /2 to n/ 4 to n/ 8 that tends to be characteristic unless there's a hidden cost somewhere else of a logarithmic algorithm these are really nice simple things that reduce the size of the problem byone at each step an iterative call it goes from n to n minus one and then to n minus 2 and then to n minus 3 characteristic of linear algorithms log linear we're going to see next time polinomialtypically quadratic and squared when we have nested Loops or nested recursive calls I'm looping over something inside of there I'm looping over something else on a on a size that depends on the size of the problem and thenwe just saw this last one multiple recursive calls at each level tends to be characteristic of exponential and as I said we'd like to be as high up in this list as we can because those are really nice
algorithms to have let me give you one more example of looking at this and then we'll be done Fibonacci standard problem right the nth Fibonacci number is the sum of the previous two Fibonacci numbers this was the examplewe saw multiplying rabbits if you like here's an iterative version of Fibonacci it says if n is zero it's just zero if it's one it's just one otherwise I'm going to set up initially the two previous Fibonacci numbersand then I'm just going to run through Loop where I temporarily keep track of that number I move the second previous one into the last previous one I add those two that becomes the second previous number and Ijust keep running through that Loop you can go run it you see it does the right thing what I want to look at is the complexity so that's constant that's constant that's linear because the work inside the loop
is constant but I'm doing it end times so this is nice bottom sorry I should say the bottom thing is constant the overall algorithm the worst case is just order n great what about the recursive version for methis is much nicer code it's nice and clean it says if n is equal to zero FIB 0 0 if n is equal to one FIB one or the first and second Fibonacci numbers are 0 one otherwise justreturn what I get by summing both of those pieces and you can probably already guess what the complexity is going to be here right because I've now got two recursive calls inside of this call so one way tothink about it is if I'm going to solve the problem up here I've got to solve two versions of the problem below which has got to solve two versions of the problem below and in general this is going
to be exponential 2 to the N now you say wait a minute I was paying attention with this guy was yattering on a couple of weeks ago honest I was and in fact what we saw was that FIBisn't balanced in terms of how it goes right it's not that on the right hand side of the tree I have to solve all of those portions because the problem gets smaller does that change the complexity well theanswer is it changes the base but it's actually still exponential and if you want to go look this up I'm sure you can find uh you know Wikipedia very quickly this this actually has a very cool e exponentialgrowth it's the golden ratio to the nth power and in fact I encourage you to go look at it in even more copious spare time you have it's a very cool proof to see it but the bottom line
is while we can do a little bit better than two to the N it still grows exponentially
within so what do we have we got Big O notation as a way of talking about comparing efficiency of algorithms what I want you to see here is that you ought to be able to begin to reason aboutwhat's the cost of an algorithm by recognizing those common patterns I keep saying it but it's going to be really valuable to you and you should be able to therefore work the other direction when you're given a newproblem how do I get this into a linear algorithm if I can log linear if I can would be really great but if you if I can't how do I stay away from exponential algorithms and finally what we'regoing to show later on is that in fact there are some problems that as far as we know are fundamentally exponential and they're expensive to compute the very last thing is you might have decided I was cheating in
a different way so I'm using a set of built-in python functions I'm not going to go through all of these but this is just a list for example for lists of what the complexity of those built-in functions areand if you look through the list they kind of make sense you know indexing you can go straight to that point Computing the length you compute it once you've stored it comparison order in because I got to compareall the elements of the list similarly to remove something from the list I got to find where it is in the list and remove it worst case that's going to be order in so you can see that theseoperations are typically linear in the size of the list these are constant for dictionaries remember dictionaries were this nice thing they weren't ordered it gave me a power in terms of storing them but as a consequence some of
the cost then go up for a list indexing going to a particular point I just go to that spot and retrieve it indexing into a dictionary I have to find that point in the dictionary that has the keyand get the value back so that's going to be linear because I have to in principle walk all the way down it it's a slight misstatement as we'll see later on a dictionary actually uses a clever indexing schemecalled a hash but in the worst case this is going to be linear so you see a tradeoff for dictionaries I get more power I get more flexibility but it comes as a cost and so these basically arewhat let me reason on top of the things I've been doing to figure out complexity and next time we'll do the last piece of this when we look at sorting so we'll see you on Wednesday