Transcript
Use with ChatGPT / Claude Auto-scroll A
uh welcome to our fourth problem session uh we're going to be talking about binary trees mostly today we'll talk a little bit about binary heaps which is a topic we won't cover until next tuesday but it will appearin a very small ways on your problem set four which will be due next friday so i'm going to go over a little bit of that material today but it's mostly concern the the subject material for today ismostly uh binary trees specifically being applied to set data structures and sequence data structures as uh professor domain talked to you earlier this week um but for now uh actually as of yesterday you've seen all of the datastructures that we're going to cover to imp that that will implement the set interface and the sequence interface right those uh those nice tables that uh professor domain has been showing you right uh those are now complete right
we have uh some data structures that are really good constant time operations for some operations so we might choose them for some uh applications and this week we've been describing to you trees which achieve like really pretty goodfor any type of query operation on my sets or sequences pretty good meaning logarithmic time not quite constant but for our purposes log n is i mean on your computer practically right not asymptotically but practically log n isgoing to be at most what on your computer
something like 64 right any input that you're operating on with uh and machine words as your input right uh you need to be able to address all those machine words right in in your input and on your computerthe size of your machine word addresses is 64 bits right and we assume that the word size is at least log in the num the size of your input so that you can address the input right right sofor your purposes on your computer log n is going to be no more than 64 which means you get a maybe a 50 times overhead or you know for smaller instances it could be more like 10 right ifyou've got like a thousand things that you're working on right it's not that bad right it's a constant it's not a constant factor for theory purposes but for your purposes log n is much better than a than a
polynomial factor right another factor of n okay so uh you've seen all the code you've seen implementations of all of these set and sequence interfaces right so i went ahead and wrote a little i compiled all of thatcode from your recitation notes of all of the different interface implementations and what i did was i wrote a little test program to see how they ran on a real machine right so i have a little test codehere um right so i have a little folder that lists you know an array implementing a sequence a binary tree implementing a sequence a dynamic array implementing all these kinds of things right then set things a sorted arraybeing a set and a binary tree and a hash table right these are our implementations i'm not using python dictionaries for hash tables i'm using the implementations that are in your restation and i'm going to run this little
test efficiency python code that basically is just gonna for each one it's gonna do a bunch of these different operations and measure to see how much time it took right i'm just logging how much time it took it'snot an asymptotic analysis but you know hopefully we see some separation yeah so i'm going to press that it runs a bunch of tests so let's take a look uh okay so i got a bunch of sequence operationsright we got build set at get at insert delete at the various places right and i'm giving these are the actual timings to some scale right to some resolution that i had for these data structures and you cansee build actually build on this machine just allocating some array and clearing it is a really efficient thing that's python's going to do for me and so that's actually it's miss labeling that as log n right uh but
uh you know these other things get out and set act really really fast right that's constant time and then these other things i essentially have can't do better than loop through the thing and so it takes linear timeand again sequence uh stuff setting at and getting at is slow but deleting and removing from the first thing i'm just re-linking the pointer right dynamic arrays again set at get ad is fast because it's just dynamic it'sjust regular arrays and then inserting and deleting last that's getting the essentially constant time now i'm actually when i'm running these tests to deal with averages i'm actually running these things a lot of times and testing their performanceand so i'm not seeing the worst case happen here right i'm averaging over all of the things which is exactly what amortization means and so that's why i'm getting good performance here uh a hash table again really uh
oh so this is what we talked about in problem session last week right implementing a uh kind of a double-ended queue with a hash table uh this is that implementation i just want to show it to you butit's actually pretty good this is what javascript uses for arrays and then a binary sequence represents a binary tree right a balanced binary tree this is our avl code that i had and you know all the other thingshave been really pretty bad at insert at and delete at but this one does comparable to all the other things now you see these are a little bit more you know machine cycles than the other things but youknow not so bad actually uh and then on the set side of things again we had a sorted array uh sorry this is a set from an array basically it's an unsorted array i'm just looking for all the
things that's very bad times sorted array does these fine operations great but inserting deleting is poor right that's why we need binary trees hash tables you know get good kind of dictionary operations but really bad order operations rightand then the binary search tree right a set binary tree uh again does quite good on all of these things in fact it's getting really quite good it's getting better for some reason than these the sorted array evendid so uh i don't know why our implementations are not optimized at all but it does pretty well asymptotically yep um could you explain again why the in the first day of surgery was blog this is just labeledbased off the timings right it happens to be that probably there's a c intrinsic underneath python that allocates this thing and so it does it really fast and so my program that's looking at these numbers and trying to
guess what the asymptotic running time is these are just labels based on these things ranges i just it's it's mis characterizing actually building it at any time yeah well i mean in in actuality if it was c coderight if all of this stuff was in c probably we'd see that that bar be longer because it's actually having to go through and touch all that memory it's still doing that here but all the python stuff issuper crafty right it's like 100 times slower than anything that c does and so you're seeing that that disparity here does that make sense okay so i just wanted to show you that uh we might release this foryou to play around with but i just wanted to give you a taste of that okay any questions you move on how do i turn this off up and off shut down
yes okay so what all right so moving on to problems working some problems uh so you have your set of problems here uh the first one is we're going to look at a sequence avl tree right this isa sequence abl tree how do i know that
you don't necessarily but these things are certainly not in sorted order of the things i'm storied in them right so it better not be a set avl tree right is it an avl tree is it balanced height balancedyeah yeah basically actually if you take compute the size of each subtree right the left and right sub-trees on all these you can confirm for yourself are balanced right there they're within plus or minus one of each otheractually this is about as far away from balance as you could get for this many nodes uh while still maintaining hype balance maintaining avl property which is why this is an instructive example it's kind of at the limitokay and uh what am i going to do this is a see what's missing in this picture if i'm claiming this is a sequence avl tree any ideas what's missing what is the sequence avl tree store that i'm
not showing in this picture what counts andit's a sequence avl tree heights right so it's a sequence avl trees different than set available trees are augmented by two things right because i need to be maintaining balance during rotations and so i need to store heightsi need to be able to tell what the heights of these sub trees are in constant time when i'm walking up the tree fixing things and the sequence requires me to store their subtree the numbers there right soi don't know i'm not going to draw it for all of these things but how about for number 4 what's its height
one two three that's the longest path from the sub the root subtree of that so this is you know height equals uh three that came from height equals two and height is one let everyone see that yeah andthen the size here how big is that that's one two three four five six seven right so this is i'm gonna put size equals seven here right and that's coming from this guy one two three four and thisguy is two right so how do i compute the subtree size it's my left subtree size plus my right subtree size plus 1 right and my height is taking the max of the 2 plus 1 right all rightso we did all that yesterday so i'm just labeling these things and what i'm asking of you is to perform a delete operation is a sequence uh tree so i'm i'm finding things by their index in the tree
right so i'm going to ask you to delete the eighth thing in my sequence okay so what is the eighth thing in my sequence yeah all right just to clarify is not delete a number correct well delete ateight do you see that it's a sequence operation yeah so this is very important that you differentiate between sequence and set semantics right if i'm dealing with the sequence i better not be looking up intrinsic things on thisdata structure right because it's not an intrinsic data structure it doesn't support that so if i wanted to support find the say the index of key 8 or something like that right then all i could do is it'ssimilar to like an array i would just have to loop through the whole sequence and tell me if the thing's in there right can't really do better than linear time this data structure is not designed for that what
is it designed for it's designed to find things by their index in the sequence right so uh how do i find the eighth index well i mean i'm looking at the tree and i can just you know countalong the in order traversal what's the inorder traversal right zero one two three four five six seven eight okay found eight but what does a sequence avl tree do right it i'm storing subtree sizes and when i'm herei don't know what index i'm at right how can i find out what index i'm at from the root i look at my left sub tree see how many it is right there are seven things here uh onetwo three four five seven eight right yeah because i'm looking for the ninth item by index eight right so this is saying that i'm the eighth item right and the guy at index seven does that make sense because
i'm looking at the subtree size here so what do i know i know that the index that i'm looking for is to my right right so i go down over here and i happen to know what am iwhat index of of am i looking for in this subtree zero right i want the first thing in this sub tree my search index has changed now right because i essentially dealt with all of those eight items rightso here i'm looking for the zero thing in my index i look to my left if i didn't have a left sub tree i would be the zero thing right and i would return me but there is stuffin here so i'm looking for the zero thing in here right which is just him and i return it okay and actually what i'm doing is i'm deleting it right so i delete it yuck what's the problem here
i'm not high balance weird what's not height balanced here um the lug subtree is earth so this guy's not height balance right right this guy's subtree is not height balance right this guy's two this guy's one okay sohow do we fix it we do some rotations right this is actually the bad case that with the third bad case that we talked about yesterday right if i tried to just left rotate this guy what would itlook like it would put 12 here it would put 10 here and 8 would be attached to that now it's height balance wrong in the other direction right that's no good right so the way to handle this casewhere i'm badly skewed to the right but my right subtree is badly skew is skewed to the left i have to do a rotation here right rotation and then do a rotation so that's that's the formula okay so
here we first do a right rotation at 10 okay which gives me something that looks like8 10 okay well obviously this is uh not better than what was before but it's an intermediate step so that we can fix it right we right rotate here and then we left rotate here right the default isthat we would left rotate here but because this had the skew in the wrong direction i need to right rotate this one first and then we can do it so now i rotate all of these guys over rightand put 12 down here 8 here 10 here done everyone see that that's what a rotation looks like okay it takes a little while to get your mind wrapped around what the transformation is but hopefully you guys allfollowed that transformation there was a little magic while i was trying to draw yeah i still don't feel like this tree is high balance it's not good observation why is that this thing still has height three what is
the height of this thing one right this is height one and actually when i was doing that rotation i needed to update all these augmentations right how which augmentations did i really need to which subtrees have changed duringthose things
i don't remember what the thing looked like what did the thing look like 10 10 had eight in its subtree so its subtree definitely changed right eight sub tree changed twelve didn't change eventually
okay so there's the case analysis that's in your lecture notes and was done in recitation right it tells you that these a b c d kind of sub trees right the ones that could change in these things thosesub trees don't change the only sub trees that change during one of these fixed operations when you do one or two rotations is either two nodes or three nodes that whose subtree has changed here uh it could havebeen the case that three sub trees have changed right but in the easy case only two nodes x and y i think in the notes could have changed and so when i do that i have to recompute theiraugmentations from their augmentations of their children but uh it's only a constant number of those so i just recompute them because i the sub trees below me haven't changed right okay so we have a height mismatch here yeah
should be where eight is right so uh originally in the picture 12 has a bunch of things in its subtree right 10 and 8 and we just deleted seven right so its subtree definitely changed there used to bethree oh no sorry it did right yeah so here three node sub trees have changed but uh that's the actually the most i'm showing you the worst case right only three nodes possible in doing one of these doublerotation things could have changed their sub trees and so we just have to fix the augmentation of those three things in the easy case it's just two things okay all right we have a uh on balance how canwe fix thisi could have been mean right i wanna be able to right rotate here right to rebalance i could have been mean and switch these two right if i switch those two then i'd have to do two rotations to
fix this thing because the middle one is heavier than the left one against what i'm doing right but i'm not that mean so i'm going to right rotate how do i do that well right rotate at 6 isgoing to bring all of this down below 4 right and stick this subtree as the left child of 6.does that make sense yuck that's going to be fun to draw
i'm just going to redraw it that makes more sense right uh eleven three two one and then six five nine eight twelve ten that's the right rotation at six is everyone cool with this the rotation my x is6 my y is 4 right i have a b c sub trees right what i'm doing is kind of switching which of x and y is the root here right so now y is the root and b andc sub trees here now become the children of x underneath y and notice that hopefully through all that process my inorder traversal has not changed we had to update our augmentations along the way but you know it's aconstant every time we walk up the tree and we walk up the tree only a logarithmic number of times yeah yes so every time we do a rotation we just like update the augmentation immediately afterwards before we do
any other routine exactly second part updating documentation just means like updating like the count and the height just the properties and stuff yeah basically what we did we define when we augmented uh professor domain yesterday defined for youwhat a subtree property is right it meant a property that i can compute only by looking at my children the augmentations of my children recursively right so here uh instead of trying to increment or try to think aboutlocally what this augmentation should be i'm going to throw away my old augmentation and just recompute it from my children because those recursively better be correct does that make sense yeah so just looking at how the rotation worksso basically you're swapping four and six so that way four becomes the parent node and six becomes the right note i'm gonna draw this picture just it's just something you gotta memorize it's this is x b c and
a can you see that picture okay
yeah it's in your notes it's not a big deal right but if you've got this structure where x has a left child right and these sub trees may be empty or not doesn't really matter what i can dois i can move from here to there has the same in-order traversal order right but it's got a different shape and in particular subtree heights have changed which means it can help us rebalance the tree and that's that'sthe whole point of avl does that make sense and that's the right rotation this one is this is a right rotation this is a left rotation any other questions
so as i'm walking up the tree every node i might have to fix with the rebalance but that rebalance does at most two rotations and there's at most log n ancestors that i have because my tree is heightbalance right at 2 2 log n or something like that right which means that at max i might have to do four log n rotations right because each one could do two rotations so that makes sense now inactuality you can prove that in a delete operation it's possible that you have to do a logarithmic number of these rotations up the tree this was a that bad case this is called the original tree i gave youis called a fibonacci tree it's the fewest it's the highest uh height balanced tree you can have on a on a given number of nodes um uh that's it's yeah the fewest nodes for a certain height i i
you can think of it either way and if you generalize that to a large enough thing then that thing will take a logarithmic number of rotations going up now actually with an insertion you can actually prove you cango through the case analysis uh an insertion operation will always rebalance the tree after one after one rebalance operation which could include two rotations does that make sense
yeah so in right rotation this guy becomes a right child yesdepending on whether you have a child yeah so if i didn't have a left subtree can't perform rotation a right rotation there yeah so a right rotation necessitates that i have a left child so if you're doing itand you'll see our code actually checks to make sure you have a left child right uh that's that's a an assertion that you might want to fire before you ever do one of these rotations anything else yeah soan insertion may take two rotations at most to fix a constant number of rotations and the deletion could take a logarithmic number of partitions now that's not something you need to know it's not something i'm proving here toyou uh just just something that's interesting there are rebalancing schemes like in in clrs right they they introduce a a red black tree to to introduce balance and that those trees actually have a weaker bound on it's not
as is tightly height balanced as as an avl tree is it allows higher than skew to right uh and because it's kind of a weaker restriction they get away with only doing a constant number of rotations that theycan afford that before they fix the tree uh but you know a little more complicated
very nice okay any questions on this okay so uh now so this is more of a mechanical question you'll get on your problem sets and now we get more onto the uh the theory type questions these are goingto be reduction type questions uh okay so this first problem uh thick nuri uh this is anyone nick fury right so it's a an avengers reference uh so basically what happens in this thing he's got a list ofsuperheroes uh that each have an opinion on whether they should go fight santa's okay and uh their opinion can be strongly positive or strongly negative and so what uh fick is trying to do is find from among hisrevengers uh what their what the log n most extreme opinion revengers are so that you can talk to them right he doesn't want to talk to everybody he wants to talk to a you know logarithmic number of them
okay it's kind of whatever all right so uh basically we have a uh a classified situation where you're given as a read-only input data store of these things in an array okay and i want to find the logn ones with the strongest opinions does that make sense and i want to do it and the first problem is in linear time okay so you actually don't know how to do this yet you'll know how to doit with material that you cover in uh well they teach you one way to do it in o46 but we're not going to get you there right now uh we'll teach you another way to do it uh inuh on tuesday right which is via binary heaps okay binary heaps are an interesting thing that implements a subset
of the set interface okay really it just you can build
on some iterable x okay i collect a bunch of things these items have keys right it's a key data structure in the same way it's implementing what we call a priority queue interface i can build these things ican insert things but i'm not going to do that here all i really need here for this situation is a delete superlative kind of operation in this case probably max delete max
okay so this is like a i got a data structure right i'm calling these things does that make sense yeah that's a priority yes a priority queue is essentially something that implements these two things actually there's a thirdone where i can insert a new thing right but i'm not going to need that right now so that's what a priority queue is and actually a set this is a subset of the set interface right right thenice thing about a heap which i won't show you how it's done right but what a heap can do so if i had both of these operations implemented using a set avl tree how long would these things takeme
how long does it take to build a set avl tree
and log in right because essentially i'm getting a sorted order out of this thing right if i'm inserting these things one at a time right or i could sort them and then put them in a tree in lineartime like you saw a couple days ago right in recitation but i have to sort them at some point right i'm kind of i need to take at least n log n time because if i'm going to beable to return their order their traversal order in linear time and i have this lower bound of m log n on sorting i kind of needed to spend and log in time here right and how long would thisdelete max take i started so long log in right so it's a set avl tree where is my max it's the rightmost thing i can just walk down the thing take it off maybe i have to rebalance but
you know that's a login operation right it's the same as like insert last in my substrate right so for a set avl tree this is n log n this is uh log n right now there's another data structurethat does better for one of these operations and the same for the other one that we've learned earlier anyone remember said avl tree didn't actually give us anything over a sorted array in a dynamic array okay so whatthat did right was we have a we could sort it in n log n time using merge sort or something like that and then we could just pop off the last one end times right that would be anamortize i mean if i didn't care about taking up that size i could do it in worse case constant time i just read off the first the last one i don't need to resize the array ever right i
can just ignore that does that make sense okay but that's okay if i had a data structure that implemented these two operations can someone tell me a uh an algorithm to generate fixed list don't worry about running timeright now but that just uses these two operations
yeah um so we built the data structure it's ordered from least to greatest for absolute value so don't don't don't worry about uh where things are ordered or anything like that i don't tell you how these things areimplemented right all i'm saying is i can i can accept a bunch of these things and i can remove the maximum and return it okay yeah anyways just build it but make sure that you build it such thatthe opinion levels are the absolute value of the opinion levels sure okay so that's that's a nice thing what i'm going to do as your colleague is saying is i'm going to look through all of the things inmy input i'm going to copy it over to some writable memory store okay right that read-only thing is not relevant to this part of the problem right what i'm going to do is uh
right sorry i'm thinking about your problem set that we're writing and mixing it up okay so uh we copy it over to uh our new uh like linear size array right and but instead of putting their values therei'm going to put the absolute values of their values that make sense i just check if it's negative it is i put the positive thing there right okay and then and then i stick that array in this buildright i put that there right so that'll take some whatever this build time is and then i can delete max k times or i can delete max some number of times however many things that i need right thatthe if i if i want log n highest things i can just do that log n times right so for this if i had such a data structure i could do this in one run of this operation and
log in runs of this operation does that make sense i can solve this problem reducing to this data structure right now for a sorted array or a sat avl tree right this operation kind of kills me already takesm log in time right the nice thing about a binary heap is it does this operation in linear timeyou will see that on tuesday and it does this operation in login time okay so how what's the running time if i use a heap to binary heap to implement this data structure order of n times order logn times log n how big is log n squared log squared n compared to n is smaller right so if i add those two running times together it's still linear right okay so that's how you solve the firstproblem okay i didn't have to tell you what a binary heap was or how it did what it did all i needed to tell you was that it did this operation in linear time and it did this operation
login type okayyeah all right the magic will be shown to you on tuesday part b says now suppose fixed computer is only allowed to write to at most log and space well okay that's a problem here right because we beforewe copied over the entire array filtered it out right and then did some operations but we couldn't even afford this if we couldn't store the whole thing externally in writable memory right okay so we can't do that soin some sense this is a more restrictive environment right i can do less things than i could it's a uh it's less powerful than my previous situation where i had as much space as i wanted to use rightso it kind of makes sense that i maybe couldn't get the running time bad that bound that we had before right maybe i have to sacrifice something because i'm in a more restrictive computational setting right okay now this
is something you could solve with binary heaps but you don't have to you could solve it with uh scent adl trees as anyone have an idea of how you could solve this using a set avl tree i'm limitedby my number of mice my my space is at most log n yeah all right so how much space does this indial tree take right space right there's constant number of pointers for each one of these nodes rightand i'm storing in nodes and space right basically every data structure we've shown you takes space the order of the things that we're storing right it's not using additional space it might take more time to do certain thingsbut the space is you know takes the number of items we're storing plus maybe a constant factor right right so i'm going to draw my input here which i can only read i can't write do i give it
i'm just going to call it a okay so this is my list of all the revenger opinions okay i can only read it but my computer can only write to this logarithmic amount of space
what can i put in that space
well i can i can certainly put log n things in there okay so if i'm given that restriction i probably want to build a data structure of that size right you know containing that number of things that makesense because what else are you gonna do right okay so i i gave you an idea maybe we could use a set avl here right i see a logarithm in my answer right it's very possible that we mighthave you know sorted arrays right or set avl things those those things give me a log somewhere in my running times right so kind of makes sense that i might have maybe a set avl tree here why whywhy would a set avl tree be helpful for me yeah because it started and you know you have the direct russell order you can calculate the traversal order and insert like anxiety sure i can do all those things
but in particular it's going to help me be able to find a large one quickly right if i if i kind of uh have a set of things it's going to be and i and i'm maintaining this datastructure by adding things incrementally to it right i can find out what the biggest one is or the smallest one pretty fast right and log in time right so if i have log n things in a in atree here right what's the height of that thing log log n that looks familiar so what can i afford i can afford a linear number of op set avl tree operations on this data structure right okay you hada question okay i'm sorry yeah um for there'll be an avl tree does it have to be a bts tree it's uh bts bst right so when i talk about uh someone likes korean k-pop okay uh so uh
bst but in natural kind of in the lingo that you're probably used to hearing in other contexts what we mean in this class is a set adl tree right now sometimes what people refer to as a binary searchtree doesn't have balance semantics right so we might call in this class a set binary tree right but really they're useful because they're balanced so we're going to usually just assume that we're talking about balance things here nowa set avl tree has these binary search tree semantics where the keys are ordered these items have keys and they're ordered it's a set interface right whereas we also presented to a sequence interface right for which these thesethings don't even have keys how could i store set semantics there right so but that's the distinction that we mean when we say uh binary search tree versus really a set avl tree versus yeah so if we're going
to make an avl tree out of this would that mean that like we when we make a node we tell it like we are keying on the absolute value okay so when you're uh making a set to avltree you got to tell us what if you're storing objects you got to tell me what their key is right if you're just storing some numbers like what i'm doing here right now this isn't a set avl treeright but if i'm just storing numbers i have to tell you the items that i'm storing are the keys okay and then everything follows right but if you've got an object that you're trying to sort like the studentsin this room you got a lot of properties right i want to all the uh the people with phone number right maybe i want to key you on phone number for some reason that's going to help me find
out where you live i don't know this is getting i don't want to go there okay so but if i if i give you a set to avl tree i got to tell you what it's keyed on ifi give you a sequence avl tree right it's obvious what my traversal order is going to be because i'm giving you a sequence right that's what the input gate was right does that make sense all right so i'vegot this set avl tree of size log n what should it be keyed by absolute value of their preference right or of their opinion i don't remember what this is called so but i what log n things doi put in herei don't know i i don't know anything about these things what makes one better than another right let's just put the first log in things that make sense all right what could that tell me now i've put this
thing in it how long did that take
log n times log log n time right but that's much less than our running time right so that we're looking for so i don't really care right i mean i want you to say how long it took butfor my purposes i know that it's lower than the running time i'm looking for so and i did that operation once i don't really care about it anymore okay yep how did you get log n because the numberof things i'm storing in this thing is log n and so if i pattern match the build time of an avl tree and i stick log n in there right then it's log n times log log n gotchaokay so is that for one iteration well right now i've just built this thing right maybe i uh well i just built it once uh i'm asserting too that maybe i don't need to build it again right what
could i do instead so right now i know i haven't filtered my data at all right i'm just storing these things in sorted order in some way right what can i do to maybe start processing the rest ofthe data yeah well i didn't like try to scroll through the list a and try to like remind someone that's bigger than like try to keep the maximum ah kind of sweep this guy over inserting things and alwaysmaintaining you know if i do that and i keep sticking things in i'll have this sorted thing at the end and now i can just read off the biggest k things right however as i'm inserting things across heremy thing's growing i'll just delete this oh delete small is fun i like that idea right basically yeah basically replace it right so what i'm going to do here's a proposal we're going to take the next guy stick
it in awesome which one don't i care about now the smallest one there so kick the smallest one out now this one that i stuck in may be the smallest right so i just kind of passed it throughthis thing but how long did that take me
it took me the height of this tree what's the height of the tree log log n right so i put one in i pop one out that's the smallest right and i keep doing that all the way downthe thing how long did that
take yeah i'm processing n minus log n things which is basically n right and each one of those operations took me height of the tree time so that gives me the running time that we're looking for and loglog yeah it's like recognition of like a slide yeah it's a kind of a sliding window technique you may have been using one recently okay everyone okay with this yeah let me just remember the context that we're talkingabout is log log n like tree and like what where so this thing the size of this thing is log log n yeah i mean sorry log n and the height of this thing is log of the sizein relation to like our little like login size like right there sticking this full of small log log entries or like like no so sorry i'm taking this stuff there's no intermediate data structure here i'm just sticking all
these things into a via bsta i mean a set abl yep into one set avl right of size log n i'm sticking a guy in popping the worst guy out right going through all the things i need tomake sure when i'm sticking it in i'm you know keeping track of which revenger it is and that i'm taking the absolute value and all those you know nitty-gritty kind of things but that's the basic idea right i'mjust taking this i'm sliding the window in putting something in taking something out that may or may not probably is not the same thing and at the end of this procedure right the invariant i'm i'm maintaining here isthat my thing always has the k largest opinions of the ones that i've processed so far right that's obviously true at the beginning when i build this thing and when i get to the end i've processed all the
things so and this has size log n and so i have the log n largest like highest extremist opinions and then i can just do an inorder traversal of this thing and read and return does that make senseand i've only used logarithmic space okay yeah so i don't get it are all the opinions in that uh are all the opinions in that avl tree all of these opinions are in the abl tree and at everat some point i will insert every opinion into this abl tree but i'll be removing the ones that i don't care about as i go does that make sense i'm always maintaining the the invariant that this thing beforei insert something has exactly log n items in it and then i'm maintaining that invariant by sticking one in taking one out oh okay so then which one are you always the min right because i'm wanting the the
largest ones and the mid by absolute value but yeah so i'm keying by the absolute value of these opinions
total run time here right it's bookkeeping right so it took mea log n times log log and time to build this data structure at the beginning right plus n times log log n i did you know basically n operation asymptotically and operations this way it's actually n minus logn operations right and each one of those operations tree operations you know doing one insert one delete each one of those took the height of the tree time and so this is that good yeah if instead of blindwe just insert and do we do a comparison and then so the in inserting and deleting uh a set avl tree is actually doing comparisons within its data structure just compare with the name sure you could do thatright right so you could i could do it the other way right i could remove the smallest element here to start with right and then i compare it with this guy and then whichever is bigger i stick it
back in same thing right it's just am i doing the delete first and then then the insertion or i'm doing the insertion first and then the deletion any other questions lots of questions all right well i'm probably gonnahave to skip the problem uh we're gonna move on to uh c s so now s c l r all right what's the reference here yeah clrs right so these are four academics who wrote a popular textbook incomputer science uh okay this is the same kind of k kind of thing okay they found k first editions and they want to auction them off uh people can go on to their website they have a bitter idit's a unique identifier right and they can place a bid for one of these books right and they can change it during the bidding period but you know at the end of the bidding period the academics want to
know who the uh you know what is the expected revenue i'll get by selling to the k highest bidders does that make sense yeah okay so note that before i build this data structure i know what k isk is a fixed thing right right because my my running time of this get revenue depends on this k it's not an input to that operation right so k is kind of i don't know what it is apriori it could be n over 2 it could be log n right it could be 1 right but the data structure i build needs to satisfy these running time properties no matter what choice okay that the academics toldme does that make sense okay so what i need to do is as as time is going on people are placing new bids and updating their bids right and you know those updates can take longer time but as
soon as i close the window i want to be able to tell in constant time rightwhat the k highest bidders are any ideas on how to do this what are the operations that i have to do i have to be able to place a new bid right i associated with a bidder is anid and a bid which is also an integer right how many dollars i'm going to pay for this book uh update the bid in some sense i need to find whether that person placed the bid before right inmy data structure so at some point i'm going to need a find on bidder id does that seem possible right so i might want to have some kind of dictionary on bitter ids right when i say that iwant to have a dictionary on something right i'm not specifying to you yet how i'm going to implement that dictionary right what are my usual options a hash table but what if i need worst case time
a set avl tree right that's going to be your go to for a dictionary right because that's going to give me log n time to find things by a key right it's the only thing except for assorted orsorted you could also use a sorted array right but that's going to not be dynamic and here we're updating who's in my data structure all the time right people are going in and placing bids right new new peopleplacing bids so my set of things that i care about is changing all the time so that's probably going to steer me away from sorted arrays because they're not good with dynamic operations okay so i'm going to needsome kind of dictionary on bitter ids but i'm also going to need to maintain the the sum right of the k highest bidders does that make sense right and so in some sense i need to keep track of
an ordered notion of the bidders right the bids that are in my data structure does that make sense right so order is going to be important on the bids i'm going to need to look up on bitter idand that's about it right okay yeah just checking so something
yes correct yeah so uh that's a very good observation right if it runs in worst case time it also runs unexpected that time right because there's essentially no randomization that i'm talking about here right
yeah it's so there's a stronger notion which we want you to specify which that actually there is no randomization here we're not using a hash table right in this class that really that's the only situation where uh that'sgoing to be an issue right uh so uh but if it is uh what this problem is saying uh for each other state whether your running time is worst case expected and or amortized what we're really trying toget you to say is what's the uh evaluate the running time of your algorithm with the proper qualifications right if it took worst case i want you to say that it took worst case if it took if youuse the hash table i want you to say expected and if these operations i were sometimes really bad but on average they're really good if i did a lot of them that's that's amortized right right or if i
reduce to using a dynamic array right or if i reduce to using a hash table those dynamic operations would still be amortized right okay so the dynamic ones uh nice thing about linked data structures is that dynamic operationsaren't amortized right so we're gonna get be able to get now for this problem we can actually get worst case bounds so we're going to try for that you can also do it in expected using some hash tablesfor that that dictionary right okay so when you approach a data structures problem in this class you want to tell me what it is you're storing first off right tell me what's supposed to be in those things rightsome invariants on this data structure to you know make sure that when i do queries later right that these things are being maintained right so that uh you know if i have you know if i'm maintaining a sorted
array right and i'm supporting an operation to find the maximum i better anything i do to this data structure better be maintaining the invariance that these things are in sorted order and the last thing has the maximum itembecause my max return thing is going to look there and return that does that make sense so i want to tell you you want to tell me what is being stored at you know a generic point in timeduring your data structure right what is being maintained so that when i support a dynamic operation or a query right in a dynamic operation where i'm inserting and deleting things from this thing i need to make sure thati'm maintaining those invariants and when i'm querying i can actually rely on those invariants to to answer my query does that make sense okay so for this problem this is okay uh any ideas i have two two kind
of keys that i might have to deal with one's a bid id and one's a a bid right so how could i if i have two keys right that i might want to maybe order on one and lookup on another how many data structures do you think i'm going to use two that's a pretty good guess okay so one of them let's just guess right like i need to be able to look up on bidright so let's store these bitters right in some kind of dictionary that's going to be able to look up those things fast right so you know two data structures right one is a a dictionary on a keyed onbitter id okay what else am i going to want what's up
the other way around a dictionary stored on the bids is a dictionary what i want here i want to maintain order somehow right because i want to maintain the k biggest things that i've seen so far right nowif if i had at some point in time right what's going to happen right if i'm maintaining the k largest at any point in time it's possible that one of those bidders maybe decreases his bid right so it'sno longer in the highest i'm going to also need to keep track of the other guys to see who i should add back into that set for example right so here's an idea i'm going to keep not justone other data structure but two other data structures maybe this is a leap you don't have to do this there's a way to do it with just one another but i'm going to store two more one is a
kind of a data structure tostore
with uh storethe k highest biddersand a data structure to store the
n minus k highest bidders does that make sense so this separates my problem quite nicely right if every time someone does an interaction with this data structureright i can check to see whether it's bigger than the smallest thing in here right if it is i can do the same kind of trick i did before right i can remove it and stick my new onein there right and where do i but i removed it i have to maintain this property right so i stick it in here right there's another case what's the other caseit's smaller right in which case i don't do anything to this data structure and i just stick it into here that makes sense right so what are the operations these data structures need to maintain finding the minimum orthe maximum of these two sets does that make sense and actually not really the where are those operations i don't have them anymore but they were the priority queue operations they had uh delete max right and also insert
where things that it did well on right so any priority queue right anything that can deal with maxes and mins right is good right and and what what's a data structure you know that can deal with maxes andmins pretty efficiently the set avl right so instead of data structure here i'm going to say setavm and obviously it's going to be keyed by bid right because that's the thing that i'm going to want to find max's and mins over okay everyone following the logic here of why i mean i'm maintaining these thingsso this is this is the level of an invariance that i want to maintain because when i go to for example do this query get revenue right i can just run through and sum all of these things ohwait how much time do i have do i have k time no i don't have k time so i don't i can't afford to sum up all of these things at the end of my right i have to
i have to return it to you in constant time any ideas yeah just compute you know update a song right along with this data structure i'm going to keep a fourth thing which is just total
of their bits right i'm going to call it like a t okay and that's something i'm maintaining it's part of my data structure right it's you could think of it as i'm augmenting this thing with a number rightand the point of augmenting this thing with the number right is that i can just if i need to know what the total of this stuff is i can just look at that number does that make sense allright so now i think you know we're almost done we're basically done right how do we do this uh someone walk through to me how i would get revenue with this data structure i just i basically kind oftold you look at this number return it right because that's the invariance that i've maintained on my data structure i'm relying on this invariant now i better make sure this is good when i do dynamic operations right i
make sure i maintain it but if i by induction are ensured that all of this stuff is good and when i do a dynamic operation all that stuff is maintained then i'm all good right so get revenue afteri kind of did all this extra work right it's very easy i just look at this number and return it okay so when we're grading a data structures problem usually we give you some points first for setting upyour data structure separately from the operations and then we give you points per operation that you successfully deal with and then some points for correctness and running time yeah you have a question so would total be like athing that we update whenever we um like mess around with the highest bitter tree and then and minus k highest bigger tree sorry say that again so like are we treating like the total like of like an augmentation
that we update every time we do something yeah yeah so it's just a one number it's not really a data structure it's just one number that i'm storing with my my database right okay all right so how doi implement a uh new bid operation yeah can we assume that the bids will also be unique can you assume that the bids may be unique no right so that's actually something that is a really useful observation we'vebeen talking about set data structures as requiring unique keys right how can i deal with non-unique keys it actually turns out that you know hash table it's really important that these be unique keys right because i i needto check whether it's in there i'm looking for that single key and when i find it i have to return right if i had multiple things with that key i might not return the one that i'm looking for
right it doesn't even make sense right but you can generalize the set uh uh kind of infrastructure right to deal with multi-sets how can i how can i do that well with each key right again i'm storing uniquekeys with each key i can link it to a sequence data structure or any other data structure right and what i'm do is i'm going to anything that has that key i'm going to stick it in that datastructure right so instead of storing one item there i have the possibility of storing many things there now i have to change the semantics here right if i'm saying find on this key well now i could say i'mgoing to return all of the things with that key or i'm going to show our some thing with that key right but you get the idea all i have to do is map it to some other data structure
to maintain those things like maybe i want all the things with that key i want to find the one with this other key right so maybe i link to a set data structure that can search on other thingsright but the idea here is we maintain this uniqueness key property right i have to relax my semantics so that i'm storing multiple things at that key location does that make sense yeah why does it matter whether you'vesaid the entree or not uh it does uh so it's going to matter here right because i have bids right and the bids could be non-unique right two people could have the same you know uh bid and byour definition of a set data structure it had to have unique keys so if i stuck in all these things keyed by bidder you got a problem right now in actuality we can get away with that by storing
basically a linked list of all the things with that key and we'd be fine right and then whenever i want to return one i could just do but actually a binary tree right actually is flexible enough that inmost implementations you can just store a bunch of those things but actually our run times do worse then right what does it mean to find next in my sequence right what does it mean to find the to returnthe next larger thing above this key doesn't really make sense because there could be multiple ones which one do i return and if i repeatedly do find next on this data structure right i might not loop through allthe things right so some stuff breaks down in our interface right so i would prefer you use unique keys in this this kind of situation next tuesday i think with binary heaps uh we'll deal with non-unique keys that's
fine but if you're gonna use non-unique keys in here you just gotta be a little bit careful about the semantics okay yep
uh so you get the same uh running time you the you have to change the semantics on what you mean by find something right i just want to return anything with this key right what if everything has thesame key then it takes constant time i just returned the first thing it's i mean these are special cases that you know you have to think about right uh i don't like thinking about them right so i justlike having unique keys and if i want a situation where i have non-unique keys i'm going to basically put collisions at that key into a new data structure right it's just easier for me to separate out my headon what's happening because all of the running times that we proposed you know very strong definitions for unique key you know when you're dealing with a multi-set it's a little bit more problematic any other questions i we really
need to kind of move on here right uh dictionary ketone bitter we still haven't implemented any dynamic operations new bid what do i do uh what am i going to need for my update i'm going to be ableto need to essentially find in each of these data structures where that bidder is right and if i just have a thing keyed on their bid right the interface doesn't tell me what their old bid was it justtells me what their bidder id is right so if i just had their bidder id and their new bid how the heck am i going to find out which of these dash or where in these data structures theyare right what i can do is i can store in this dictionary which i can look up in some amount of time right a pointer to where it exists in these things does that make sense this is called
cross linking you may have done that a little bit in problem set two or something like that yeah are we storing a pointer to a specific figure yeah exactly right so the the invariant we have is that allof the bidders we've processed so far exist in these data structures right in one of these data structures and because we've used a set avl tree right in particular exists in a node of one of these data structuresright what we can do is in this thing maintain pointers right mapping each of the bitter ids to their location in these data structures and why is that going to be a useful thing right uh say i mappedthis dictionary right what could i use for this dictionary to get the running time we're looking for i could use a hash table or a set avl right if it's set avl i'm going to get logarithmic time worst
case with a hash table i'm going to get constant time but it's expected right so it could be linear time in the worst case right so we're going to use a set avl tree right because that's what wedo right now and that's going to give us worst case okay so what i'm going to do is for each one of these things i'm going to store that pointer so what i'm going to do is first i'mgoing to do that operation we had if i'm adding a new bitter right i'm going to take the you know the d and b right these two values that object that's that that bitter object or whatever i'm goingto look at the smallest thing in this data structure right see if it's bid is bigger than my my the the thing i'm inserting right if it is then i'm not going to touch this data structure i'm just
going to insert it in here and now after i insert it in here i know exactly where it is in the data structure i just inserted it right right so now holding that in my hand the node righti can go and insert that bitter into here right by bit id right so it's going to take logarithmic time and now i can store with that node my pointer to this data structure does that make sense andin the other case i kind of do the same thing right if it's bigger than the smallest thing here i pop that smaller thing out stick it in there and i stick my new guy in here cross-linking eachof those pointers along the way does that make sense hopefully kind of kind of okay yeah and for update very similar right if i want to update a certain bidder i look in this data structure finds the bidder
traverse that pointer to wherever it is in one of these avl trees right if it's in this if it's in this one i just remove it from the tree right or i remove it from the tree and theni reinsert right with whatever the new bit is right and if it's in this one again i remove it from the tree reinsert and whichever these things is and then i might have to you know swap a constantnumber of things back and forth here to maintain that this has the k highest right and when i do those dynamic operations i'm always removing some constant number of nodes in each of these trees and and adding backin a constant number of things and while i do that i just make sure to update this total as i go right his total was the sum of all of the bids in here and if i insert a
new bid in here i have to add to that total and if i remove one i have to remove from that total but again it's a constant number of things i'm moving in and out of these data structuresand so it can update this in constant time that makes sense now the look up here and the insertion and deletion into here those each took logarithmic time worst case but i did a constant number of them soagain longer than time does that make sense that's that's essentially this problem it's a little it's difficult right there's a lot of moving parts here right but if you just break it up into describe to me and likeyou really do a good job on this part describe well to me what your data structure has then those descriptions of those algorithms can be pretty brief actually right so you know in this one you tell me these
three data structures you tell me this guy's mapping to its location and these things i'm maintaining this guy right and then you just maintain those things with dynamic operations and then use those things for query operations that makesense okaywow we have 10 more minutes
i'm going to briefly do four or four okay for you okay receiver roster we've got a coach she's got a bunch of football players receivers and wanting to start on our team the uh some number of of playersthat have the best the highest performance okay and by performance we mean the average number of points they've played in games that they have logged in their system right but actually their data is incomplete right they don't knowwhich games and how much they scored in all these things there could be errors right and so these interns they're up they're constantly updating this database with queries like uh oh uh you know never mind this person didn'tplay in this game or actually they did and they scored this number of points right that's the clear and record things right and then at some point in time right like when we start when we want to play
a game right i want to be able to return the the jersey with the k-th highest performance and log in time okay this is kind of a kind of a rank query right right the kth highest okay uhnow in actuality i might want to return all k highest players so that that might be my my roster right but this is you know a more generalized query it's more specific more it's it's not really comparable butyou get an idea for why that might be useful to the coach i don't know maybe not okay so what's the idea here we have a lot of different things floating around we got games they have ids uniqueids we got receivers they have unique ids and each receiver could play in many games right oh that's kind of worrisome and many receivers could play in the same game these kind of many-to-one mappings are a little confusing
and then we've got each player receiver having a certain number of points per game and we're trying to sort them kind of by their performance which is a rational number right which has to do with the number ofgames they've played and the total number of points right now i see rational number i can't compute that right that's what we were talking about last problem session right but what i can do is i could store thetotal number of games they played and the total number of points they had right and you could imagine by augmentation similar to this right every time i add a game right one of these small operations i can updatethat information for each player right right if i'm just if one of these these dynamic operations is affecting only one receiver i can you know update whatever it is in in constant time probably right if i just store
with the player what their total number of games is as recorded by the database and how many points they've scored then if i have a data structure that needs to sort the receivers by their performance so i mightbe able to find the kth one right the k largest then i can't compute that performance but what can i do i can compare two players based on their performance using cross multiplication right right because i have thenumerator and denominator of each of these rationals and i can cross multiply and figure out whether one's bigger or smaller and as long as i have a comparator i can do set jbl stuff does that make sense okayso that's the i'm just going to outline kind of the the components of this data structure okay well first off uh i'm gonna need to record a receiver and a receiver could have a lot of games but the
important this is kind of a receiver centric kind of problem does that make sense to you guys right i'm not ever wanting to filter on all the receivers playing a game right i'm never like removing i'm never removinga game from the system i'm removing a receiver from ever playing in a specific game does that make sense so if i'm storing a receiver and each receiver has some games associated with them kind of makes sense imight want to have a nested data structure right where with maybe i have a a dictionary on receivers and for each one i store all the games that they've played it in some other data structure right with eachreceiver i store another its own data structure containing all its games so that makes sense okay so that's the idea right we have some kind of i need to be able to look up receivers right because uh you
know i'm i'm clearing them or i'm recording them right so i'm gonna have a you know a dictionary or you know here i'm looking for worst case login time so i'm going to you know skip the dictionary abstractionand go straight for the set avl avl uh uh keyed on receivers i before c e except after cit is i e i okay that rule never works okay uh set avl tree on receivers and each one of those nodes right with each one of those receivers i'm going to store for each store a set avlon games okay why do i store a set avl on games why don't i just store a list of all the games because if i want to remove this game from a receiver i need to do that inlogin time and here what we're saying is that n is the number of games but the the number of receivers on the team is always less than the number of games so right if i search in this avl
tree and i search in its avl tree i can be assured that those two searches was only login yeah because i might i need to remove a game right so there you go then what am i doing i'mreturning the k highest performance well i need for with each one of these guys i also store what was this augmentation the sum of the points stored in these games right sum of points and uh what was itnumber games because if i store both of those things in constant time i'm going to be able to compute their performance right where i'm going to be able to you have the data i need to compare performances yeahso you just don't have variables yeah yeah it's just numbers right these aren't data structures this is data structure these are just numbers okay i'm storing that with each receiver right but that's not going to help me find
the kth highest player right none of these things are sorted by performance right so i need the last data structure
fivei need to store something dynamically sorted by performance so yeah set avl storing receivers
keyed on performance now when i say keyed ketone performance you want to mention something about the cross multiplication right like i'm storing with each one of these things this augmentation and when i'm comparing two things i'm using crossmultiplication but other than that then we can abstract it away right you've abstracted that function call and i can imagine comparing two keys i can do this right this is a theory thing i'm not asking you to implementthat right but that's sufficient for me as a reader of your solution to be able to say yeah you know what you're talking about okay all right so how do i connect these things right the thing is i'mgoing to need to be uh i need to update this these things right when i insert or remove a game right so how do i know where these receivers are in this thing i store a pointer into this
data structure right so up here i store a pointer right to where it is in the data structure right again i'm storing all the receivers this has the same size as the number one data structure up there hasthe same number of receivers rightbut we're not quite done yet because i'm not wanting to know like who has the the best performance right i want to know who has the kaith best performance ugh how do i find the kate best thing inthis treat right i've got a tree right set avl tree it's mapped on performance right i know where the last one is but if i want to find the kate one from the end how do i do thatit's an avl tree a set avl tree all i'm storing is heights is there an operation that you've thought about you're not storing the size of each ah a set avl tree by default does not store sizes right
that's what a sequence does but you think maybe that would be helpful in this situation right yeah so actually if i decided to augment by sizes also i could do the exact same kind of sequence find at operationright and i could be able to look up the n minus k item right in here using the exact same function for subtree at that i had in the sequence avl tree stuff right so actually in clrs theydon't even bother with sequence avl trees right they go straight to if i wanted this rank find functionality on a sorted order of things right then i could augment with subtree sizes right but it's actually a much moreuseful general property so we decided to present it to you in the in the context of sequence abs juice because then i can just basically reduce to it when i get to here okay so that's kind of a
structure of the data structure that'll work on this problem i leave it to you as an exercise to implement all of these operations for yourself or take a look at the solutions the last one um is going tobe put online the solution uh it's pretty complicated it's what's called you can think of the size augmentation finding rank as a one-sided range query it's basically how many things are to the right of this value right whatthe last problem does is walks you through a two-sided range query right where i want to know how many nodes are between these two values okay so it's a walk-through all right thanks
guys