video_id
stringlengths 11
11
| content
stringlengths 0
123k
| datetime
stringlengths 19
19
| leetcode_number
int64 1
2k
| thumbnail
stringlengths 48
151
| title
stringlengths 9
106
|
---|---|---|---|---|---|
ho7Q7_gKldY | hello everyone welcome today we are looking at another lead code question looking at another lead code question which is speaking iterator now this question is is being asked in the february first second week of 2021 and what this question says is we are given an integrator class interface with method next and has next design an implemented picking iterator that supports a p functionality it essentially picks an element that can that will be done by the next call or to next so if you look at this question right we need to kind of come up with a class and then it has say three methods which is like peak next and has next and these three methods are are supposed to kind of either uh tell the given user whoever is going to use this class uh what is my current value to that particular enumerator is what is my next value and does it contains a next value or not right now in a way whatever what i'm understanding out of this question is this is more specific to a given language because your i numerator which is being used here is very very intrinsic to c sharp language now if i want to understand more what what this particular language does is i have to just go and look for this link which is given to us as a hint that okay what this numerator interface is now if if i change the language right say i change it to um uh let me let me change it to say python if you see right this is a different concept here here i'm just saying that okay i have a given nums it is a list format and need to work on it right now now list has its own method which is specifically to that python language if i use java java if you see it is having a iterator class and that is what we are going to use in order to implement our uh solution in right now considering i'm i'm using a c-sharp language so if i go and look for this i numerator right what function it contains or what method it contains so uh i have this uh i i i numerator class and in if i look at it it contains the following properties it contains a current property which says the element which is in the current position okay kind of helps us okay what this peak has to do right peak has to do nothing but it has to just return my uh whatever my enumerator which i'm going to create dot current right now what is my numerator in numerator here uh so if someone is trying to call a class right whenever he is going to instantiate an object of it right and whenever he's going to create an object of it he has to call the internal constructor to it right so whenever i'm going to call a constructor i have to assign values whichever i'm going to use in that method right so if i take it in that manner internal you can say i can make it internal you can say i can make it private private and i can create an enumerator now what and i can create an enumerator now what i'm what i'm trying to say here is i'm what i'm trying to say here is whenever someone instantiates this class whenever someone instantiates this class right right this property of this property of this class will now have this integrator this class will now have this integrator whichever is given as an input whichever is given as an input because this is a input which is given because this is a input which is given to me to me now i when the moment i do this right i now i when the moment i do this right i have my have my internal property or internal you can internal property or internal you can say say variable which holds that value right variable which holds that value right and and i here if i'm someone then if someone i here if i'm someone then if someone calls they say calls they say p get rated dot peak then i'm using that p get rated dot peak then i'm using that internal internal uh uh method and i'm just using the uh uh method and i'm just using the current functionality which is given current functionality which is given to us as a property here right now what to us as a property here right now what is the next one is the next one next question which is they are asking next question which is they are asking okay i need to implement the next class okay i need to implement the next class that means i need to that means i need to implement whatever uh the next value in implement whatever uh the next value in that iterator is that iterator is so in order to see what is next let's go so in order to see what is next let's go back to this one and see okay what is back to this one and see okay what is what is what what methods i have what is what what methods i have i have a move next okay what does this i have a move next okay what does this do is do is it successfully advances advances to the it successfully advances advances to the next element so in a way right if you next element so in a way right if you see see she sharp has already given us those she sharp has already given us those methods methods those uh properties those uh properties which in a way we are trying to which in a way we are trying to implement here right so in implement here right so in in in this is what i'm going to create in in this is what i'm going to create is right i'm going to create a boolean is right i'm going to create a boolean this will always keep a flag off that this will always keep a flag off that okay whether i have a next variable okay whether i have a next variable in in place or not so i have a next val in in place or not so i have a next val flag okay i have a next variable which flag okay i have a next variable which is present or not is present or not right so what i'll do is write what is right so what i'll do is write what is going to be my current value going to be my current value that will be my enumerator that will be my enumerator dot current all right and i'll move dot current all right and i'll move advance to the next next uh value advance to the next next uh value right so i'll run my uh iterator to the right so i'll run my uh iterator to the next next uh value so what that will be uh value so what that will be so that will be uh inimitated dot move so that will be uh inimitated dot move next as we just saw in the next as we just saw in the uh uh in the helper helper link which was shown here right so let me first see whether i'll move to the next one that was move next capitals and why i'm having this one this is always going to maintain that whenever this scope uh the object's scope is given to us it always maintains whether i have a next value or not i'll return my current value and what i'll do here in the index i'll just return my next well scope which is this one okay so if you see right uh this is a medium-based question in lead code but it more or less like very very internal to a given um language which you are using here what i have done is i have leveraged the i numerator properties and methods which are given to us i have another method which is called reset it will reset back to uh this reset hold collection to kind of to ground zero but considering i have to use only whatever i have to move to the next iterator or i have to use the current index peak is supposed to do just say what is my next element is so that was current and my next element my next method was supposed to move my cursor to the next particular value which is present or not right i created this flag just to maintain that okay do i have a next value to it right and because so that i can leverage that next flag into this particular has next method happening okay okay i think the output matched i got a wrong answer for one of the i got a wrong answer for one of the options which is this one options which is this one i got one false instead of a true let's i got one false instead of a true let's see what happened here see what happened here oh so for starters right the moment i oh so for starters right the moment i instantiated i i missed one thing that instantiated i i missed one thing that okay i'll okay i'll mark this too true mark this too true let's run this and see if that did the let's run this and see if that did the trick okay i got the right results let's cool it got accepted so uh suggestion to cool it got accepted so uh suggestion to this one is more or less like this one is more or less like the moment you see this question and in the moment you see this question and in case you didn't follow what i did in the case you didn't follow what i did in the c c sharp use your preferred language go to sharp use your preferred language go to the helper documents the helper documents read through what that iterator or read through what that iterator or numerator is whichever is being numerator is whichever is being leveraged in your language read through leveraged in your language read through those methods and properties which you those methods and properties which you can leverage can leverage and just simply apply them in the method and just simply apply them in the method which will be requested here which will be requested here with this i'll take your leave uh thank with this i'll take your leave uh thank you guys thanks a lot in case you like you guys thanks a lot in case you like the explanation like description please the explanation like description please go and go and do like and subscribe uh do like and subscribe uh in case you have any questions please in case you have any questions please post that into the comment section post that into the comment section see you next time thank you thanks | 2024-03-22 14:10:17 | 284 | LeetCode 284 Peeking Iterator |
|
x9iOjex5CNE | hey what's up guys this is john here again so uh today this is john here again so uh today uh let's take a look at this problem uh let's take a look at this problem here number 1066 here number 1066 campus bike bikes number two very interesting it's not it's a good problem you know it's a media level i think it's a good medium level problem okay you know i think i have uploaded another videos regarding camper spike number one okay so this one is like a little bit of variation comparing with the other one so let's take a look okay so you're given like a campus represented like a 2d grade here they're like n workers and m bikes where like n is smaller than m which means it's guaranteeing that every worker each worker can can be assigned to a bike okay and we assign one unique bike to each worker so that the sum of the manhattan distance between each worker and they're assigned by bike is minimized so this is the formula to calculate the manhattan distance between those two points basically you know with given like this n number of workers and m numbers of bikes it asks you to to find the minimum the minimum yeah so and as you guys can see here right so the name and the worker then the workers and bikes the the constraints is only like within the tin so which means you know every time when you see like this one here like see like this small number of here i think you should always and and as as for this problem right so this is like another classic two list of problems basically you have a you have a at least one here okay at least one and then you have a list two here these two and they ask you to find the uh like the minimum the minimum like values right basically to connect to connect each one of those in in into the other okay we have seen us some other similar problems but there is this one right so since the uh since the the bike sorry since the worker is smaller than the bikes so which means are when we define the dp here right so the dp here and the first one is the index right so we can define the first one with index because we know with this index it means that uh between between zero and the index and index minus one uh for other workers within this range they are they have already been assigned to a bike okay so that first one is index the second one is of course is the mask it's a mask of the signed bikes right so because you know since we need to check which we need we need to track which bike had which bike had been assigned so instead of uh instead of looping through the whole list uh we should always try to use a mask okay so that's it's much easier for us to uh basically to compare or to track like the status of of of each bike you know basically every time when you have a list and you want to check the list out of this of the status always try to think of a mask here okay so and yeah basically that's the that's the dp uh dp function here and and then after that it's just like the uh backtracking right the backtracking it's not a it's kind of like backtracking plus a dp so first uh let's do a a top down dp here okay basically you know with this index and the mask here we we can uniquely identify a current state right because at this moment right at this moment if if the previously this many workers have been assigned to a bike right plus this mask then we know okay this is a a unique state that's why we can use this one as a dp definition cool so um so first i'm gonna define like a hyper functions to give us the manhattan distance okay between two points so return p1 0 minus p2 0 plus abs p1 1 minus p21 okay so that's that and the next one is is it our dp here dp functions here like the the index and the mask okay so as always right so our template right the template is this one and if index mask if this the key is in the memorization okay then we simply return the memorizations right with this one visit the values for this key here okay and then uh let me try to finish the the template first okay so that's always a good thing to finish the template so you can focus on the on the on the actual business logic there so and the template the template is that we we will return an answer here and we will define like a answer a value here and then later on we'll just assign this answer to this like memorizations right in the end we simply return the answer okay so and regarding our problem you know you know regarding this for this problem since we're asked to get the minimum values here that's why we need to assign this us initialize this thing to a maximum size of value here so that later on we can get the minimum value out of it okay so and all right so that's that and now it's the time for us to see from the current state how many how how many other like different scenarios we can go from the current scenario so basically you know and the scenario when we can go from here is that i mean based on this one here there's a current worker here right and what all the other possible bikes we can assign to this worker right and remember this mask records the signed bike status so far right so in order to do that we just need to do a range we just need to loop through all the bikes here okay and we compare the the beat the bit value so that we can so it so that it can tell us if this bike has been assigned to a worker or not right so to do that uh let's search the bike uh let me define uh a length of workers maybe a length of workers here because the length of workers okay and then we also need the bikes here right so the length of bikes length of bike so that we can we can loop through the bike so now we have a let's do a worker here so we have worker here what grade goes to the what the current index right the workers and the index that's our current worker right and then now we just need to loop through what are all the bikes that we can assign to the current worker okay so i in range of the uh of b right that's the so we just need to check the if this ice so we just need to check the if this ice index index has been assigned right i i spike has has been assigned right i i spike has been assigned so how can we do that been assigned so how can we do that right right we just do a if you guys still remember we just do a if you guys still remember like how can we check that the beat like how can we check that the beat value right value right so we do a bit bit shift so we do a bit bit shift to the to the left by by eighth position to the to the left by by eighth position and then we do it to end with the and then we do it to end with the end with the the mask okay end with the the mask okay if this one is equal to zero if this one is equal to zero then we know this spike has not been then we know this spike has not been assigned to anyone assigned to anyone okay so for those who still don't know okay so for those who still don't know the speed manipulations here the speed manipulations here i mean i'll briefly uh give you like uh i mean i'll briefly uh give you like uh an explanation here basically let's say an explanation here basically let's say for example the mask is 0 for example the mask is 0 1 1 0 1 1 0. 1 1 0 1 1 0. and if we want to check and if we want to check if this if this bit value is one if this if this bit value is one or zero how do we check that basically or zero how do we check that basically we create like a we create like a um we create a like a mask value um we create a like a mask value by uh by doing this one here right so by uh by doing this one here right so basically we're basically we're creating like this one zero zero one creating like this one zero zero one zero zero zero zero zero zero that's the uh that's this like zero zero that's the uh that's this like the the bit shift here the the bit shift here by creating this one and we do an end by creating this one and we do an end with the original mask here with the original mask here since everything every every bit ev since everything every every bit ev every other bit every other bit uh value is zero so the the end uh value is zero so the the end the final result it depends on the final result it depends on depends on the end for this this is one depends on the end for this this is one here okay here okay which means if the original mass if the which means if the original mass if the bit value of the android bit value of the android mask is is one then the total answer at mask is is one then the total answer at the final answer is this one is zero the final answer is this one is zero zero one zero zero zero zero which is zero one zero zero zero zero which is not equal to zero otherwise if this one not equal to zero otherwise if this one equals to zero equals to zero then it means the final result is zero then it means the final result is zero okay that's how we use this thing to okay that's how we use this thing to check check if the current bit value is one or not if the current bit value is one or not okay so basically you know if this one okay so basically you know if this one is one right so and we can get is one right so and we can get so now it means that okay so we can so now it means that okay so we can assign this bike to the current worker assign this bike to the current worker and now we can calculate the the and now we can calculate the the manhattan distance between manhattan distance between those two right so uh bike those two right so uh bike bikes uh i right so now we have a bikes uh i right so now we have a distance right distance equal to get distance right distance equal to get distance of the worker distance of the worker the worker and the bike okay the worker and the bike okay now uh we can do our now uh we can do our dp here right so minimum answer dp here right so minimum answer of the what of the the dp since the the of the what of the the dp since the the the bike has already been assigned right the bike has already been assigned right so now so now let's move to the next the next one let's move to the next the next one okay and we also need to update the mask okay and we also need to update the mask so to so to to update the mask which means to mark to update the mask which means to mark this this this this index of bike to b1 so the way we're index of bike to b1 so the way we're doing it is similar doing it is similar like the how we check the just how we like the how we check the just how we check the value here instead of check the value here instead of end we just need to do our work here end we just need to do our work here okay or the mask okay then this is how we set this one this thing to value two to one here and since you know we are like we didn't change the mask we're just directly passing like updated uh another value in here so that we so that we don't have to do a backtracking okay cool so that's that's and sorry so here we return the dp right 0 and 0. so because at the beginning we have a zero bikes and we have a zero zero bike zero bike and zero zero uh worker here so yeah now the base case right always remember to set your base case so what what is the base case the base case is when the index is equal to the work to the workers which means when every worker has a bike assigned then we simply return what we do we return 0 here makes sense right because oh so sorry because here okay i forgot to add add this distance here because in the end right for the last workers right so for the last worker after the last worker has been assigned to the bike and then we do another like index plus one here and then later we need to set zero because there's nothing to be assigned here which which means in this case there's there's zero manhattan distance for us cool i think that's that should work cool i think that's that should work yeah that that's pretty much everything yeah that that's pretty much everything let's try to run the code here cool so let's try to run the code here cool so this one this one accept it let's try to submit it yeah accept it let's try to submit it yeah so it's a success i mean yeah i mean you know for me i mean the top down is i think it's more in it's more intuitive for me so basically it's basically we're following the uh we're following the uh the problem right basically at the fir first we're signing we're assigned the the first the bike to the first workers and then where then we try all the possible bikes okay and then we we assigned the uh we signed the second one with all the other remaining bikes the third one so on so forth until in the end we reached this one but among all those kind of combinations right we get the minimum out of the out of those all the cool so that's that and cool so that's that and okay so how about a bottom up i think okay so how about a bottom up i think and it's always a good thing to to and it's always a good thing to to practice practice both the top down and bottom top the both the top down and bottom top the bottom up so you can bottom up so you can get a deeper understanding of the dp get a deeper understanding of the dp okay so like i said you know okay so like i said you know for the bottom up you have to think it for the bottom up you have to think it in a reverse way right basically you in a reverse way right basically you know from know from here onwards you're getting from the here onwards you're getting from the current state you need to move to the current state you need to move to the next state next state right but from for the bottom up with right but from for the bottom up with the current state the current state you need to think backwards basically you need to think backwards basically you you have to think of okay how many you you have to think of okay how many what are the different like scenarios what are the different like scenarios that can that can can get to the current state from the can get to the current state from the previously previous state previously previous state and that's the first the first and that's the first the first difference and second difference is the difference and second difference is the uh uh uh is the uh how you do the for loop uh is the uh how you do the for loop here here because you know and how you set up the because you know and how you set up the base case base case because the uh you know for the for the because the uh you know for the for the top down you know uh top down you know uh it's almost guaranteed that the all out it's almost guaranteed that the all out of all the of all the other branches there are they're all other branches there are they're all valid uh except for the base case valid uh except for the base case because it's guaranteed it's being because it's guaranteed it's being controlled right basically you're from controlled right basically you're from top down top down you're starting from the from the valid you're starting from the from the valid state and then you're just moving state and then you're just moving trying to explore a more valid state trying to explore a more valid state based on the current valid state based on the current valid state okay but for the bottom up you know for okay but for the bottom up you know for the bottom up the bottom up not every combinations are valid not every combinations are valid right and because as you guys can see right and because as you guys can see here from the top down here right here from the top down here right so we are actually there there are some so we are actually there there are some cases that cases that i mean it's not valid so what are not i mean it's not valid so what are not what is other invalid cases what is other invalid cases the amount of cases are like maybe uh the amount of cases are like maybe uh if if if we have a three workers that if if if we have a three workers that have been have been marked to assign the the bikes okay marked to assign the the bikes okay and but the mask here let's say you if and but the mask here let's say you if the workers we're at the workers we're at like right three here like right three here let's see the if three workers have been let's see the if three workers have been marked to the marked to the have been marked to the uh to be uh have have been marked to the uh to be uh have a bike here a bike here but what if the ma the mask is zero zero but what if the ma the mask is zero zero one one one one zero zero what if there's only like two zero zero what if there's only like two ones in this mask ones in this mask so basically no this is an invalid state so basically no this is an invalid state it means that okay we we're saying three it means that okay we we're saying three persons workers have been assigned to persons workers have been assigned to the mask the mask so to assign to the bikes but instead on so to assign to the bikes but instead on the other side we only have two the other side we only have two two two bikes being assigned which is two two bikes being assigned which is invalid state but these things invalid state but these things will not happen in the in the top down will not happen in the in the top down because we are we're guaranteed here because we are we're guaranteed here right right basically now since we're doing a top basically now since we're doing a top down here down here the the first state is always valid the the first state is always valid which is zero zero which is zero zero okay and then from here onwards right we okay and then from here onwards right we are are exploring all the valid states because exploring all the valid states because we're it's guaranteeing that we're it's guaranteeing that as you guys can see we only assign as you guys can see we only assign a unassigned bike to the current person a unassigned bike to the current person so it's guaranteeing that so it's guaranteeing that the state uh the index and the mask the state uh the index and the mask they're they're they're always matched to each other they're always matched to each other okay okay but if you're doing for if you're doing but if you're doing for if you're doing like the like the top top down sorry the bottom up you top top down sorry the bottom up you know since we are going to loop through know since we are going to loop through all the possible other possible like all the possible other possible like combinations right combinations right and some of them are invalid states so and some of them are invalid states so we have to be we have to be careful about those so and okay and of course so so before doing that let's so today the date and time complexity for this right so how many how many of our state we have here we have like uh let's say we have a the walk run bike right so basically this one is like the workers times uh 2 to the power of bike of bike that's the total uh total state here and for each of the uh total state here and for each of the state we will be state we will be exploring all the bikes here so it's exploring all the bikes here so it's going to be another going to be another a b here right that's the length of the a b here right that's the length of the bike so that's the total bike so that's the total time complexity for this problem okay time complexity for this problem okay and from here actually you we can use and from here actually you we can use this one to this one to construct our bottom up dp here construct our bottom up dp here so which is so we have a we need these things here right so and then we have a dp so for dp so what what do we need the dp the first thing is that we have two dimensions the first one is the is the worker second one is the 2 to the power of the b here so which means when we construct the dp here we have to do this right so the second is this right so sorry is this right so sorry of this one this one okay and four in range w excuse me what happened here excuse me what happened here okay and here max size what happened here okay so the reason we are setting this one to max size is because we need to uh calculate the the minimum value right so we initialize everything to the maximum okay and then now it's the it's the okay you know what let's try to finish the our our main for loop here so on the outer on the outer loop here we we need to ring look through the workers right basically we have worker plus one so which means we have worker equals to the workers uh i minus one since we are doing like the one base and the worker is the zero base okay now the second second loop is is a mask okay as you guys can see here so and so for the top down here for the top down here we are only exploring the valid the valid states here but here we are the valid states here but here we are exploring exploring all the masks okay in range all the masks okay in range like this right we're like this right we're exploring all all the masks out of the exploring all all the masks out of the mask for mask for the current worker and but for some of the current worker and but for some of them it's not valid them it's not valid okay so and uh yeah same thing here right so with the current mask how can we get to the previously state right basically same thing we need to uh we need to range the bike here again okay so the way we're checking is that i mean if the current if this range if this one is it's one then it means that okay so some once okay so this one has been assigned to a bike which means the previous state is uh we so which means that previously this bike had not has not been assigned which means we can get to the current state from that from that state okay so this is what i'm what i mean here so basically i do the check here the k right uh uh and the mask and the mask is not equal to zero so this one this means that this spike been assigned has been assigned okay to a worker to a worker okay yeah then it means what it means that okay so let's do a let's do a get the distance for this bike first right so the bikes equals to this the k similar like the the top down version and we have distance equals the get distance right the the worker and the bikes the bike yeah so now the only difference here is this right so we'll do a eye mask right so which means that for the current bikes and current mask so we have find a way to get to the current state right so we do a minimum of that dpi mask of what comparing to what so the previous state is that so the previous state is that we have we have i minus one worker uh have been assigned to a map to a to a bike and uh and without this this bike has not been assigned okay so how can we do that we just need to do a reverse basically we need to remove this one from the current mask so that we can uh convert it to the previously state of the mask one this k right we do a one this k right we do a x or xor of the mask that's how x or xor of the mask that's how we remove this one from this mask we remove this one from this mask so that we can revert to a previously so that we can revert to a previously state here state here and yeah don't forget to add this and yeah don't forget to add this distance distance okay and then in the end we do what we okay and then in the end we do what we simply return simply return we return the minimum we return a we return the minimum we return a minimum of dpr minus one okay so why we minimum of dpr minus one okay so why we do a do a minimum here uh uh minimum here uh uh because you know okay so dp minus one because you know okay so dp minus one means that okay we have a means that okay we have a we have all the workers to be assigned we have all the workers to be assigned to to all the bikes to to all the bikes but the problem is that you know within but the problem is that you know within all those kind of all those kind of kind of uh the the possible values right of the mask here we need to find the minimum out of them because let's say we have two workers and we we have 10 bikes right so dp we have dp2 here and and the mask here it could be anything it could be zero zero one one zero zero zero zero okay and it could be dpr two maybe uh zero one zero zero zero zero one basically there are like multiple ways of assigning this the bike bike to these two workers that's why we have to do a minimum do a minimum out of all of them okay but as you guys can see right so now all of the possible masks are are valid only the ones with these two two ones are valid so how do we control that you know so we control that i mean we can show that uh by setting up like a base case so the base case is this like the uh like how do we how we start from this from the top down basically the base case is we have zero workers and zero and the zero uh zero bikes so which means this is a valid state and with zero workers and zero zero spikes the the total manhattan distance is zero okay and but to be careful here i mean you know somewhat i think it's a time thing to set to do something like this for example you know let's say what if the uh let's say the bikes is zero let's say uh sorry fc you it's it let's see the worker is equal to zero but the bike is not back back is not to zero so which means we have we have zero workers but but we we have uh like five bikes i think you know it's it's tempting to do something like this it means that you know with uh with the mask right in in like uh you know like something like like this right so we do a dp like uh zero workers right zero workers and the mask mask two to zero similarly as we can do something like this uh with this i equal in the in the in the workers right in range of w plus one okay so these things means that okay we have uh that we have this many workers but we don't have any any bikes right so something like this because you i mean you might think that you know of course you know with zero workers or zero bikes of course the the manhattan the minimum distance is zero okay which is which is correct but you cannot do this the reason being is that you know not every state here is i actually except for the zero zero all the other state they are all invalid state so right because the the problem is telling us each worker has to have one bike but in this case we have zero workers and we have many we have many bikes here so which means uh which means that not every worker can have a bike okay same thing for this one right same thing for this like the uh we have a many workers but we have zero bikes oh also means that okay there's no basically not everyone every worker can has like a bike so we which means we cannot set this this two for loop here the only thing we we should set is zero zero because with zero zeros so that you know it's guaranteeing that when we reach the the last dp i here all the other cases for the for the mask they will all be max mike's size only the ones starting from zero zero will give us the the correct answer yeah um yeah okay let's try to run the code first yeah cool so yeah as you guys guys can see here right yeah as you guys guys can see here right actually this bottom up is actually this bottom up is actually slower than than the top down actually slower than than the top down why is that like like i said you know why is that like like i said you know even though the time complexity is the even though the time complexity is the same but the difference that you know same but the difference that you know for the uh for the top top down we're for the uh for the top top down we're only exploring the valid only exploring the valid states okay by making sure states okay by making sure each worker is assigned to a bike and each worker is assigned to a bike and the the the mask is ma the mask matches with the the mask is ma the mask matches with the current workers current workers but with the bottom up as you guys can but with the bottom up as you guys can see we have a see we have a we have a nested for loop three level we have a nested for loop three level nested photo basically we're looking nested photo basically we're looking through through all the possible states that's the all the possible states that's the difference difference okay and okay and cool i think that's it for this problem cool i think that's it for this problem yeah and yeah and thank you so much for watching this thank you so much for watching this video guys stay tuned see you guys soon video guys stay tuned see you guys soon bye | 2024-03-25 16:40:52 | 1,066 | LeetCode 1066. Campus Bikes II |
|
fP2hlpe0YFQ | To a pick pick hello hello welcome on the channel so a question we are hello hello welcome on the channel so a question we are doing 171 excel sheet column bird game doing 171 excel sheet column bird game first let's understand what is the question so first let's understand what is the question so basically this you have equal in this we title will be your basically this you have equal in this we title will be your screen life and you have to tell screen life and you have to tell which one which one which one I have given you an example to APN it like this, if your hair is fine then it will be on your worst position, it is on the middle second, if you do it like this, it is 2016, Okay, then egg Okay, then egg Okay, then egg is 2728, so today we will start understanding like is 2728, so today we will start understanding like how will we approach, how will be the solution, how will we approach, how will be the solution, okay then support, there is only one slot, okay then support, there is only one slot, now there is one slot, so what can happen to it, if it is now there is one slot, so what can happen to it, if it is Muslim acid, it is B, so what will be the position of Muslim acid, it is B, so what will be the position of it. it. it. two slots have been given back, so if you use the seal here, then what can happen here, you can teach horoscope together, you can teach horoscope with your wife, then it is Hi Guys Think here, you Think here, you Think here, you can keep it here D, then you will calculate from the sun, can keep it here D, then you will calculate from the sun, what time together, what time together, 226, okay, Twenty-20 with one should be 226, okay, Twenty-20 with one should be completed, that means one calculation, you have completed, that means one calculation, you have kept anything, they must have kept it together, still kept anything, they must have kept it together, still how many together. how many together. how many together. 6 will be completed, okay, so it means that this brain here twice, we have deleted the food, then if we support, there are 3 slots here, okay, there are 3 You understand, it You understand, it You understand, it is from the seat, okay, so its simple meaning is is from the seat, okay, so its simple meaning is that there is one year here, 2016, that there is one year here, 2016, 2016 and feet C will come, then whatever happens after that, 2016 and feet C will come, then whatever happens after that, it will be with agriculture, then it will be with agriculture, then here 126 and then here 126 and then here 126 and then that much solution, so once you start the pattern here, then what is there, here we will multiply it, what will be its position, we will apply happiness and prosperity here with the power of 80 of these 226. This position will be 2060 Power Descendant and if we understand this and apply it, then what will happen here from the zero next to 16, then what will happen here from the zero next to 16, then 16506 Power One and here 2016, you are crazy, 16506 Power One and here 2016, you are crazy, you are fine, then the pattern has become, then now you are fine, then the pattern has become, then now I understand. I understand. I understand. approach it from behind. By back we mean that we will travel this system from behind and while increasing from 2060 power, we will apply the real age from zero till here till Yoga and Management. From this What will we do for the What will we do for the What will we do for the very Ballia account, we gave it our own very Ballia account, we gave it our own that red button wheat 20680 and English that red button wheat 20680 and English results and come to do more results and come to do more anti virus and started taking it, the reverse will anti virus and started taking it, the reverse will not work, the campaign had said column not work, the campaign had said column title.com 05 - Will 05 - Will 05 - Will you not do you not do Scientific Plus app that Cat Cat came - ah that Cat Cat came - ah why Candy Crush OnePlus One on the phone why Candy Crush OnePlus One on the phone because if it will go to 20 G but if it is because if it will go to 20 G but if it is one then the position is different, right in one then the position is different, right in 282 we will do that account, now it has to be increased in Uble 2016 282 we will do that account, now it has to be increased in Uble 2016 So Tips * Scanner increased what to do So Tips * Scanner increased what to do this Khurram please remind please please return this Khurram please remind please please return race let's race let's take the soil anywhere in the court take the soil anywhere in the court but it is okay that you but it is okay that you take York whether he has given this take York whether he has given this range answer is right or wrong range answer is right or wrong Hello Hi, it is correct on this also, it is okay, so it seems straight, this is what is coming, let's submit it, ok, so it is basic simple, I am asking you a question, it is a Taiji question, similar to the list board's Delhi Changes questions are Will keep and announcement of B-2 will keep coming Will keep and announcement of B-2 will keep coming Will keep and announcement of B-2 will keep coming so if you like then like share so if you like then like share subscribe ok by the | 2024-03-21 14:04:24 | 171 | Excel Sheet Column Number | LeetCode | Question 171 |
|
QWbVCqIhTO4 | hello guys they will try to solve the binary vertical order traversal profit binary vertical order traversal profit and see the problem statement given by and see the problem statement given by me tree return the vertical altered me tree return the vertical altered force all his notes value from top to force all his notes value from top to bottom and column by : if two notes are bottom and column by : if two notes are in the same row and a colander older in the same row and a colander older should be from left to right okay how to should be from left to right okay how to solve this problem let's see the example solve this problem let's see the example in this case you should have returned in this case you should have returned the 9 and then 3 15 and then 27 how to the 9 and then 3 15 and then 27 how to get this answer say you are at the root get this answer say you are at the root and the you can see this root know that and the you can see this root know that as there 0 0 in there in there you can as there 0 0 in there in there you can see the three at the dealer there and is see the three at the dealer there and is left a child should be negative 1 left a child should be negative 1 because it's on the left of it so the because it's on the left of it so the horizontal distance should be negative 1 horizontal distance should be negative 1 and this 20 should be positive 1 and and this 20 should be positive 1 and okay we go down and we are at 20 now at okay we go down and we are at 20 now at the same idea the same idea now the 15 is positive 1 minus 1 so it's now the 15 is positive 1 minus 1 so it's it's the same it's a 0 now so it's in it's the same it's a 0 now so it's in the same vertical line with the 3 and the same vertical line with the 3 and how about a 7 because their 20 is part how about a 7 because their 20 is part of one so the favor is part of 2 because of one so the favor is part of 2 because we plus 1 on the 20 so this is the idea we plus 1 on the 20 so this is the idea we we have to calculate we have to we we have to calculate we have to calculate a horizontal distance of each calculate a horizontal distance of each node and then put them together the same node and then put them together the same horizontal distance in the same group horizontal distance in the same group then he will be the answer so as I said then he will be the answer so as I said we needed to get her on this and of each we needed to get her on this and of each node so node so an easy way a simple way data I I made an easy way a simple way data I I made another class that I will have a tree another class that I will have a tree node and either will also have a node and either will also have a horizontal distance and the contractor horizontal distance and the contractor know to route this this will be a know to route this this will be a running distance okay so I will use hash running distance okay so I will use hash map why because if I get the hurom map why because if I get the hurom distance I can simply put it into the distance I can simply put it into the list the same her own systems list so list the same her own systems list so there will make this in constant time so there will make this in constant time so I will use hash map okay but I still I will use hash map okay but I still need a first me that this result result need a first me that this result result in result list okay each case root if root equal to not simply return this then we will do PFS why because when we do BFS we can get the horizontal distance of the current route and this left or right route if I can make it is easier so you know Q new linked list okay our first offer this route not into it is hurry on to this and will be 0 okay and the way to the typical BFS why queue is not empty okay now the curve in co2 q po okay do not forget we need a inter minimum horizontal distance first we initialize to integer max value and the max distance will be integer minimum value why because the hashmap do not have older and in the last so we should a return return the list in order so instead we just needed who saved me my Harlem dissonant Maxima around the distance okay so it gets the current node um map but oh I haven't map map integer the key is the horizontal distance and other value is the root root value okay okay if absent if this very untraditional easy so we need a new array list and then I will add that get to this her her long distance and add other was Kurt root Davao okay have them into it and there if Kirk Rueter karuta top left not naughty what you now offer them in tutor you know you see the root and the horizontal distance will be her her own distance minus one laughter so is minus one is the Curt root all right not equal to not offer all right what okay mmm so in this case we have um choice every node and Indiana we should get our answer we should do that Oh do not forget update a mini mini Maryland is and will be mess minimum mehar long distance and the current around Oh distance the same max along this'll be mass max max around is anaconda around the distance okay in the end for in - I go to minimum a long distance I left I called em max her long horizontal distance I trust us I will add the into the final result yet I so finally returned risk mmm I think it's right okay okay thank you | 2024-03-24 10:17:16 | 314 | LeetCode 314. Binary Tree Vertical Order Traversal Explanation and Solution |
|
Ds4U_MG4oWk | Hello Hi Ap Me Zu Lakshan To The Super Hero Problem And Dasha Problem And The Video Problem And Dasha Problem And The Video then subscribe to the Video then Video then subscribe to Video then subscribe to Ya Baby When You Have A Center Of You Ya Baby When You Have A Center Of You To Find The Number Of that I will tell you what Mamu sa flat you that I will tell you what Mamu sa flat you checked and difficult video that and your eclipse horoscope one and super that and your eclipse horoscope one and super absolutely minimum number of requests definitely absolutely minimum number of requests definitely subscribe loot-loot subscribe Video subscribe subscribe to And MS Word Yuktiyukt Dash Loot Jaane And MS Word Yuktiyukt Dash Loot Jaane And MS Word Yuktiyukt Dash Loot Jaane Loot Jaane Loot Jaane Loot Jaane To Loot Jaane Loot Jaane Loot Jaane To E Superheroine Phase Vacuya Research Loot Loot Loot E Superheroine Phase Vacuya Research Loot Loot Loot Liya Subscribe If Login Middle Video Subscribe Number Off Number One Side Subscribe And Number Off Number One Side Subscribe And Half Fuel Subscribe From This Half Fuel Subscribe From This Half Fuel Subscribe From This Quite Like SUV Increase The Number Of Mode Number Number Number One To Do Subscribe Button More Folic Acid Number To The Total Visits A Confusing Conditioner Kangar Hi A Yeh Problem Problem Ko Subscribe Now To subscribe the Video then subscribe to subscribe the Video then subscribe to the subscribe subscribe A Pressure Horn Rate And Account Sirvi A Pressure Horn Rate And Account Sirvi Sirvi The Best All The Subscribe My Channel [ n't forget to subscribe [ n't forget to subscribe [ Music] Bluetooth And Boys And Subscribe subscribe the ki mumkin subscribe the ki mumkin forward forward forward Problems Mantra subscribe The Video then subscribe to the Page if you liked Om Namo Been Followed But Let's Check Officer Sunil You Are You Om Namo Been Followed But Let's Check Officer Sunil You Are You Decide Subscribe Now Hai Water Digest Hai Water Digest Hai Water Digest Award Dhoop Ignore Ad Tak Hum Idli Award Dhoop Ignore Ad Tak Hum Idli Idli Idli Subscribe My Channel Subscribe To Hai IDBI Temple Dedicated To Leave When You Will Hai IDBI Temple Dedicated To Leave When You Will Not Give Up At Least One Item Number 19 Not Give Up At Least One Item Number 19 Different Oil Co Ki And K X The At some of lotus that is the At some of lotus that is the At some of lotus that is the meaning of hello how you decided to tooth on more do do do do do do 102.1 decree from districts 512 hello hi me eggs tod not so young boys are used for your exams from sacha floor set up the Prohibition Prohibition Prohibition Prohibition Prohibition Prohibition Are You Can Work Order Follow Radhe-Radhe subscribe And subscribe The Amazing spider-man Idi Idi Idi Subscribe and subscribe the Video then and subscribe the Video then subscribe to the Page Mein Latk Controller Rakesh Vriddhi one rate like this That Aapne Side Sona Baby 19 2010 Huey Porn Pics And Subscribe To That Huey Porn Pics And Subscribe To That Aapke Smartphone Tuition Middle Man Late European From This And Didn't Late European From This And Didn't Know What Is The Meaning Of This This is the time - Vanchit Yovan Plus subscribe number road to Lord Mahavir and 119 and where it definitely smells youth debit the loot your left my needs and guess what needs and guess what is the maximum number subscribe to the Page if you liked The subscribe to the Page if you liked The Video then Love You Can Maa Hai - One Common Adhed Ko Hain Yes To Jab Road That Even The Great Subscribe Video Ko Hue Loot Not Been Gone To Cash Not Been Gone To Cash Not Been Gone To Cash ko CPI (M) CPI (M) came 20 minutes ago a Gautam festival subscribe kare subscribe to the Page if the Page the Page that till now friends and have been marked a that till now friends and have been marked a break in break in break in dancer Ruby PM David Cameron plus one luck to all the best all the best subscribe to this is this is the increase one break policy fixed Jai Hind Sacrifice - Who's First Of the subscribe this Video is not fixed 2019 Trick will be in a position to be a great desire will give you soe game modes and one item minimum that such mental updates will be on that such mental updates will be on that such mental updates will be on adhik na dharma loot loot increasing number of subscribe to subscribe contact number off do tag increasing in cases in the mid jabir wa peeth subscribe to aur dasha tay and addictive subscribe to Ko Ko Ko and Ashok Ji Hai and Shola Delhi-Noida Ashtamesh Videos Videos Videos Do Subscribe Must Subscribe | 2024-03-22 17:39:34 | 887 | LeetCode 887. Super Egg Drop | O(n * k) Worst case | O(k * log(n)) Avg Complexity |
|
fxwvVnBMN6I | hello guys welcome to another video in the series of coding today we are going the series of coding today we are going to do the problem which is called to do the problem which is called longest palindromic substring so given a longest palindromic substring so given a string s you have to return the longest string s you have to return the longest palindromic substring in s palindromic substring in s let's try to take an example to let's try to take an example to understand so we are given b a b a d we have to return which is the longest sub string that is a palindrome you have to return the longest palindrome in this let's take an example first of all what is a palindrome palindrome means if you read from the starting or from the end means you read either from right to left or left to right it's going to read the same for example this is a palindrome because b a b if you read this way also it's b a b if you read in this way also it is b a b right so that's why this is a palindrome now in this string the maximum possible is of length three because we can see that b a b is a palindrome there is no other substring which is of longer length that is a palindrome in this because see if you take b a b a d ah from the starting it will be b a b i d but you if you take from right to left it will be d a b a d and both are not same and so on right so in this uh you can take any of the answers for example babs answer abs answer but everything is of length three only maximum okay let's take another example let's say we have let's take a simpler string a b a a now in this you can see that there are many palindromes the character a alone is a palindrome the characters a a is also a palindrome uh you can see aba is also a palindrome but the longest one is of length phi and it's going to be this a a b a if you read from the beginning it's a a b a if you read from this side also it's going to be a a b a and both are same that's right it's a polynomial now if we think of the brute force approach to solve this problem we are going to first of all list down all the possible substrings and if you do that the time complexity will be of n square and then we will again i need to check whether each substring is a palindrome or not so we will keep two pointers start and end and one by one we'll keep comparing the characters we'll keep moving the pointers and so on right so again it will be o of n cube time complexity to check whether each substring is a palindrome or not to list the substrings it will be of n square because they are going to be these many substrings uh and then um [Music] to find out whether it's a palindrome or not the time complexity again will be multiplied by n so then it will be of n cube but we don't want this right we want to uh reduce the time complexity so the hint that they have given us see they have given us a very beautiful hint to solve this problem if you see the hint how can we reuse a previously computed palindrome to compute a larger parallelogram okay now it is much better right let's say let's say that i want to check whether the entire string a a b a is a palindrome or not okay now if i want to check this entire string right what i'm going to do i'm going to keep one pointer at the start one pointer at the end now a is equal to a so i will move my pointers okay so now my pointer comes here at this position again a is equal to a so i will move my pointers now i i reach in the middle and since this is a palindrome because all the characters are equal from both both the sides they are going to be same okay so this is where we can save some time complexity we can just check if the last characters are equal or not right so i'm just going to check the last character a is equal to a okay this is correct now the for the inner palindrome we can already store the answer and we can use this answer let's say i've already computed whether aba is a palindrome if aba is already a palindrome and i know that right let's say this is a palindrome i have already completed and i have stored it then i can just check the first and the last characters if they are equal and the inner string is a palindrome let's say a is equal to a the first character and the last character are equal and the inner string in a string in this case is a b a is a palindrome which i have already computed then i need not do o of n complexity to check whether it's a palindrome i can just do it in over one complexity i can just take the first and last characters so i i need to already compute the inner string so how are we going to do that now it's become very simple so let's start from the very beginning so for the inner palindromes i will already have to compute right let's say this is i this is j okay so i plus 1 and j minus 1 whether this is a palindrome or not i should have already computed right so let's say i have a matrix and i am checking if i want to find out the number of characters uh dp of ij is a palindrome or not if it is a palindrome how many characters how many how much length does it have right uh to be a palindrome so let's say my i is equal to 0 and j is equal to 4 right so i'm checking whether dp of 0 4 is a palindrome or not if it is a palindrome the length of this will be stored as the answer so i will just give a condition check if s of i s is the string if s of i is equal to s of j right that means here i am just checking whether a is equal to a right so this is equal to this so i can just store whatever value is there in my dp of i plus 1 and j minus 1 right so inner string the inner string will start from here and it will end from here plus 2 y 2 because i am adding two new characters right i am adding the first and the last character so dp of i plus one j minus one should already store three okay because the this a b a is of length three right so if this is of length three and i am adding two new characters to my parent room dp of 0 4 will be equal to 5 it's a palindrome of length phi obviously right the length of this string is 5 so this is a simple logic to solve this problem now how can we solve this problem so let us start from the very beginning we will have i and j values corresponding to where the string is starting so my i will correspond to where the substring is starting and my j is corresponding to where the substring is ending okay so let us build the matrix okay so this is a a b a this is my i i means where the string is starting this is my j where the string is ending okay now let me quickly try to do one thing draw lines here so that it is a little bit little bit neater and we can easily fill the values okay so we have to fill the values here so let us start from the very beginning okay let me also write the i and j values 0 1 2 3 4 okay similarly let me write the j values here this is 0 this is 1 this is 2 this is 3 this is 4 okay so let us start so we are going to start from the very first thing so this a is equal to this i is equal to 0 and j is also equal to 0 that means our string is starting at a and ending it let me let me write rewrite the string here so that it's much more clearer first we are at i equal to 0 j equal to 0 because you can see the inj values here that means our substring is starting at a and ending at a right so it is just one single character one now for all the single characters single characters are always palindrome right you read from the beginning or you read from the end it's always palindrome so single characters are palindromes of length one right so for all the single characters i can just store one so zero comma zero is one now let's say my i was here and j was here right so this i is equal to one j is equal to one this is also a single character so here also i can fill one okay let's say i move my i to two and j to two this b is also a single character it is also palindrome so whenever we have single characters they are definitely palindromes of length one so similarly i can just fill one in all the diagonal values because let's say starting at 2 ending at 2 the string starting at 3 ending at 3 it is just single character right so i can just fill 1 okay now let's fill the next values now you can note that we are filling values diagonally ok so this is another beautiful problem where we fill values diagonally okay let's continue it will be much more clearer when we discuss the entire problem now let us try to fill this box right so what does this box correspond to 0 comma 1 so i is at 0 j is at 1 right that means we are starting from here and we are ending here that means this substring this substring we are thinking what to fill in this substring now for this for palindromes of length 2 it is very easy right you can just check if the first and last characters are equal then it is a palindrome of length two if the first and last characters are not equal then it is of length zero that's it as simple as that okay so for panel rooms of length two also it's very easy you can just check you can easily just check if the characters are equal or not in this case a is equal to a right so the string a a is a palindrome so i can just fill two okay now let's go forward next box i have to fill this box a is starting at in this box in this box a starting at 1 b is ending at 2 that means here uh i is starting at 1 and j is at 2 that means this this string now a is not equal to b right that means this is not a palindrome so here i can just fill 0 very simple okay similarly let's go here 2 3 right so this is your i this is your j so i'm just checking this string now b does not equal to a that means it's not a palindrome so the length of palindrome is 0 because it's not even a palindrome as simple as that so we can just fill 0 here similarly let's check here for this box this character is a this character is also a so now again this is your i this is your j both are a right a is equal to a that means it's a palindrome and it's a palindrome of length two okay so we can fill two here and we can continue our iterations now let's try to fill this box okay so this is starting at zero and this is going to end at 2 so this is starting 0 so this is starting at the character a and this is ending at this character b right so this is your i starting at 0 this is your j ending at 2 okay so we are going to check whether this string is a panel now it's not a paladin you can just check the first and last characters you need not do anything just check first character is a right here you can see it is a and here this is b right a does not equal to b a does not equal to b so this cannot be a palindrome so we can just fill 0 here no need to just think anything if characters are not matching if the outer characters are itself not matching how can it be a palindrome that's it simply just write zero now we'll try to do it a bit more quickly okay because we want to fill out the values and write the code also now let's consider this and this you can see that here in this case i is at 1 and j is at 3 sorry we have to yes yes it's correct it's correct i is at 1 and j is equal to 3 right we are filling this box so in this case you are checking whether the string a b a is a parallel room or not so you are just checking the first and last character just check if a is equal to a it is equal right so now we will check whether the inner string is a parallel how can we check the inner string we have to just check this diagonal why this diagonal because let's see this is i this is j so the what is the inner box i plus 1 j minus 1 right so we are just going to check if the string starting at i plus 1 and ending at j minus 1 is a palindrome or not so if this is i and this is j i plus 1 comma j minus 1 will be equal to this box right so you have to just check the box on the diagonal below so if it is a palindrome then we can just get its length right so this is having a length of one now these two characters are matching that means we have got two characters and the inner box is a panel of length one so we can fill two plus one equal to three in this box okay as simple as that so we can just fill three here why are we filling three because we have to check whether this is a palindrome now the inner string is a palindrome of length one and we have got two extra characters so two plus one is equal to three so that is why it is a panel of length three okay now let's go to the next box we are starting here and we are ending here so i is starting at two j is ending at four right so we are checking whether b a is a pallet room now b is not equal to a right b is not equal to a so how can it be a panel room we can just fill 0 and move forward okay that's it let's just fill 0 and go forward now let's we have to fill this box so this box is starting at a equal to 0 ending at a equal to 3 so this is your i this is your j we are checking whether this is a palindrome or not okay so first let's compare the inner characters now if we see that if we see the sorry outer characters a is equal to a right so obviously this is awesome for us but when we check the inner string right when we check i plus 1 j minus 1 which is in a string when we check here we see it is not a palindrome so the inner string is not a palindrome a b is not a palindrome right a b is not a palindrome the inner string is not a palindrome we can see we have already checked that it is having a value of zero inner string is not a palindrome even if outer characters are same this cannot be a palindrome a aba is not a palindrome right so in this case the answer will still be zero because if the inner string if the inner string is not a palindrome if it if the answer is zero here it cannot be a palindrome okay now let's continue to this box so what is this box it is starting at i 1 and it is ending at j 4 right so we are checking if a b a is a palindrome ok again a is equal to a awesome but a is equal to a this is great but if we check for i plus 1 j minus 1 which is equal to this box this is also 0 so ba is not a palindrome right so even if the characters are equal if inside the string is not a palindrome that means that this has to be 0 there is no other option but this has to be zero right so both of these are zero now let's come to the last box it is starting at a equal to zero ending at a equal to four so this is your i this is your j i is zero j is equal to four now uh a is equal to a right outer strings is a paladin so we have to just check the inner string so you will check i plus 1 j minus 1 this entire inner string if it is a parallelogram of length 3. so inner string is a palindrome of length 3 you have got 2 extra characters out of character so 2 plus 3 is equal to 5 so this is a panel room of length 5 that's it simple so we can fill 5 here and we can just write 5 here and we can continue and return 5 is our answer so this is our entire logic now let's let's move forward to coding this okay so let's start coding this let me just quickly make it full screen so that's a little bit better okay so let's start so we have to build this matrix that we just discussed you can call it anything you like i am just calling it dp and let me initially take the size of the string so let's say the length of the string is equal to n so this is a matrix that is going to be built of n cross n size so let me just give the size in the matrix initially i am going to fill all the values as zero okay now let me start hydrating with this matrix we will also take this example that we just discussed a a b a a okay we have this current string so let us start iterating current okay by the way we are going to iterate diagonally right so let's quickly discuss how to iterate diagonally so first we are going to start with 0 0 then we are going to go to 1 1 then 2 2 i am writing the coordinates over which we are iterating right so we have to iterate in this manner first we have to start from the cell with coordinate 0 0 and go up to 4 4 right in the next iteration we are iterating this side diagonally so let me write the coordinates so when we iterate this side diagonally we are going to start at 0 1 and we are going to continue our iterations from 0 1 we are going to go to 1 2 then we are going to go to 2 3 then we are going to go to 3 4 right and then when we iterate in the third row we are starting at 0 2 and increasing i j so it becomes 1 3 then it becomes 2 4 and so on right so what are we doing what are we doing is we are starting where are the starting position first we are going to start iterating from 0 0 this is the first coordinate after that okay this is our i this is j okay in the next loop when we start our iteration we are going to start from 0 1 so then this is how your i this is your j starting i n j then you are going to start from 0 to this is your starting i this is your starting j okay this is for the outer loop this is what we are going to start with our i j and then each time you are just increasing i by 1 and j by 1 in the inner loop you are just increasing i by 1 and j by 1 every time right you are just doing in the inner loop you are just always doing i plus 1 j plus 1 so when you are starting the difference between i and j is equal to 0 when you increase the difference and make the difference between i and j s 1 then you increase the difference make the difference between i and j s 2. so we can use this difference variable in the outer loop initially the difference between your i and j is equal to 0 and then the difference difference less than n right so in our difference less than n right so in our case in the string if n is equal to 5 case in the string if n is equal to 5 the difference goes from 0 to 4 okay and the difference goes from 0 to 4 okay and then we can just increase our difference then we can just increase our difference so so so then we can take a inner loop inner so then we can take a inner loop inner loop is going to start with i equal to 0 loop is going to start with i equal to 0 and what will be your j j is going to be and what will be your j j is going to be simply i plus difference right so simply i plus difference right so because the difference between i and j because the difference between i and j is defined as j sorry the difference is defined as j sorry the difference between i and j is defined as difference between i and j is defined as difference so because of which so because of which this is going to be your condition right this is going to be your condition right now we can just move forward till when now we can just move forward till when can we go for when do we stop always we can we go for when do we stop always we are stopping when the j value becomes are stopping when the j value becomes equal to 4 right so this is your equal to 4 right so this is your stopping condition for the hydration j stopping condition for the hydration j value less than n is your stopping value less than n is your stopping condition condition now you can just increment i increment j now you can just increment i increment j that's it this is a simple that's it this is a simple inner loop okay now uh very simple logic inner loop okay now uh very simple logic if if i is equal to j i is equal to j i sorry i is equal to j that means we i sorry i is equal to j that means we are iterating in the first diagonal are iterating in the first diagonal right when i is equal to j you are just right when i is equal to j you are just iterating in the very first diagonal so iterating in the very first diagonal so for the very first diagonal the values for the very first diagonal the values are all going to be one it's very simple are all going to be one it's very simple dp of ij is just one because you have dp of ij is just one because you have single character single character as single character single character as only only length one right okay now we can go to length one right okay now we can go to else else let's say if difference is else else let's say if difference is equal to 1 equal to 1 in this case in this case you are hydrating over the second second you are hydrating over the second second it has become very messy let me do one it has become very messy let me do one thing let me erase this we have thing let me erase this we have understood how to declare the variables understood how to declare the variables okay let me try to make it a little bit okay let me try to make it a little bit less messy okay let me erase all this less messy okay let me erase all this okay okay so we have finished the first diagonal so we have finished the first diagonal we made all the values equal to one okay we made all the values equal to one okay very simple now let's go to the second very simple now let's go to the second diagonal second diagonal some values are diagonal second diagonal some values are going to be two which values if the if going to be two which values if the if if the strings if the strings if the starting and end positions right if the starting and end positions right if your i and j if your i and j characters are equal then it's going to characters are equal then it's going to be 2 otherwise it's going to be 0 very be 2 otherwise it's going to be 0 very simple as simple as that so we can just simple as simple as that so we can just check if check if s of i is equal to s of j in that case s of i is equal to s of j in that case okay so dp of i j i can just give is equal to if s of i is equal to s of j then it's going to be two otherwise it's going to be zero okay for the second diagonal also it's very easy now comes from the third diagonal onwards what do you have to do now also it's very simple let's take the next case from the third diagonal onwards you are going to just check for example let's consider this case this is starting at a this is ending at a here right your i is equal to 1 and your j is equal to 3 in in this box so you are just checking if these characters are equal if these characters are equal you are getting the value of the inner string okay so what we did we saw the left diagonal this is a palindrome of length one b is a palindrome of length one so to b we are adding two characters which we just found i and j so two plus one is equal to 3 that's why we fill 3 in that box so very simple again just check if s of i is equal to s of j right and the inner diagonal should also be a palindrome so how will you check dp of i plus 1 j minus 1 should be greater than 0 right it should be greater than 0 if it is equal to 0 that means it's it's not a palindrome so the outer character should be equal and the inner string should also be not equal to zero means this should also be a palindrome inner string is a palindrome of length greater than zero and outer strings are also outer characters are also equal if it is so then in that case you can just make dp of ij equal to d p of i plus 1 j minus 1 plus 2 okay that's it as simple as that otherwise d p of i j will just be 0 right so that's it these are the three conditions very simple conditions now we can just check for the answer every time right so here if this condition is equal to true right now after this we can give after these three conditions we can just store our answer we need to return the string that is a panel rule in our case we have to return this a b a string as our answer so let me declare string answer okay and let me also take one um variable that is going to store the maximum length of the palindrome that we got till now initially it is 0 right initially it is 0. now let me check if the palindrome that we have got right now right so if dp of ij if dp of ij is not equal to 0 if it is a non-zero value that means this is the palindrome right so the string starting at i and ending at j is a paladin okay so now i can check if if now what is going to be the length of this string the length of the string is equal to j minus i plus 1 because it is starting at i and ending at j let me take one example let's say you have the simple string aba right now it's a palindrome where is it starting at it's starting at the index 0 it is ending at the index 2 and what is the length of this the length of this is equal to 2 minus 0 plus 1 2 minus 0 plus 1 so the length of the string is going to be equal to 3 how are you getting the length j minus i plus 1 right so that is how you are getting the length j minus i plus 1 is going to give you the length right so this is going to be the length of us of a string so i am going to check if the length of the string that i have got currently is greater than the max length that i already have because i have to return the maximum length string as my answer right then in that case i can change the max length to be equal to j minus i plus 1 right and i can also change my answer what is going to be my answer my answer is going to be the string that is starting at the index i and it is of this much length so when you use the sub str function the first parameter is the index where the string is starting which is i and the second parameter is the length right it is the length so i can also give max length here right it is the length of the string that's it and finally after all this you can just return answer okay that's it this is a simple code let me just slide it this is the entire code let's run and see if it is working let me just submit and see it is working let me just submit and see if it's working for all the given test if it's working for all the given test cases so it's working it's working and thank you for being patient and | 2024-03-18 11:20:21 | 5 | Leetcode 5. Longest Palindromic Substring |
|
_xIBOUWEq1c | Subscribe Must Subscribe subscribe to subscribe and subscribe is surface it follows this path no extent of square into another attraction this result appointed Video subscribe hai e wish e left the room is too expensive Laddu Rupend subscribe Video subscribe and subscribe and subscribe subscribe and subscribe and subscribe selection is than in these cases to acid porn loot do subscribe and subscribe subscribe 9 subscribe 9 a case where extension and reflection of a case where extension and reflection of but s possible to find a place where one Can Find Video Subscribe Suves Into That And Deflection SP Leaders Will Tell U That And Deflection SP Leaders Will Tell U Behind Gif Worth RS Trending Was Loot Once In Bihar Values Will Be Old And Loot Once In Bihar Values Will Be Old And Will Just All The Condition Will Just All The Condition Will Just All The Condition condition and result navodaya vid oo e will put discus condition is china jai hind jai ho ki is election main is cord value day will return 90 is simrely famous condition and simply till which meeting night response is submitted. [Music] | 2024-03-22 16:23:06 | 858 | Mirror Reflection | Live Coding with Explanation | Leetcode - 858 |
|
YZdIwAEtgIY | hey what's up guys chung here again so today uh let's take a look at again so today uh let's take a look at this this lead code problem here number 729 lead code problem here number 729 my calendar one so which means there my calendar one so which means there will be my calendar two or three but will be my calendar two or three but today today let's take a look at my calendar one let's take a look at my calendar one first it's a medium problem i think i first it's a medium problem i think i kind of like this problem okay so let's kind of like this problem okay so let's take a look at the problem take a look at the problem uh you need to implement a my calendar uh you need to implement a my calendar class to store your events class to store your events and a new event has like a start and a new event has like a start and end which the the end is exclusive and end which the the end is exclusive and the start is inclusive basically and and the start is inclusive basically and then you have this book method so you cannot have two events that are overlapping to each other for example it gives you like this example here so first you have events 10 and 20 from start from 10 to 20 and then if the event can be added then you just you just returns true of course and then you add the event and the sec the next time uh it actually asks you to add event 15 to 25 but 15 to 25 has an overlap from 15 to 20 then which means you cannot add this event that's why you return false and the next one is 20 to 30 which is fine because 20 is 2 and 20 it's like it's not overlapping to each other then then you return true also you add the other event and yeah i mean that's the uh that's a problem right i mean i mean it's uh the naive approach is of course we just simply like uh basically i'm going to like talk about two approach this time first one is the uh the linear search and the second one is like the binary search which will be using a binary search tree to implement this okay so so first let's try to implement the naive solution which is going to be the so this self.books will be maintaining so this self.books will be maintaining all the all the other valid other valid book other valid other valid book in this like list here and every time in this like list here and every time um we have a start and end that's the um we have a start and end that's the event we simply loop through event we simply loop through look through all the events basically look through all the events basically for for book for s and end book for s and end in self and then for each of the existing book and then for each of the existing book we just we just we just need to check if that book has we just need to check if that book has an overlap an overlap has any overlapping part of is the has any overlapping part of is the current set start and end current set start and end with current book so the way we're doing with current book so the way we're doing the check is we simply do uh you know so the check is we simply do uh you know so to do the check right so to do the check right so s1 and e1 s1 and e1 s2 and e2 so what's the way to check s2 and e2 so what's the way to check if this any of this like the range or if this any of this like the range or the interval has any the interval has any overlapping so basically we just need to overlapping so basically we just need to to check two things to check two things so it has overlap when right when the if the start is smaller the start is smaller than the end and this start smaller than e right so basically we just check these two things as long as this start is less than this and the other star is at less than the other the other end then we know there's overlap what do we do we simply return false okay and uh if everything works fine we simply do a we simply like uh insert right let's do a self dot books dot append okay and then start and end and then we we return true yeah pretty simple right so let's try to run it yeah okay submit yeah pretty straightforward all right and then what's the time complexity here so let's say that it's going to be n square right because every time we add like so i mean an n is the uh that is the time and the time we uh we call this we call this book function right basically we have like uh yeah so let's say we call this book function end times and for every book for every bookings we need to look through all the existing books so the worst case scenario we're going to have like the o n square n times n right to loop through everything that's yeah so pretty straightforward right and yeah so pretty straightforward right and can we do it better can we do it better oh of course right we can do it like oh of course right we can do it like um a better way right a better way is to um a better way right a better way is to keep keep all the books all the soft books sorted all the books all the soft books sorted right i mean sorted means the uh right i mean sorted means the uh things since it cannot have the things since it cannot have the overlapping when i overlapping when i when i say sorted i mean i'm talking when i say sorted i mean i'm talking about restored by the about restored by the by the uh the start here by the uh the start here let's say we have 10 20 right and then let's say we have 10 20 right and then we have a we have a this is 35 to 50 this is 35 to 50 and then we have this like um 60 to 70. okay 60 to 70. okay so i mean if we have these things here so i mean if we have these things here right you right you if it's sorted all we need to do is we if it's sorted all we need to do is we just need to find just need to find let's say now we we have like let's say let's say now we we have like let's say we have like we have like what do we have let's say we have a 55 what do we have let's say we have a 55 and uh 55 and 60. okay now we want to insert this 55 and 60. all we need to do is just we can just simply do a binary search to find the position to insert this 55 and n60 okay in this case it will be somewhere here and we also check while we're doing the binary search if this one has any overlap with the existing range okay right [Music] so then then we will need like a data structure to maintain these things right uh i think in java there's like this data structure called the tree map where you can just which will be a perfect fit in this situation but since i'm using python uh python doesn't have such uh data structure so um so what we will do here is we will be implementing like a binary search tree by ourselves so how does this binary search search i mean we so the first item the first i mean we so the first item the first book event will always be our route so book event will always be our route so in this case in this case uh let me have another example here uh let me have another example here let's say the first booking will be uh let's say the first booking will be uh be from 30 to be from 30 to 250 so this will be our root 250 so this will be our root note and now now let's have like uh note and now now let's have like uh another one came in so so let's say that another one came in so so let's say that the next one is 10 the next one is 10 10 to 20. okay so basically every time 10 to 20. okay so basically every time when we see a note we we do a comparison when we see a note we we do a comparison basically first is if the uh if the if basically first is if the uh if the if the new the new if the new end is smaller then if the new end is smaller then then this node starts then we know okay then this node starts then we know okay so we need to go so we need to go to the left side to the left side and same thing for for the right side and same thing for for the right side right basically right basically and if the new if the new start is and if the new if the new start is greater greater than the nodes then the nodes end then than the nodes then the nodes end then we need to go to the right side okay so we keep going keep going left and and right and then we'll do a recursive call of that insert function until none of the conditions match right let's say we uh so in this for example this one basically if we see a 10 so in this case 10 20 is smaller than 20 smaller than 30 so which means we need to go to the left and basically okay then we see okay that does the left has a has a note if it has a note then we'll be will be recursively calling that that notes that knows like uh the insert method otherwise if this is empty we simply insert this one to 20. we insert this one to here okay and yeah and let's say the next one is 15 to 25 okay so let's see this is the the next one um okay then we we also start from the root because every time when we do the insert we'll start from start starting from the root now this time same thing right so because 25 is smaller than 30 then we will go to the the left side so then we will go to the the left side so that now the card node is 10 to 20 that now the card node is 10 to 20 and none of these and none of these two conditions is satisfied two conditions is satisfied because 25 is not smaller than 10 because 25 is not smaller than 10 and this 15 is not smaller it's not and this 15 is not smaller it's not greater than 20 right so we which means greater than 20 right so we which means so that means this one has an overlap so that means this one has an overlap with the current node with the current node we will just return false in this case we will just return false in this case basically basically basically we're not adding this node to basically we're not adding this node to our binary search tree okay yeah base i think that's basically the idea here and let's try to code these yeah things so for that let's create yeah things so for that let's create like a like a node structure here right class node structure here right class node and uh node and uh so we'll be we'll be having like a few so we'll be we'll be having like a few things here so for a tree node things here so for a tree node in this case we're gonna have to start in this case we're gonna have to start sorry um to have a node we need to have sorry um to have a node we need to have like the like the the constructor first okay in this case the constructor first okay in this case it's going to be self it's going to be self start and end right start and end right and then start equals to start self dot end equals to end and we're going to have a left and right right so at the beginning left and right are just none and then we will be needing like a none and then we will be needing like a insert method here dot uh basically we're trying to insert dot uh basically we're trying to insert a note a note right so what are we going to check here right so what are we going to check here because we're because we're trying to because we're because we're trying to insert this node to the current node insert this node to the current node here here right like i said we just do a check right like i said we just do a check basically if basically if um if note so the first case we use we're going going to the left so the going to left means uh if the if the notes end is smaller or equal than the uh self start right so and then we we will be we'll go to the lab we go to left basically if not note left okay basically if not note left okay if this node doesn't have a left we if this node doesn't have a left we simply do what we simply just simply do what we simply just assign this one to the left equals to assign this one to the left equals to the node the node and we and then we return true right and we and then we return true right because if there is nothing on the left because if there is nothing on the left that means that means it means that okay we can simply we can it means that okay we can simply we can safely safely append this node to this tree append this node to this tree okay else so if if the left node is not empty it's so if if the left node is not empty it's not now not now then what do we do we do a recursive then what do we do we do a recursive call okay call okay it was soft dot what it was soft dot what left south left yeah it's not this note okay south left yeah it's not this note okay uh uh basically if the current node if the basically if the current node if the current node left is not current node left is not empty right and then we do a self load empty right and then we do a self load self self dot labs dot insert dot labs dot insert okay so i think you guys uh i understand this so i think you guys uh i understand this right basically right basically if the left node is not it's not empty if the left node is not it's not empty we just keep trying we basically will we just keep trying we basically will we'll go we'll go to that we'll go we'll go to that that path and try to insert the node that path and try to insert the node under that under that under that cell under that node under that cell under that node okay and same thing okay and same thing and i'll save i'll see if it sound it's uh this and this one is the the right path so right path means if the node if and yeah if if self end is smaller than the then the note dot start then the note dot start right so if that's the case same thing right so if that's the case same thing we go to the left or the right side and we go to the left or the right side and self dot right equals to node and then self dot right equals to node and then we return true we return true else return else return self dot right dot insert node self dot right dot insert node okay and else like i said if none of okay and else like i said if none of things things none of the conditions mat are is math none of the conditions mat are is math are made then it means that we have a are made then it means that we have a overlap here overlap here we simply return fast uh root right and our root will be uh root right and our root will be equals to equals to none i think yeah so none i think yeah so and here what we will do is and here what we will do is uh basically if not uh basically if not self dot root right we simply do a self dot root right we simply do a self dot root equals to a node self dot root equals to a node um start and end um start and end okay else okay else simply re return we simply return self simply re return we simply return self dot dot root dot uh insert okay root dot uh insert okay so the insert will be a note so which so the insert will be a note so which means we'll be having like a note here again right start and end yeah i think that's that should do it uh yeah so yeah because here i forgot to yeah so yeah because here i forgot to return to return to yeah i think basically that's pretty yeah i think basically that's pretty much this right basically we're much this right basically we're maintaining we're maintaining like a maintaining we're maintaining like a binary search tree binary search tree with a key is like the start and end with a key is like the start and end so at any time so at any time if that the range is smaller than the if that the range is smaller than the current range we go to left otherwise we current range we go to left otherwise we go to right go to right we keep doing this a recursive call we keep doing this a recursive call right right until until we find an invalid node until until we find an invalid node which which means until this node has a means until this node has a overlap which means this is going to be overlap which means this is going to be the thing we check for for the the thing we check for for the overlapping here and then we we simply return fast so with this kind of our time complexity from o our time complexity from o n square to o and n square to o and log n right because the n is still the log n right because the n is still the end time but for each end time but for each insert since we're doing a binary search insert since we're doing a binary search instead of instead of n we'll be having like log n here n we'll be having like log n here okay yeah and space yeah space complex is it's space complexity uh i think it's the it's also on because we're maintaining like uh unsized unknowns okay the the size of n of a tree right for each node we will have like a yeah so and the tricky part for this is yeah so and the tricky part for this is just we have to do a recursive call just we have to do a recursive call of node itself that's why we'll be we of node itself that's why we'll be we need to uh need to uh we need to like implement this insert we need to like implement this insert function inside this function inside this inside this node class okay so so that inside this node class okay so so that we can do a recursive call we can do a recursive call on either the left or or the right note on either the left or or the right note okay um okay um yeah and i the rest is just like nothing yeah and i the rest is just like nothing right so right so if it's if it's not empty if it's empty if it's if it's not empty if it's empty we just we just return true and it re initiates the root return true and it re initiates the root otherwise we try to insert cool i think that's that's it that's pretty much it is what i want to talk about for this problem i hope guys you guys can learn this like how to implement this binary search tree yeah the the key point is the uh maintain maintaining a key so in this case start and end but for the others it might not it might be something else but the key the point is we have we need we need a key right we need the key value to tell us when to go left and when to go right okay and then the left and right of course and other than that it's just the build this left node or the right node and try to do this recursive insert so this is this part is just like a template just remember this one cool guys thank you so much for watching the videos and stay tuned see you guys soon | 2024-03-21 11:38:01 | 729 | LeetCode 729. My Calendar I |
|
L0SXlIr8rEs | hello and welcome to another video in this video we're going to be video in this video we're going to be doing bitwise and of a numbers range and doing bitwise and of a numbers range and in the problem you're given a left and in the problem you're given a left and right that represent a range and you right that represent a range and you want to turn the bitwise and of all the want to turn the bitwise and of all the numbers in that range inclusive so for numbers in that range inclusive so for example for five and seven you want to example for five and seven you want to Output four because five is represented Output four because five is represented like this this is six and this is seven like this this is six and this is seven so if you're not familiar with the so if you're not familiar with the bitwise and basically in order for the bitwise and basically in order for the bitwise and of a range to be a one every bitwise and of a range to be a one every every single number in that column has every single number in that column has to be a one so here this number is not a to be a one so here this number is not a one so this is zero this is zero also one so this is zero this is zero also and this is all one so one zero so this and this is all one so one zero so this is four for z z it's zero and for one is four for z z it's zero and for one and this thing it's and this thing it's zero and so you can't do this in a Brute zero and so you can't do this in a Brute Force like you can't just say like let Force like you can't just say like let me take every number from left to right me take every number from left to right and bitwise and because this is too big and bitwise and because this is too big of a constraint so this won't pass in of a constraint so this won't pass in linear time so you have to basically linear time so you have to basically kind of go back to this thing where if kind of go back to this thing where if you take the bitwise and of a bunch of you take the bitwise and of a bunch of numbers numbers if any if any like let's say we're if any if any like let's say we're looking at this bit here if any number looking at this bit here if any number has this bit set to zero then the has this bit set to zero then the bitwise and of everything with that bit bitwise and of everything with that bit will be zero so that's kind of what will be zero so that's kind of what you're looking for you're essentially you're looking for you're essentially looking for like for a given bit is looking for like for a given bit is there a number in my range that is set there a number in my range that is set to zero and also your result will always to zero and also your result will always be less than or equal to left because if be less than or equal to left because if left is some number let's just say is left is some number let's just say is like six and right is any bigger number like six and right is any bigger number or sorry six or sorry six and right is any bigger number like and right is any bigger number like let's say right has a one bit over here let's say right has a one bit over here and then whatever over here because left and then whatever over here because left doesn't have a one bit here this bit can doesn't have a one bit here this bit can never be one so you can't have a result never be one so you can't have a result bigger than left because if the right bigger than left because if the right number is bigger like I said um this bit number is bigger like I said um this bit for the left will always be zero so this for the left will always be zero so this bit in the result will always be zero bit in the result will always be zero and if this bit is the same for these and if this bit is the same for these two two numbers that means that in in order for numbers that means that in in order for the right number to be bigger um this the right number to be bigger um this has to have some bits over here on this has to have some bits over here on this left side on that the other one doesn't left side on that the other one doesn't and either way um whatever the left one and either way um whatever the left one has it will always be less so the idea has it will always be less so the idea so basically when you and two numbers so so basically when you and two numbers so if you and a and if you and a and b and you will never make a number b and you will never make a number bigger than a or b you will always bigger than a or b you will always either make the smaller of the numbers either make the smaller of the numbers or um something smaller than both of or um something smaller than both of them so that's kind of idea anding them so that's kind of idea anding numbers never makes a bigger number so numbers never makes a bigger number so if you and a bunch of numbers in a Range if you and a bunch of numbers in a Range your result will always be left or your result will always be left or smaller now there is like a solution in smaller now there is like a solution in the tutorial which I think is really the tutorial which I think is really weird and kind of hard to come up with weird and kind of hard to come up with using like some prefix thing so I'm using like some prefix thing so I'm going to instead um show a solution it's going to instead um show a solution it's a lot more intuitive that you can a lot more intuitive that you can actually come up with in a real actually come up with in a real interview so let's go through it so here interview so let's go through it so here I have a bunch of numbers this is just 0 I have a bunch of numbers this is just 0 to 15 um written in binary so this is to 15 um written in binary so this is like 0 one Toth and so on so what you like 0 one Toth and so on so what you can recognize is if you let's just take can recognize is if you let's just take a look at like one bit at a time so this a look at like one bit at a time so this rightmost bit this is the two to the rightmost bit this is the two to the zero bit you can see how it alternates zero bit you can see how it alternates so whenever we have a so whenever we have a one every other number goes to zero so one every other number goes to zero so so we know if we have a one here like so we know if we have a one here like let's just say we have some number let's let's just say we have some number let's say we have a number like any number say we have a number like any number with a one here this just means it's odd with a one here this just means it's odd right so let's say we have like nine we right so let's say we have like nine we know that and this is our know that and this is our left we know that if our right right is left we know that if our right right is 10 or more than this bit at the end will 10 or more than this bit at the end will always be zero right because whenever always be zero right because whenever it's a one the next number makes it zero it's a one the next number makes it zero so we can make this assumption that for so we can make this assumption that for the rightmost bit whenever it is a one if the greater or if num + one exists then the and of those will be zero right because if like if we're on this number here if this is our left if this ex if this is our right um then then these two numbers anded this bit right here will be zero right because like I said in order for this to be a one all of these have to be a one so whenever you have a one on the rightmost side if as long as you literally as long as the right doesn't equal to the left as long as it's bigger like any range here will always have one number with a zero over here right so the only way it's not is this now let take a look at the second bit so whenever we have a one at the the most it takes two numbers to turn that into a zero right so like let's say we're on this number let's say this is our left this number over here takes this bit and turns it into a zero right so at most whenever this is a one at most it takes two numbers like the two greater numbers right if this is like 0o 1 two three and so on right four five and all the way down to 15 so that's what you can recognize so for the second bit at most it's two but it might also be one like let's say this is our left and this is the bit here the next number turns that into a zero so we can recognize that for the second bit at most two numbers are needed right like farther down like if we have a left so to turn um needed to turn this into a zero so if we have a number let's say any number with the spit on like six we know that if we have eight as well then we know for sure that at the end this number this this like here will be zero because it takes two it takes two numbers farther down to turn into a zero now you might need less like let's say we're at seven if we have seven and eight then we don't even need two numbers down right so seven and eight also works and I'll take a look at the next bit and hopefully you're kind of getting to see the pattern so for this bit over here this third bit it takes at most four numbers to turn this into a zero right so this took at least at most one number this took at most two numbers this takes at least or at most four numbers right so if um let's say we are on this bit here so if we're on this four if left so let's say left is four if right is eight then this number will turn into a zero so you could see this is eight right here and this is left this would be left so you can see because because this is in the range right if you and four with eight this bit will be zero so we know for sure that if our left is X then if if right is x + 4 we know for sure that the third bit will be zero and then similarly going back to our first example so if left is X for first bit we know that if right is x + one then this bit will be zero for sure in the total land then for the second bit we know that if right is X+ 2 then we know for sure this bit will be zero the second bit will be zero then for the third bit it's X+ 4 and so on and so on and so on now the only other thing so you can literally do that right you can say like for sure I know that if I have some number from my left I can just figure out like okay the left most bit if I have l+ one then if I have L plus 2 then if I have L plus 4 then if I have L Plus 8 and so on you can just go down like bit by bit by bit and you know like the max range you need to to have that bit be a zero and you can do that literally bit by bit and we'll show that later but like I said you might need less numbers so for example if left is seven and right is eight here seven or actually let's label a couple more of these so six 7even 8 so if left is seven and right is eight we also have all of these bits on these two bits on that take at most two or four operations but here or not two or four operations you need at most four numbers down but here right is only one number down and this is still turning it into a zero so the thing you're missing here is for a given bit you need to figure out like what's the actual value right like this is two to the 0er which is 1 2 to the one which is two two to two which is four but whenever you have like let's say you're on this bit be if you just look at everything that's on the right so the right is 11 one one now when you add one all of these turn to zero so the thing we're missing here is not only like at most it'll be four but at least it will be four minus whatever the total is to the right of that bit right because when whenever that whole total is all ones when we add one that this bit will turn is zero whenever this total is this we have to add two for this to be zero whenever this we have to add three and so on so as a general equation we can write this down now so for a given left with some set one bit right in order for result the number that has to result the number that has to exist that has to be in the exist that has to be in the range is range is left plus two to the whatever bit we're left plus two to the whatever bit we're on right so two to the bit we're on on right so two to the bit we're on minus sum of the um all the bits before minus sum of the um all the bits before that so sum of all the bits to the right that so sum of all the bits to the right of it so sum of the bits to the right so of it so sum of the bits to the right so meaning now we can like basically meaning now we can like basically predict anything we want so let's kind predict anything we want so let's kind of use this to show some examples of of use this to show some examples of things so let's say we are on a number things so let's say we are on a number like five and we're on this bit like five and we're on this bit here and we want to know okay we have a here and we want to know okay we have a left of five so what what number has to left of five so what what number has to be in our ra range right what's the be in our ra range right what's the smallest number that has to be in our smallest number that has to be in our range for this bit to be zero well let's range for this bit to be zero well let's take a look at our equation so it's left take a look at our equation so it's left which is which is five plus two to the whatever bit we're five plus two to the whatever bit we're on so this is two to the two right cuz 2 on so this is two to the two right cuz 2 to the 0 2 to the 1 2 the two is 2 2 to the 0 2 to the 1 2 the two is 2 2 this is four minus the sum to the right this is four minus the sum to the right of this bit because basically whenever of this bit because basically whenever as this grows we need we need less as this grows we need we need less numbers to turn this into a zero right numbers to turn this into a zero right because once this is one one in this because once this is one one in this case then when we add just one this case then when we add just one this turns into a zero and if this was like a turns into a zero and if this was like a one over here and so on we'll go into one over here and so on we'll go into those but essentially yeah so this is 5 those but essentially yeah so this is 5 + 4 minus the sum to the right of the + 4 minus the sum to the right of the bit which is just bit which is just one so the number we need to have is 9 - one so the number we need to have is 9 - 1 which is 1 which is 8 so if our left is five and we have 8 so if our left is five and we have eight which right here if if our WR is eight which right here if if our WR is eight or bigger this bit will be zero in eight or bigger this bit will be zero in the final result and we can do this for the final result and we can do this for a couple more examples so let's use a couple more examples so let's use maybe like this bit here so like what maybe like this bit here so like what what number do we need over here let's what number do we need over here let's look at this leftmost bit here so our look at this leftmost bit here so our number here is nine so this is our left number here is nine so this is our left plus this bit value so this is 2 to the plus this bit value so this is 2 to the 1 2 3 so eight 1 2 3 so eight minus the sum of everything to the right minus the sum of everything to the right because like I said once this this sum because like I said once this this sum as it grows you need less numbers to as it grows you need less numbers to make this into a zero so this sum here make this into a zero so this sum here is just one so it's going to be 9 + 8 - is just one so it's going to be 9 + 8 - 1 so 9 + 7 which is 1 so 9 + 7 which is 16 so when we get to this 16 that's when 16 so when we get to this 16 that's when this bit turns into a zero and you can this bit turns into a zero and you can kind of see how that's going to work out kind of see how that's going to work out right because you see all these numbers right because you see all these numbers go down so this is 10 11 12 13 14 15 now go down so this is 10 11 12 13 14 15 now finally when you get to 16 it will be finally when you get to 16 it will be one and then this will be a zero so the one and then this will be a zero so the first number that you need to make this first number that you need to make this into a zero is 16 so you can basically into a zero is 16 so you can basically use this equation to go through all of use this equation to go through all of the bits in your left number and if your the bits in your left number and if your bits in your left number are zeros then bits in your left number are zeros then the bits in the result will also be zero the bits in the result will also be zero but if your bit is a one then you just but if your bit is a one then you just calculate okay what what's the smallest calculate okay what what's the smallest number in my range that I need for the number in my range that I need for the one to be my final result and if I have one to be my final result and if I have that then then you can just turn that that then then you can just turn that bit into a zero bit into a zero okay so let's look at this example of okay so let's look at this example of this five and seven to kind of show what this five and seven to kind of show what this is going to be so left is five this is going to be so left is five right is seven so we're going to do the right is seven so we're going to do the bitwise of the five so F bitwise of the bitwise of the five so F bitwise of the five is just five is just this and we we're going to like go this and we we're going to like go through this formula for this number so through this formula for this number so for this bit here we're going to check for this bit here we're going to check like what's the value so the value is like what's the value so the value is just one so the number we need our right just one so the number we need our right to contain or range to contain to make to contain or range to contain to make this value zero in the result is just this value zero in the result is just five plus the value of the bit which is five plus the value of the bit which is one minus the sum to the right of this one minus the sum to the right of this which is just zero so we need a six to which is just zero so we need a six to make this a zero in the result and we make this a zero in the result and we have a seven so six is fine so we'll have a seven so six is fine so we'll have our result down here we'll just have our result down here we'll just make it all zeros for now then we look make it all zeros for now then we look at our next one bit every zero bit in at our next one bit every zero bit in the left will be a zero bit in the the left will be a zero bit in the result because remember we can make we result because remember we can make we can never make our numbers bigger so now can never make our numbers bigger so now we look at this bit over we look at this bit over here and this this bit has has a value here and this this bit has has a value of um of um four actually I think I drew this four actually I think I drew this incorrectly yeah so instead of the a incorrectly yeah so instead of the a five is actually just this right yeah so five is actually just this right yeah so five is just this so this part was five is just this so this part was correct but this part so that here's a correct but this part so that here's a four and we basically check okay so we four and we basically check okay so we have a four so remember our formula is have a four so remember our formula is take the left plus the value of the bit take the left plus the value of the bit which is four minus the sum to the right which is four minus the sum to the right which is one and it makes sense right which is one and it makes sense right because if this was like this then it because if this was like this then it would take four numbers to make this would take four numbers to make this into a zero right because this is four into a zero right because this is four so the next time this is a zero would be so the next time this is a zero would be eight but as you increase this right eight but as you increase this right part you get closer and closer to part you get closer and closer to turning this into a zero because after turning this into a zero because after this becomes one one then when you add this becomes one one then when you add one this becomes a zero so as you add one this becomes a zero so as you add here you need less numbers to turn this here you need less numbers to turn this into a zero so that's why when this is a into a zero so that's why when this is a one you need one less number so that's one you need one less number so that's why it's this because it's going to go why it's this because it's going to go one then two then three then finally one then two then three then finally transform so 5+ 4 minus one so we have transform so 5+ 4 minus one so we have eight here and then we check do we have eight here and then we check do we have eight well right is only seven so eight eight well right is only seven so eight is not in the range so this one will is not in the range so this one will persist and this one will not because persist and this one will not because six is in the range so our final result six is in the range so our final result here will be here will be eight oh sorry four and you can see that eight oh sorry four and you can see that is the result here so that's kind of the is the result here so that's kind of the idea behind it um once you draw out idea behind it um once you draw out these numbers you can you can see how these numbers you can you can see how they alternate and then you can figure they alternate and then you can figure out well I just really need to know like out well I just really need to know like how long they take to alternate and how long they take to alternate and every bit will will take two to the to every bit will will take two to the to the power of the bit to alternate minus the power of the bit to alternate minus the total to the right because as you're the total to the right because as you're adding numbers to the right you're adding numbers to the right you're getting closer and closer and closer to getting closer and closer and closer to flipping that bit value and yeah so we flipping that bit value and yeah so we can code that can code that up so we're going to use a couple up so we're going to use a couple variables you can probably clean this up variables you can probably clean this up but it's fine we're going to have a but it's fine we're going to have a result variable we just set it to zero result variable we just set it to zero we'll have an i and the reason we'll we'll have an i and the reason we'll have an i because the way we're going to have an i because the way we're going to get every bit is we'll just um have a get every bit is we'll just um have a one and we're going to shift it some one and we're going to shift it some number of bits to get it to match up to number of bits to get it to match up to the right index so we'll start with the right index so we'll start with shifting shifting a one zero bits so one shifting shifting a one zero bits so one will be over here then we'll like shift will be over here then we'll like shift it one bit to get get it to be over here it one bit to get get it to be over here shift the two bits to get it to be over shift the two bits to get it to be over here and so on and this will let us um here and so on and this will let us um this will let us like set bits of our this will let us like set bits of our final result alternatively I guess you final result alternatively I guess you could like shift your result or could like shift your result or something but I'm not going to do that something but I'm not going to do that so we're going to have a right so we're going to have a right total because like I said when we get a total because like I said when we get a bit we are going to get the total to the bit we are going to get the total to the right and this total will only um grow right and this total will only um grow so like let's say our number is six like so like let's say our number is six like when we're on this bit it'll be zero when we're on this bit it'll be zero when we're on this bit it'll be zero when we're on this bit it'll be zero when we're on this bit we'll have like when we're on this bit we'll have like this value this value and then we're on this bit we'll add and then we're on this bit we'll add like another value and so on and so on like another value and so on and so on so this total is just like a cumulative so this total is just like a cumulative Su that we can keep track of and then Su that we can keep track of and then we're going to make a copy of our left we're going to make a copy of our left variable and we are going to get the variable and we are going to get the rightmost bit bit by bit and check if rightmost bit bit by bit and check if it's a one or a zero so for example if it's a one or a zero so for example if we have like five five is um this right we have like five five is um this right so we're going to say like let's get so we're going to say like let's get this value then let's shift it to the this value then let's shift it to the right so essentially get rid of this right so essentially get rid of this then let's get this value shifted to the then let's get this value shifted to the right and so on and so on you can right and so on and so on you can probably do this cleaner but this is probably do this cleaner but this is just how I did it so we're going to have just how I did it so we're going to have left or L is going to be a copy of left left or L is going to be a copy of left and we're going to say while this is and we're going to say while this is greater than zero let's just keep greater than zero let's just keep getting the rightmost bit so if L and getting the rightmost bit so if L and one that means that the bit is set so one that means that the bit is set so then we need to then we need to check what's the number that we need for check what's the number that we need for this to be zero in the result and check this to be zero in the result and check if it's in the range so we can say if if it's in the range so we can say if left plus oh we need one more variable left plus oh we need one more variable which is going to be the power of two which is going to be the power of two we're currently on so the power of two we're currently on so the power of two so this would be like two to the 0o two so this would be like two to the 0o two to the one two to the two and so on so to the one two to the two and so on so our power of our power of two will just be one for now and this is two will just be one for now and this is not like the power of two this is more not like the power of two this is more like two to the zero right so this is like two to the zero right so this is going to be two to zero then then every going to be two to zero then then every iteration of the loop we'll just iteration of the loop we'll just multiply this by two so if left plus multiply this by two so if left plus power of power of two minus the right two minus the right total is greater than total is greater than right that means that our right is not right that means that our right is not in the range right so if we calculate in the range right so if we calculate some number here like eight and our some number here like eight and our right is only only seven that means this right is only only seven that means this number is not in the range so if this number is not in the range so if this number is not in the range then this number is not in the range then this will be one in our result so we can will be one in our result so we can result or result or equal one shifted um shifted left I equal one shifted um shifted left I times so it'll start being shifted left times so it'll start being shifted left zero times so like if we have this zero times so like if we have this result basically one is going to start result basically one is going to start over here and when we or these together over here and when we or these together we'll get we'll get this and if we shift this one like one this and if we shift this one like one time let's say then the one will be over time let's say then the one will be over here and then when we order these here and then when we order these together we'll get this and so on if we together we'll get this and so on if we shift it twice it'll be over here if I shift it twice it'll be over here if I roll This Together get this so it'll roll This Together get this so it'll basically just set the correct bit in basically just set the correct bit in the the result then finally what we need to do result then finally what we need to do is we need to update our total so our is we need to update our total so our right total we will now add the one right total we will now add the one value here so we will say plus equals value here so we will say plus equals power of power of two because if this bit was a one bit two because if this bit was a one bit then this is going to add to our right then this is going to add to our right total of sum right so like if this was total of sum right so like if this was set we'll have the value here and then set we'll have the value here and then when we check the bits to the we check when we check the bits to the we check bits to the left of that we're going to bits to the left of that we're going to have this like total here so we're going have this like total here so we're going to add the power of two and then we are to add the power of two and then we are also going to multiply our power of two also going to multiply our power of two by two right because we'll have like two by two right because we'll have like two to the zero two to the one and so on so to the zero two to the one and so on so we can just multiply by two that way we we can just multiply by two that way we don't have to keep getting powers of two don't have to keep getting powers of two over and over although it doesn't really over and over although it doesn't really matter because like the most can be is matter because like the most can be is like 2 to the 30th so technically this like 2 to the 30th so technically this doesn't really save much like you can doesn't really save much like you can just do 2 to the 30th this is more good just do 2 to the 30th this is more good when you need to do two to like the when you need to do two to like the million or something this is more million or something this is more useful um so then we need to take our useful um so then we need to take our copy of left and shift it to the right copy of left and shift it to the right because we just used that bit we did because we just used that bit we did everything we needed and we need to everything we needed and we need to increment our index for the bit that increment our index for the bit that we're going to use to set in the result we're going to use to set in the result and finally return and finally return result and yeah I do think this is a lot result and yeah I do think this is a lot more intuitive than the uh let's see it more intuitive than the uh let's see it looks like okay I do think this is a lot looks like okay I do think this is a lot more intuitive than the solution more intuitive than the solution provided in the editorial because I provided in the editorial because I think that one they just have a huge think that one they just have a huge leap where like I don't think it's leap where like I don't think it's intuitive at all and people are posting intuitive at all and people are posting like I wouldn't come up with this in an like I wouldn't come up with this in an interview but I think this kind of thing interview but I think this kind of thing noticing this pattern that like my one noticing this pattern that like my one alternates every you know two to the X alternates every you know two to the X and then I can kind of get a pattern and then I can kind of get a pattern here so if you're not seeing these here so if you're not seeing these patterns just draw out a few numbers and patterns just draw out a few numbers and see if you can spot them and I think see if you can spot them and I think it's like pretty reasonable to come up it's like pretty reasonable to come up with this one then in an interview with this one then in an interview definitely not super easy um definitely definitely not super easy um definitely if if you're not familiar with bit if if you're not familiar with bit manipulation it's definitely going to be manipulation it's definitely going to be pretty tough like if you haven't done a pretty tough like if you haven't done a lot of problems but if you have done bit lot of problems but if you have done bit manipulation problems I think this is manipulation problems I think this is like not too bad um yeah so time it's like not too bad um yeah so time it's basically all one and space basically basically all one and space basically one cuz essentially we're just going one cuz essentially we're just going through the bits of one number right through the bits of one number right we're only going through the bits of our we're only going through the bits of our left number um one by one so that like left number um one by one so that like at most it's like 30 bits so that's why at most it's like 30 bits so that's why like this whole runtime stuff doesn't like this whole runtime stuff doesn't really matter because one Solutions just really matter because one Solutions just come down to like how many variables do come down to like how many variables do you use or some kind of stupid stuff so you use or some kind of stupid stuff so it's not super important as long as you it's not super important as long as you have a one solution and yeah let me know have a one solution and yeah let me know if any of this was confus confusing if any of this was confus confusing hopefully it was clear I don't know how hopefully it was clear I don't know how much depth to go into on bit much depth to go into on bit manipulation problems cuz I've done a manipulation problems cuz I've done a lot but um if this was confusing or if lot but um if this was confusing or if you need clarification anything just you need clarification anything just feel free to write in the comments and feel free to write in the comments and yeah thanks for watching and I'll see yeah thanks for watching and I'll see you in the next one | 2024-03-22 09:39:59 | 201 | LeetCode 201 - Bitwise AND of Numbers Range - Python |
|
5ACKq8nGQk4 | okay 368 largest his largest divisible was subset given a self distinct was subset given a self distinct positive integers find the largest positive integers find the largest subset such that every parent s sub I subset such that every parent s sub I and a sub J of elements in the subset and a sub J of elements in the subset satisfy as I mod a sub J 0 0 s sub j sy satisfy as I mod a sub J 0 0 s sub j sy 0 0 if the multiple solutions returning 0 0 if the multiple solutions returning return any subset is fine okay so 1 2 3 return any subset is fine okay so 1 2 3 give you a 1/2 or 1/3 because 23 are give you a 1/2 or 1/3 because 23 are relatively prime to each other right so relatively prime to each other right so you basically one a set in which kind of you basically one a set in which kind of I don't know how to phrase it in the I don't know how to phrase it in the mathematically way mathematically way mathematically way mathematically way precisely but I you want the largest set precisely but I you want the largest set such that all the numbers are factors of such that all the numbers are factors of other numbers in this set yes and I mean other numbers in this set yes and I mean just hmm trying to think of it with just hmm trying to think of it with sorting yeah yeah it means everywhere sorting yeah yeah it means everywhere sorting so I think first thing I would sorting so I think first thing I would do is sort to give the problem some do is sort to give the problem some structure I mean I think some of this is structure I mean I think some of this is intuition and maybe I could articulate intuition and maybe I could articulate it a little bit better I think the first it a little bit better I think the first thing is that some whoops my soda popped thing is that some whoops my soda popped but uh-oh but uh-oh tell me that's really going pop anyway tell me that's really going pop anyway so the first thing I would do is kind of so the first thing I would do is kind of sort of create structure in the problem sort of create structure in the problem then the intuition I have is that you then the intuition I have is that you want to go from you you want to create want to go from you you want to create these subsets from smaller to bigger and these subsets from smaller to bigger and and in this case you actually need to and in this case you actually need to create output I mean because you can create output I mean because you can always imagine a similar variant of the always imagine a similar variant of the problem in which you only need a number problem in which you only need a number then you don't need to but I think this then you don't need to but I think this actually it's just the longest path the actually it's just the longest path the longest path in the dag and as long as longest path in the dag and as long as you sort and sorting creates this kind you sort and sorting creates this kind of easier to digest of easier to digest directed miss of the graph so that you directed miss of the graph so that you can kind of create long as longest paths in a graph in you know what Yumiko in basically with dynamic programming and that gives you n square time I don't know if that's fast enough depending on how they raised it but that's what I mean so the sorting it actually gets dominated by it down anyway and the things you can do to make longest path longest path in a dag one faster than n square we may or may not explore that depending on calendar constraints I'm going to just did a naive one first and fix some diagram and if not that will kind of create the explicit graph a little bit to kind of speed things up even though sometimes it might not work depending on how dense the graph is so we'll see but yeah first bubble sort I always I always mix sort and sordid and all those things in five funds I'm just double checking okay well I mean okay I gave it a sordid okay well I mean okay I gave it a sordid input so that actually might not mean input so that actually might not mean anything let's test this real quick okay anything let's test this real quick okay so that looks okay cool so that looks okay cool as another web sorted we I'm wanting to as another web sorted we I'm wanting to know is that our in dynamic programming know is that our in dynamic programming sometimes don't need to kind of weeks we sometimes don't need to kind of weeks we construct a path in this case you do so construct a path in this case you do so we need to create a little bit of we need to create a little bit of structure before that so that's fine structure before that so that's fine though it may be maybe we could also though it may be maybe we could also clean it up later with there in theory clean it up later with there in theory more classes instead of it which we'll more classes instead of it which we'll talk about later I always get confused about x-range off I always get confused about x-range off by one or someone like that I'm just by one or someone like that I'm just checking checking now before I dip and taken to Nobu now before I dip and taken to Nobu tipper okay so this seems okay okay I just print this one I'll bring a okay I just print this one I'll bring a little slow and deliberate right now but little slow and deliberate right now but I definitely to kind of show up my I definitely to kind of show up my understanding of the API is to be honest understanding of the API is to be honest or like just not understanding but for or like just not understanding but for familiarly I spent a while and I need to familiarly I spent a while and I need to kind of practice a little bit I may be kind of practice a little bit I may be at some points to more streams but okay at some points to more streams but okay that looks good guys actually I guess that looks good guys actually I guess want me to set it up yes hmm yeah because yeah so I think one thing that I don't I think I jumped a little bit ahead is that if X my P is zero then like let's say I think I jumped ahead a little bit I think if there's a thing where like effects might be zero zero right then if there's a see that much a is zero zero there's a sort of a transitive property and that's kind of why this kind of works yeah and I think I just needed to point out that transitive property of modding because in this case this implies that C also in in because we sorted it beforehand I in in because we sorted it beforehand I can only go one way way I know that no can only go one way way I know that no qualm statement it it in theory goes qualm statement it it in theory goes either way but but because we create a either way but but because we create a structure where you know the biggest structure where you know the biggest number look yeah bigger number will come number look yeah bigger number will come later we only needed to worry about later we only needed to worry about things like this in one direction right so now we're checking that yeah if if the jave element can be extended with two by the element okay and then now we [Music] yeah yeah so just taking care of some edge cases but otherwise and now we have to be someone like that when it real quick mmm someone like that when it real quick mmm that's not quick let me also sort this that's not quick let me also sort this away first away first I guess doesn't an action need to be I guess doesn't an action need to be sorted sorted but uh okay that's two don't get along but uh okay that's two don't get along this way what is truly were just too soon mmm that's real I need to do one more maybe he doesn't know if I won that's fine no but also I need to pen not most but numbers of most that's how that goes I mean it's still off by one but it okay okay and this actually should not occur and and this actually should not occur and that's their literary civil elements and that's their literary civil elements and input because by default you should get by default you get yeah at least one case where this is true if I'm just more than zero so I was just thinking okay so okay that looks good I mean I'm a story for fun even though I think technically we don't need to but okay nice to try another couple of examples just in case okay you know God just had a bunch of random numbers I don't know what uh uh how Victor way can be I'm just uh uh how Victor way can be I'm just gonna punch little bit more and then gonna punch little bit more and then maybe yeah 312 okay so I mean we're maybe yeah 312 okay so I mean we're gonna cook to a quick some in gonna slow gonna cook to a quick some in gonna slow some it I guess not good okay so accept some it I guess not good okay so accept it so yeah I think for me I yeah so this it so yeah I think for me I yeah so this is the medium problem largest divisible is the medium problem largest divisible subset I mean I kind of solved it in 34 subset I mean I kind of solved it in 34 lines I think this one's a little tricky lines I think this one's a little tricky I think I mean the tag portion actually I think I mean the tag portion actually is pretty good I mean that it recently is pretty good I mean that it recently good for not reasonably a problem but good for not reasonably a problem but it's recently this reasonably standard it's recently this reasonably standard problem that should be in your arsenal problem that should be in your arsenal for better for worse I don't know how for better for worse I don't know how much I agree with is an individual much I agree with is an individual question but but dynamic programming question but but dynamic programming using dag that's you know this code is using dag that's you know this code is pretty standard and you have to pretty standard and you have to reconstruct the path which is maybe a reconstruct the path which is maybe a little bit less tender but still doable little bit less tender but still doable with some practice I mean the part that with some practice I mean the part that get me a little bit is that you have to get me a little bit is that you have to know a little bit about number theory to know a little bit about number theory to kind of get this one which is kind of I kind of get this one which is kind of I mean number theory is fun and I actually mean number theory is fun and I actually enjoy playing around number theory not enjoy playing around number theory not intent I'm a favor like programming intent I'm a favor like programming contest type of number theory from time contest type of number theory from time to time but these are things that like to time but these are things that like unless you're doing cryptography or unless you're doing cryptography or something like that like I don't know if something like that like I don't know if it's something that's obvious to people it's something that's obvious to people if you know it and maybe could if you know it and maybe could reasonably for reasonable reason for reasonably for reasonable reason for doing an interview but it's still kind doing an interview but it's still kind of feel like I don't know just something of feel like I don't know just something that people don't think about normally that people don't think about normally or even you know read about and I think or even you know read about and I think the key thing is noting that to be frank the key thing is noting that to be frank the transitive property that I kind of the transitive property that I kind of skipped through a little bit I brought skipped through a little bit I brought it up and obviously I didn't even prove it up and obviously I didn't even prove it or anything which you can kind of do it or anything which you can kind of do and and time but it's also something that like time but it's also something that like for me I'd call it intuition / practice for me I'd call it intuition / practice over a long time but I don't think over a long time but I don't think that's a fair thing to kind of assume that's a fair thing to kind of assume candidates with I don't know easier to candidates with I don't know easier to reasonably flew away like I mean or like reasonably flew away like I mean or like it does have good predictive power for it does have good predictive power for me in a sense then like a candidate me in a sense then like a candidate might take two minutes of it I go yeah I might take two minutes of it I go yeah I mean you know I play around with math mean you know I play around with math event and and they may think that then event and and they may think that then we'd get the transfer part of it very we'd get the transfer part of it very quickly or they may take you know twenty quickly or they may take you know twenty minutes doing something like just not minutes doing something like just not making the assumption and and it creates making the assumption and and it creates more work kind of for the interviewer to more work kind of for the interviewer to be like maybe poke them in the right be like maybe poke them in the right direction or maybe just give them a direction or maybe just give them a straight hand to be like hey this is a straight hand to be like hey this is a property that you should consider but property that you should consider but it's still like but for me if you have it's still like but for me if you have to do that and it doesn't really have to do that and it doesn't really have good protective power and I don't think good protective power and I don't think and that's like I said you're doing some and that's like I said you're doing some security stuff with cryptography stuff security stuff with cryptography stuff or something like that it's reasonable or something like that it's reasonable to expect anyone to you know given come to expect anyone to you know given come across in in a good way or even you know across in in a good way or even you know if you take algorithms 101 or whatever if you take algorithms 101 or whatever whenever this gets torn nowadays like I whenever this gets torn nowadays like I don't think that comes up that much I don't think that comes up that much I could be wrong and leave some comments could be wrong and leave some comments and I'm wrong but that's my feeling but and I'm wrong but that's my feeling but other than that in theory this is a good other than that in theory this is a good form other than there are the number form other than there are the number theory part only because because I as an theory part only because because I as an individual I do like taking a couple of individual I do like taking a couple of kind of fundamental pieces and kind of kind of fundamental pieces and kind of putting them together and maybe putting them together and maybe interesting ways and so that like like interesting ways and so that like like you know you don't want it out a problem you know you don't want it out a problem that has you don't want a problem that that has you don't want a problem that has like oh yeah you need to know max has like oh yeah you need to know max flow or some some like grad level flow or some some like grad level algorithm you know just to prove that algorithm you know just to prove that they know and know certain like almost they know and know certain like almost trivial right I mean you and to some of trivial right I mean you and to some of that you could debate how how how far to that you could debate how how how far to take that energy because to some people take that energy because to some people given any algorithm is trivial but given any algorithm is trivial but that's that's it besides the point I that's that's it besides the point I guess but maybe my mind yeah guess but maybe my mind yeah other than maybe this stuff about the other than maybe this stuff about the number theory I think taking a couple of number theory I think taking a couple of kind of cone quote off-the-shelf kind of cone quote off-the-shelf algorithms and can put them together algorithms and can put them together those are platforms I'd like to kind of those are platforms I'd like to kind of challenge my interviewee interviewees challenge my interviewee interviewees well yeah so yeah so I think I inferior well yeah so yeah so I think I inferior I mean I personally like this problem as I mean I personally like this problem as a result but I also would use this as an a result but I also would use this as an interviewer just because I mean I don't interviewer just because I mean I don't know like I said like I would never know like I said like I would never expect my interviewees to know number expect my interviewees to know number theory and this I don't know - vocals theory and this I don't know - vocals for it and it's very clear or maybe even for it and it's very clear or maybe even finance or something like that and they finance or something like that and they asked for very weird math things but uh asked for very weird math things but uh yeah so that's my opinion yeah so that's my opinion otherwise I mean otherwise like you know otherwise I mean otherwise like you know I solve everything with 34 lines and I I solve everything with 34 lines and I even five ways a little bit goes so so even five ways a little bit goes so so yeah so I think it's doable | 2024-03-24 11:32:33 | 368 | 368. Largest Divisible Subset (updated video in description) (Leetcode Medium) |
|
z22MfUJVxTE | drink more apple juice and eat more mango this video will quickly show you a technical question as well as possible answers i hope you subscribe and like that will really help me and my family and why should we drink more apple juice and eat more mangoes well because i noticed they are good for your brain god bless bye [Music] [Music] [Music] [Applause] [Applause] [Music] [Music] so [Music] [Music] [Applause] [Music] [Applause] [Music] [Music] please click subscribe thank you please click subscribe thank you thank you for watching god bless | 2024-03-21 11:27:44 | 126 | LeetCode 126: Word Ladder II (2 Solutions!!) |
|
Wf4QhpdVFQo | hey everyone welcome back and let's write some more neat code today so today write some more neat code today so today let's solve designing a linked list as let's solve designing a linked list as you may know a linked list is a pretty you may know a linked list is a pretty simple data structure where we have some simple data structure where we have some nodes and typically every single node nodes and typically every single node will have some type of value like one or will have some type of value like one or two in this case the values are integers two in this case the values are integers and also nodes will have pointers at the and also nodes will have pointers at the very least every node will have a next very least every node will have a next pointer which could be connected to a pointer which could be connected to a another node and then that node could another node and then that node could also have a next pointer that may not be also have a next pointer that may not be connected to a node and then this would connected to a node and then this would be considered the end of the linked list be considered the end of the linked list and we could also have a previous and we could also have a previous pointer going from every single node pointer going from every single node backwards and in the context of this backwards and in the context of this problem actually we have the choice of problem actually we have the choice of whether we want to use a singly length whether we want to use a singly length list or a doubly linked list and in this list or a doubly linked list and in this problem I'll be implementing the doubly problem I'll be implementing the doubly linked list because it's a bit more linked list because it's a bit more complicated and I think that's probably complicated and I think that's probably what qualifies this problem as being a what qualifies this problem as being a medium problem so I'll quickly go over medium problem so I'll quickly go over what exactly we're going to be what exactly we're going to be implementing and then we're going to implementing and then we're going to start so first we need a instructor for start so first we need a instructor for our linked list class that's pretty our linked list class that's pretty straightforward we also want a get straightforward we also want a get function which will get the node at some function which will get the node at some particular index and in this problem particular index and in this problem things are zero index so the first node things are zero index so the first node would be the zeroth position the next would be the zeroth position the next node would be the first position and node would be the first position and then two and then three et cetera et then two and then three et cetera et cetera just like an array now we do have cetera just like an array now we do have to deal with some edge cases in the case to deal with some edge cases in the case that this index doesn't even exist in that this index doesn't even exist in this problem if we were trying to look this problem if we were trying to look for index two well there is no a node at for index two well there is no a node at index two in that case we would return a index two in that case we would return a default value of negative one we also default value of negative one we also want to be able to insert nodes in this want to be able to insert nodes in this case at the head of the link list so case at the head of the link list so we're just given a value not a node we we're just given a value not a node we could be given the value 3 for example could be given the value 3 for example and we want to insert a new node with and we want to insert a new node with the value 3 at the beginning of our the value 3 at the beginning of our linked list so if this is our linked linked list so if this is our linked list we want to insert a new node here list we want to insert a new node here give it a value three connect it with give it a value three connect it with you know the next node and then this you know the next node and then this will be the new head of our linked list will be the new head of our linked list next similarly we have ADD at tail next similarly we have ADD at tail that's pretty much the same thing except that's pretty much the same thing except we would be inserting the node over here we would be inserting the node over here and then connecting it it would be the and then connecting it it would be the end of the linked list we don't have to end of the linked list we don't have to worry about edge cases with this one worry about edge cases with this one either but the next two are probably either but the next two are probably what make this problem a bit difficult what make this problem a bit difficult we have plenty of edge cases with these we have plenty of edge cases with these ones one let's start with ADD at index ones one let's start with ADD at index we're given an index and a value we want we're given an index and a value we want to insert a node so if this was called to insert a node so if this was called with index 0 and value three we would with index 0 and value three we would just be inserting at the head just like just be inserting at the head just like we did previously because in index 0 we did previously because in index 0 when they say we're inserting at this when they say we're inserting at this index we're inserting before the indexed index we're inserting before the indexed node so if we're given a value of zero node so if we're given a value of zero for the index we're inserting before the for the index we're inserting before the zeroth note so we would be inserting at zeroth note so we would be inserting at the head instead if for the index we the head instead if for the index we were given one then we would be were given one then we would be inserting before this node because this inserting before this node because this is zero this is one then we would be is zero this is one then we would be inserting in the middle over here and inserting in the middle over here and we'll talk about how we're going to do we'll talk about how we're going to do that but mainly we're going to be that but mainly we're going to be needing to update these pointers to needing to update these pointers to something like this now the other one we something like this now the other one we have is delete at index actually before have is delete at index actually before we move on to that if the index is we move on to that if the index is greater than the length the node will greater than the length the node will not be inserted so that is an edge case not be inserted so that is an edge case that we have to worry about so if we that we have to worry about so if we were given index of zero that's were given index of zero that's perfectly fine if we're given index of perfectly fine if we're given index of one that's fine and if we're given index one that's fine and if we're given index 2 that's also fine because we're 2 that's also fine because we're inserting before index two so we would inserting before index two so we would insert the node right here but if we insert the node right here but if we were given a value of 3 then that is out were given a value of 3 then that is out of bounds lastly we have delete at Index of bounds lastly we have delete at Index this one is a bit more straightforward I this one is a bit more straightforward I think than adding that index because if think than adding that index because if we're given an index 0 this one then we're given an index 0 this one then we're going to be deleting this node if we're going to be deleting this node if we're given an index one we're deleting we're given an index one we're deleting this node if we're given index two that this node if we're given index two that is out of bounds there's nothing to is out of bounds there's nothing to delete here in that case we don't have delete here in that case we don't have to do anything now let's move on to the to do anything now let's move on to the solution okay so now let's code it up solution okay so now let's code it up and we'll also be going through the and we'll also be going through the visualization of the solution as we do visualization of the solution as we do it because it's pretty helpful when it because it's pretty helpful when we're doing a lot of like pointer we're doing a lot of like pointer manipulation things can get kind of manipulation things can get kind of tricky first thing we want to do is of tricky first thing we want to do is of course create a node class where we have course create a node class where we have a next pointer and a previous pointer so a next pointer and a previous pointer so I'm going to go ahead and do that so I'm going to go ahead and do that so we're going to have a class I'm just we're going to have a class I'm just going to call it list node and it's going to call it list node and it's going to have a pretty basic construct going to have a pretty basic construct after where we're just given a value and after where we're just given a value and we're going to initialize that value and we're going to initialize that value and we can by default set the previous we can by default set the previous pointer equal to null and the next pointer equal to null and the next pointer also equal to null now let's pointer also equal to null now let's move on to the Constructor of the linked move on to the Constructor of the linked list class what I'm going to do is list class what I'm going to do is initialize two nodes actually a left initialize two nodes actually a left node which is just going to be given a node which is just going to be given a value of 0 to start with and also a value of 0 to start with and also a write node which is going to be given a write node which is going to be given a value of zero as well and I'm also going value of zero as well and I'm also going to connect these nodes together so left to connect these nodes together so left dot next is going to point at the right dot next is going to point at the right node and right the previous is going to node and right the previous is going to point at the left note so what we've point at the left note so what we've done so far is basically we've created done so far is basically we've created two nodes over here that are connected two nodes over here that are connected with each other the reason I'm drawing with each other the reason I'm drawing them so far apart is because these are them so far apart is because these are going to be our dummy node so we have a going to be our dummy node so we have a left dummy node and a right dummy node left dummy node and a right dummy node this is not required to solve this this is not required to solve this problem and this is not something most problem and this is not something most likely you'll come up with by yourself likely you'll come up with by yourself it's just a very very helpful technique it's just a very very helpful technique to deal with lengthless problems you'll to deal with lengthless problems you'll see why I'm doing this later on but see why I'm doing this later on but basically it allows us to not have to basically it allows us to not have to deal with edge cases because think about deal with edge cases because think about it when we have like an empty linked it when we have like an empty linked list like this one inserting into the list like this one inserting into the linked list is basically just creating a linked list is basically just creating a node and then having something point at node and then having something point at it and saying this is the new head of it and saying this is the new head of our linked list and when we have our linked list and when we have multiple nodes and we want to delete the multiple nodes and we want to delete the head of our length list it's different head of our length list it's different because we don't actually have to move because we don't actually have to move any pointers over here we're just saying any pointers over here we're just saying that now this is our new head but when that now this is our new head but when we have dummy nodes then every single we have dummy nodes then every single operation is dealing with a node that is operation is dealing with a node that is in the middle of the linked list so in the middle of the linked list so whether we're removing this node or whether we're removing this node or inserting a node everything is going on inserting a node everything is going on in the middle of the linked list we in the middle of the linked list we don't have to deal with any edge cases don't have to deal with any edge cases at the beginning or at the end and at the beginning or at the end and imagine our real doubly linked list imagine our real doubly linked list looks something like this where the blue looks something like this where the blue nodes are the actual nodes that have nodes are the actual nodes that have real values that we inserted into the real values that we inserted into the linked list and these are just kind of linked list and these are just kind of our dummy nodes now our get function our dummy nodes now our get function thankfully is pretty straightforward thankfully is pretty straightforward remember that this is our zeroth node remember that this is our zeroth node and this is our first note so when we're and this is our first note so when we're given an index we just want to return given an index we just want to return that value so we're going to start at that value so we're going to start at this node here and then keep this node here and then keep incrementing our pointer until we've incrementing our pointer until we've reached the correct index the way I like reached the correct index the way I like to do that is so I'm going to set to do that is so I'm going to set current equal to self dot left dot next current equal to self dot left dot next and basically while our current pointer and basically while our current pointer is non-null because we know we possibly is non-null because we know we possibly could go out of bounds and our index is could go out of bounds and our index is greater than zero the reason I'm doing greater than zero the reason I'm doing it this way is because I prefer to just it this way is because I prefer to just decrement our index by one every single decrement our index by one every single time the alternative is to just declare time the alternative is to just declare a second variable but I'd rather just do a second variable but I'd rather just do it this more simple way and we're going it this more simple way and we're going to be incrementing our pointer every to be incrementing our pointer every time so current is going to be current time so current is going to be current dot next now you might think can we just dot next now you might think can we just go ahead and return current.val not go ahead and return current.val not necessarily because we have to make sure necessarily because we have to make sure that we haven't gone out of bounds so we that we haven't gone out of bounds so we have to say if car is non-null and we have to say if car is non-null and we have to make sure that we haven't have to make sure that we haven't reached the end of the length list reached the end of the length list because remember the way we're doing it because remember the way we're doing it we have a dummy node what happens if our we have a dummy node what happens if our current pointer ends over here at this current pointer ends over here at this dummy node we definitely don't want to dummy node we definitely don't want to return that value that's considered return that value that's considered being out of bounds we're also going to being out of bounds we're also going to say if current is not equal to self dot say if current is not equal to self dot right and lastly our index has to be right and lastly our index has to be equal to zero because otherwise that equal to zero because otherwise that means maybe this Loop exited before we means maybe this Loop exited before we were able to reach the index that we were able to reach the index that we wanted to reach that would happen if our wanted to reach that would happen if our linked list was too small to delete this linked list was too small to delete this index that means this index did not index that means this index did not exist in that case we can return this exist in that case we can return this value otherwise we're going to return value otherwise we're going to return negative one okay so now moving on to negative one okay so now moving on to adding at head thankfully this is pretty adding at head thankfully this is pretty straightforward we hardly have to even straightforward we hardly have to even focus on the drawing in this case mainly focus on the drawing in this case mainly what we're going to do is given the what we're going to do is given the value that we're given let's say the value that we're given let's say the value is X we're going to create this value is X we're going to create this node we're going to take the left node we're going to take the left pointer and then move its pointer to pointer and then move its pointer to point at this new node and I forgot to point at this new node and I forgot to draw the previous pointer of this one so draw the previous pointer of this one so sorry about that but assuming that it sorry about that but assuming that it has a previous pointer point in here has a previous pointer point in here what we're going to do is move that what we're going to do is move that pointer to also point at the new node so pointer to also point at the new node so its previous pointer is pointing here its previous pointer is pointing here now and of course this new node that now and of course this new node that we're creating I'll make it blue because we're creating I'll make it blue because it's a real node we're going to be it's a real node we're going to be having it's an exponent point at this having it's an exponent point at this guy in its previous pointer point at guy in its previous pointer point at this guy pretty simple and we'll be this guy pretty simple and we'll be doing the exact same thing when we work doing the exact same thing when we work on ADD at tail which is basically going on ADD at tail which is basically going to be inserting a new node here where to be inserting a new node here where this pointer is going to go here and this pointer is going to go here and this is going to point back this is this is going to point back this is going to point here and this is going to going to point here and this is going to point backwards so I'm going to create a point backwards so I'm going to create a new node and call it just node and I'm new node and call it just node and I'm also going to do this I'm going to also going to do this I'm going to create a next value and a previous value create a next value and a previous value these are the next and previous nodes we these are the next and previous nodes we know the next node is going to be self know the next node is going to be self dot left dot next and we know that the dot left dot next and we know that the previous node is just going to be self previous node is just going to be self dot left so this way I think it makes it dot left so this way I think it makes it easier than having to use like these easier than having to use like these names because otherwise it can get kind names because otherwise it can get kind of confusing if we just focus on the of confusing if we just focus on the current node that we're inserting the current node that we're inserting the next node and the previous node it's next node and the previous node it's pretty simple so we'll have previous dot pretty simple so we'll have previous dot next point at node we'll have next dot next point at node we'll have next dot previous point at the node and we'll previous point at the node and we'll have the the node's next pointer have the the node's next pointer pointing at the next node and we'll have pointing at the next node and we'll have the node's previous pointer pointing at the node's previous pointer pointing at the previous node as you can tell this the previous node as you can tell this is pretty simple I even prefer to kind is pretty simple I even prefer to kind of condense them into a single line like of condense them into a single line like move these two into the same line and move these two into the same line and these two into the same line but that these two into the same line but that doesn't really matter and since this is doesn't really matter and since this is very similar to adding that tail I'm very similar to adding that tail I'm just going to go ahead and copy and just going to go ahead and copy and paste it the main difference though is paste it the main difference though is that our next node in this case is going that our next node in this case is going to be self dot right and our previous to be self dot right and our previous node is going to be self dot write dot node is going to be self dot write dot previous otherwise these pointer previous otherwise these pointer manipulations are pretty much exactly manipulations are pretty much exactly the same you could even create a helper the same you could even create a helper function if you wanted to to simplify function if you wanted to to simplify this now let's move on to the more this now let's move on to the more difficult ones add at index and delete difficult ones add at index and delete at index they're pretty similar we'll at index they're pretty similar we'll start with ADD at index so what we're start with ADD at index so what we're going to do is start our current pointer going to do is start our current pointer here at the first node and we're going here at the first node and we're going to keep incrementing until we get to the to keep incrementing until we get to the correct index that we want to be at now correct index that we want to be at now what happens if we reach this in index what happens if we reach this in index that's going to be fine because remember that's going to be fine because remember we're not inserting at this index we're we're not inserting at this index we're inserting before this index so if our inserting before this index so if our pointer ends here we're going to insert pointer ends here we're going to insert the node over here if our pointer ends the node over here if our pointer ends over here we're going to insert the node over here we're going to insert the node over here if the r pointer ends over over here if the r pointer ends over here we're going to insert the node here here we're going to insert the node here but if our pointer goes out of bounds but if our pointer goes out of bounds past the dummy node then we can't insert past the dummy node then we can't insert a node so what we're going to do set our a node so what we're going to do set our current pointer equal to self dot left current pointer equal to self dot left dot next while current is non-null and dot next while current is non-null and index is greater than zero I'm going to index is greater than zero I'm going to decrement our index that's very decrement our index that's very important we don't want to get stuck and important we don't want to get stuck and we're going to increment our current dot we're going to increment our current dot next well our current one or two the next well our current one or two the current dot next and now how do we know current dot next and now how do we know if we're actually at a valid position if we're actually at a valid position well first of all if our current pointer well first of all if our current pointer is non-null and our index is equal to is non-null and our index is equal to zero in that case what are we going to zero in that case what are we going to do well I'm gonna first copy and paste do well I'm gonna first copy and paste what we did up above because it's very what we did up above because it's very very similar so let's copy and paste it very similar so let's copy and paste it and first we're create getting a new and first we're create getting a new node with the value that we're given as node with the value that we're given as a parameter what's going to be the next a parameter what's going to be the next node in this case well current is going node in this case well current is going to be the next node so we're going to to be the next node so we're going to set this to occur what's going to be the set this to occur what's going to be the previous node in this case well it's previous node in this case well it's going to be Cur dot previous and then going to be Cur dot previous and then after that this is again pretty much the after that this is again pretty much the exact same you can see that once you get exact same you can see that once you get used to this you can pretty much just used to this you can pretty much just turn your brain off and then you know turn your brain off and then you know just go on autopilot now moving on to just go on autopilot now moving on to delete at index it's going to be very delete at index it's going to be very very similar to this with the main very similar to this with the main difference being that in our drawing we difference being that in our drawing we are actually deleting the node itself are actually deleting the node itself that our pointer lands at so if this is that our pointer lands at so if this is the node that we're deleting then we the node that we're deleting then we delete it if this is the node that we're delete it if this is the node that we're deleting then we delete it but what deleting then we delete it but what happens if our pointer ends at this happens if our pointer ends at this position at the dummy node well we're position at the dummy node well we're definitely not deleting the dummy note definitely not deleting the dummy note it's not a valid node so in that case we it's not a valid node so in that case we would not want to perform the delete would not want to perform the delete operation similarly if we end up out of operation similarly if we end up out of bounds we still don't want to delete bounds we still don't want to delete because obviously we can't delete in because obviously we can't delete in that case so now coding it up I'm just that case so now coding it up I'm just gonna you know know copy and paste this gonna you know know copy and paste this entire thing because it's again pretty entire thing because it's again pretty similar we're going to keep incrementing similar we're going to keep incrementing our current pointer until we get to the our current pointer until we get to the position then we're going to check is position then we're going to check is our current pointer non-null and not our current pointer non-null and not only that but is our current winner not only that but is our current winner not equal to self dot right because in that equal to self dot right because in that case we also can't delete and our index case we also can't delete and our index should be equal to zero that means we should be equal to zero that means we were able to actually reach the position were able to actually reach the position that we wanted to reach and at this that we wanted to reach and at this point we can perform the delete in this point we can perform the delete in this case the next node is going to be case the next node is going to be current dot next and the previous node current dot next and the previous node is going to be current dot previous just is going to be current dot previous just like we already have and then this is like we already have and then this is you know just making that insertion you know just making that insertion actually no we don't want to insert in actually no we don't want to insert in this case we want to delete how do we do this case we want to delete how do we do that though well first of all we that though well first of all we probably don't want to actually create a probably don't want to actually create a new node you can see that maybe you new node you can see that maybe you don't want to turn your brain off too don't want to turn your brain off too much so given a previous pointer and a much so given a previous pointer and a next pointer the way to delete a node next pointer the way to delete a node like this one is pretty simple we don't like this one is pretty simple we don't even have to update this node's pointers even have to update this node's pointers we just have to take the previous nodes we just have to take the previous nodes next pointer and change it and we also next pointer and change it and we also have to update the next node's previous have to update the next node's previous pointer and then change that as well pointer and then change that as well this next pointer will be pointing at this next pointer will be pointing at the next node and this previous pointer the next node and this previous pointer will be pointing at this note and then will be pointing at this note and then as far as we know this node doesn't even as far as we know this node doesn't even exist technically we do have a memory exist technically we do have a memory leak if we don't delete this node but we leak if we don't delete this node but we usually don't have to worry about that usually don't have to worry about that encoding interviews or on late code so encoding interviews or on late code so then moving back to the code what I'm then moving back to the code what I'm going to do is say next dot previous is going to do is say next dot previous is going to be equal to previous and going to be equal to previous and previous dot next is going to be equal previous dot next is going to be equal to next and that is pretty much the to next and that is pretty much the entire code I'm going to go ahead and entire code I'm going to go ahead and submit it to make sure that it works and submit it to make sure that it works and as you can see yes it does and it is as you can see yes it does and it is pretty efficient so I really hope that pretty efficient so I really hope that this video was helpful if it was please this video was helpful if it was please like And subscribe if you'd like to view like And subscribe if you'd like to view the entire code you can do so on neco.io the entire code you can do so on neco.io we should also have solutions for the we should also have solutions for the other most common languages thank you other most common languages thank you for watching and hopefully I'll see you for watching and hopefully I'll see you pretty soon | 2024-03-21 10:26:18 | 707 | Design Linked List - Leetcode 707 - Python |
|
RCbYIG6BPqc | Transactions, the columns in this are ID Country State which represents whether our transaction is confirmed or declined OK and next we have the amount and next translate what we have to do in the queries that we have For Math and Country, we have to For Math and Country, we have to For Math and Country, we have to calculate the total number of function, its name is function, its name is Platform Display now whatever we have, we have band. [Music] | 2024-03-25 18:09:11 | 1,193 | 1193. Monthly Transactions I |
|
3Ei6JGdoueg | hello guys let's look at this problem this is from leadcore sweetly challenge this is from leadcore sweetly challenge let's see how we can solve this problem let's see how we can solve this problem so problem statement says that we are so problem statement says that we are given in cities which are numbered from given in cities which are numbered from 0 to n minus 1 and there are roads 0 to n minus 1 and there are roads between these cities and there exactly n between these cities and there exactly n minus 1 roads and the connections are minus 1 roads and the connections are representing that there is a road from representing that there is a road from this node to this node that means if 0 & this node to this node that means if 0 & 1 are each is at Apple in this 1 are each is at Apple in this particular connections array then means particular connections array then means there is an edge directing from 0 to 1 there is an edge directing from 0 to 1 and similarly for 2 0 that means there and similarly for 2 0 that means there is an aid that acting from 4 to 0 what is an aid that acting from 4 to 0 what we need to do is we need to ensure that we need to do is we need to ensure that by adding some roads into this by adding some roads into this particular connections graph so that particular connections graph so that from starting from any node we can reach from starting from any node we can reach to node 0 so if we take this example to node 0 so if we take this example here what we were supposed to do is we here what we were supposed to do is we needed to ensure that if we start from 1 needed to ensure that if we start from 1 we should be able to reach this 0 and we we should be able to reach this 0 and we start from 3 we should be able to reach start from 3 we should be able to reach 0 and so on for each node so if we for 0 and so on for each node so if we for example let's consider 1 for now if we example let's consider 1 for now if we start from 1 we would never be able to start from 1 we would never be able to reach 0 because there is no age reach 0 because there is no age directing from 1 to 0 or directly or directing from 1 to 0 or directly or indirectly indirectly similarly for 3 and we can start from 2 similarly for 3 and we can start from 2 and reach till 3 but again as we came we and reach till 3 but again as we came we have seen previously that 3 cannot be I have seen previously that 3 cannot be I mean from 3 we can not reach 0 so mean from 3 we can not reach 0 so starting from 2 also we cannot reach starting from 2 also we cannot reach similarly from 5 we cannot go to 4 we similarly from 5 we cannot go to 4 we cannot go to 4 and from 4 4 so 4 is the cannot go to 4 and from 4 4 so 4 is the only road that can lead to 0 without any only road that can lead to 0 without any modification so the minimum number of modification so the minimum number of changes that we can do here is just as changes that we can do here is just as you can see the gray in the red ones we you can see the gray in the red ones we can just change the direction here and can just change the direction here and in that way we would be able to reach in that way we would be able to reach from each node to this node 0 similarly from each node to this node 0 similarly here also you can just consider in the here also you can just consider in the third example both of them are already third example both of them are already pointing to 0 so we can reach to 0 from pointing to 0 so we can reach to 0 from each of them each of them it is also given that this graph will it is also given that this graph will not have any cycle and it's not given not have any cycle and it's not given but yeah with n nodes and n minus 1 ages but yeah with n nodes and n minus 1 ages between them we can never have a 1 cycle between them we can never have a 1 cycle also yeah the total number of nodes are also yeah the total number of nodes are given to be 10 to power 4 there will not given to be 10 to power 4 there will not be any self connection so let's consider be any self connection so let's consider how we can solve this one so in the how we can solve this one so in the current state when the graph given graph current state when the graph given graph is a directed one it will be hard for us is a directed one it will be hard for us to do a DFS or BFS and try to find try to do a DFS or BFS and try to find try to reach from one node to other node but to reach from one node to other node but what we can do is we can try to add fake what we can do is we can try to add fake node fake edges to each of these node fake edges to each of these relations in the in the different order relations in the in the different order as well like for example if we were as well like for example if we were given 1 2 3 s we could we should add let given 1 2 3 s we could we should add let me choose a different color so that we me choose a different color so that we can distinguish we should add one more can distinguish we should add one more node start one more age starting from 3 node start one more age starting from 3 to 1 then here as well we can add one to 1 then here as well we can add one more node starting from 3 to 2 so that more node starting from 3 to 2 so that it becomes bi-directional so that it's it becomes bi-directional so that it's easy for us to start from one node and easy for us to start from one node and reach the other node let me just add for reach the other node let me just add for now and we'll explain you why we why do now and we'll explain you why we why do we need this so once we have all the we need this so once we have all the edges as a bi-directional lace we will edges as a bi-directional lace we will start our DFS starting from 0 and check start our DFS starting from 0 and check whether we can reach from 0 to all the whether we can reach from 0 to all the nodes nodes following the vacates or the original 8 following the vacates or the original 8 so if we are going to follow the so if we are going to follow the original age this means that if there original age this means that if there were no fake age we would have not were no fake age we would have not reached from that breaker node to 0 node reached from that breaker node to 0 node so for example if we were to reach from so for example if we were to reach from 0 to 1 then we know that using the 0 to 1 then we know that using the original age original age we know that it would not be possible to we know that it would not be possible to come back to zero without this fake age come back to zero without this fake age so in this case we would increase the so in this case we would increase the counter by one similarly now that we are counter by one similarly now that we are at one and we would check that because at one and we would check that because now we have made one zero to one as a now we have made one zero to one as a possible age we will not consider for possible age we will not consider for the previous one we will just simply the previous one we will just simply check for one now what happens for one check for one now what happens for one all the nodes which are achievable from all the nodes which are achievable from three from one we'll check for them so three from one we'll check for them so for one there is only one node which is for one there is only one node which is achievable from three and that is also achievable from three and that is also using the original one that means if using the original one that means if there was no fake age we would have there was no fake age we would have never reached back to one and then back never reached back to one and then back to zero starting from the three so in to zero starting from the three so in this case also we would need one more this case also we would need one more age so we will increase our counter to age so we will increase our counter to two and so let me just add these colors two and so let me just add these colors here so that we we can know so here we here so that we we can know so here we would need this one and also here we would need this one and also here we would need this one now we have reached would need this one now we have reached three and we have ensured that there are three and we have ensured that there are ages there are roads to reach from one ages there are roads to reach from one to zero and three to zero we will check to zero and three to zero we will check for three from three we would need the for three from three we would need the fake age to reach to two that means fake age to reach to two that means there was an age is existing from four there was an age is existing from four to from two to reach to three already so to from two to reach to three already so we would not increase this counter here we would not increase this counter here and then we'll recurse back in using the and then we'll recurse back in using the DFS in the DFS itself what are we going DFS in the DFS itself what are we going to do now is we are going to get further to do now is we are going to get further another branch of starting from zero so another branch of starting from zero so the other branch is also using the fake the other branch is also using the fake age to reach the next node that is 4 so age to reach the next node that is 4 so if we are not using the original node if we are not using the original node that means there was already an age that means there was already an age coming from this node to 0 and so we coming from this node to 0 and so we will not need to add another edge here will not need to add another edge here so we will just we have just ensured so we will just we have just ensured that they from 4 we can always is to 0 that they from 4 we can always is to 0 without adding any a strand H there now without adding any a strand H there now from 4 we have a direct originalist to 5 from 4 we have a direct originalist to 5 which is its child node so out not child which is its child node so out not child we can say Addison no and then what it we can say Addison no and then what it means is that we cannot come back from 5 means is that we cannot come back from 5 to 4 without this fake age so we would to 4 without this fake age so we would need one extra is starting from 5 till 4 need one extra is starting from 5 till 4 here so overall it added 3 nodes 3 and 3 here so overall it added 3 nodes 3 and 3 more edges to the existing a existing more edges to the existing a existing network so that from starting from each network so that from starting from each node we will be able to travel back to 0 node we will be able to travel back to 0 as we have seen that if we have this as we have seen that if we have this bidirectional networking instead of bidirectional networking instead of unidirectional network and if we start unidirectional network and if we start from 0 that means do a DFS from 0 what from 0 that means do a DFS from 0 what is the pattern that we are following is is the pattern that we are following is if we are following the original node to if we are following the original node to reach from 0 to the register node we reach from 0 to the register node we will add a cost will add a cost otherwise we will not add a cost so when otherwise we will not add a cost so when making this age I mean when making this making this age I mean when making this graph we can simply add a weight to each graph we can simply add a weight to each is like when we can add a weight from 0 is like when we can add a weight from 0 to 1 as 1 and then we can add a weight to 1 as 1 and then we can add a weight from 1 to 0 as 0 similarly from 1 to 3 from 1 to 0 as 0 similarly from 1 to 3 the weight of this edge should be 1 and the weight of this edge should be 1 and then for the fake one it should be 0 then for the fake one it should be 0 here as well starting from 3 to 2 it here as well starting from 3 to 2 it should be 0 and starting from 2 to 3 it should be 0 and starting from 2 to 3 it should be 1 so for each original age we should be 1 so for each original age we will add weight 1 and for each fake age will add weight 1 and for each fake age we can ID we can add a weight 0 so how we can ID we can add a weight 0 so how these add edges can be added and all these add edges can be added and all these fake weights that can be given to these fake weights that can be given to these ages let's take a look at the code these ages let's take a look at the code to understand it better so to understand it better so I have already solved this one and let I have already solved this one and let me just walk you through the code so we me just walk you through the code so we are given these connections and we can are given these connections and we can have a vector of array to create our to have a vector of array to create our to maintain our graph and this these are maintain our graph and this these are the edges the X denotes an age and zero the edges the X denotes an age and zero tells you the edge is diverging from X tells you the edge is diverging from X of zero is the source node and X of 1 is of zero is the source node and X of 1 is a target node for each edge so we have a target node for each edge so we have been given that there is an edge been given that there is an edge existing from X of 0 to X of 1 so we existing from X of 0 to X of 1 so we will simply add 1 at this particular will simply add 1 at this particular edge to our network 2 that means to our edge to our network 2 that means to our graph and as we have discussed that we graph and as we have discussed that we can we should add a cost of this way can we should add a cost of this way that means our weight of this age as 1 that means our weight of this age as 1 because this is the original one and because this is the original one and then we can add a reverse age that will then we can add a reverse age that will be a fake one with the cost 0 and then be a fake one with the cost 0 and then what we are going to do is we are going what we are going to do is we are going to do a DFS where we will maintain a to do a DFS where we will maintain a global answer and you will start the DFS global answer and you will start the DFS from 0 to 0 I mean 0 node and the parent from 0 to 0 I mean 0 node and the parent node should be 0 so we are going to do a node should be 0 so we are going to do a DFS and we'll check if the adjacent one DFS and we'll check if the adjacent one is not a parent 1 because now we have a is not a parent 1 because now we have a bidirectional is so it can lead into an bidirectional is so it can lead into an infinite infinite loop of child node infinite infinite loop of child node calling it's panic itself if so we will calling it's panic itself if so we will just ignore if this one is the parent just ignore if this one is the parent itself otherwise for all the adjacent itself otherwise for all the adjacent node we will check whether the second node we will check whether the second value that means if this particular age value that means if this particular age is a original one through which we have is a original one through which we have traveled to this particular adjacent traveled to this particular adjacent node then we will increase down our node then we will increase down our answer otherwise we will just keep it answer otherwise we will just keep it that that much only and do a DFS from that that much only and do a DFS from the adjacent node so yeah I hope I was the adjacent node so yeah I hope I was able to explain you guys please hit the able to explain you guys please hit the like button and subscribe to my channel like button and subscribe to my channel if you if you like my lord thanks for watching this like my lord thanks for watching this video guys | 2024-03-21 02:56:05 | 1,466 | Reorder Routes to Make All Paths Lead to the City Zero | Leetcode | Weekly challenge |
|
1nbb_RhqpdY | everyone welcome to day 24 january record challenge and today's question is record challenge and today's question is find the most competitive subsequence find the most competitive subsequence in this question you are given an array in this question you are given an array and a positive integer k you need to and a positive integer k you need to identify the maximum the most identify the maximum the most competitive sub sequence of size k that competitive sub sequence of size k that is present in this input array is present in this input array and what are the rules for identifying and what are the rules for identifying whether one sub array subsequence is whether one sub array subsequence is comp more competitive than the other comp more competitive than the other subsequence it is subsequence it is the it is of a lower value than the the it is of a lower value than the other one other one for example 134 is more competitive for example 134 is more competitive than 135 because the first portion that than 135 because the first portion that they differ they differ in the final number is 4 a 4 is less in the final number is 4 a 4 is less than 5 than 5 hence the first sub sequence is more hence the first sub sequence is more competitive competitive than the second one so what you need to than the second one so what you need to do do you need to identify uh the point you you need to identify uh the point you need to identify need to identify uh the most competitive sub sequence uh the most competitive sub sequence that is present in the input error that is present in the input error under the size k one standard solution under the size k one standard solution is to add is to add to generate all the permutations all the to generate all the permutations all the subsequence of size k subsequence of size k and then compare them all one by one and then compare them all one by one using a prior maybe using a priority using a prior maybe using a priority queue queue uh and finding out uh and removing the uh and finding out uh and removing the one that is of lower one that is of lower uh or lower uh this is less competitive uh or lower uh this is less competitive which is of more value and rejecting which is of more value and rejecting that and accepting the one which is of that and accepting the one which is of lower value and more competitive in lower value and more competitive in nature nature this is a start this is the first this is a start this is the first thought process that came to my mind thought process that came to my mind when i read this question but we when i read this question but we will not solve this by the standard by will not solve this by the standard by the brute force approach the brute force approach we will go by some other solution using we will go by some other solution using stacks stacks so let me just start the slideshow i have taken the similar example that was specified in the question two four three three five four nine six and the size that we are looking for on the subsequence is four now let's calculate the total length of element that are present in the stack one three one two three four five six seven eight eight so in the resultant subsequence uh we need to remove a four elements from this input array we need to remove four elements from this input array eight minus four and if we are able to identify those four elements which one to remove we will get our lowest uh lowest valued subsequence which will be most competitive in nature so let's start with a variable uh that will tell us how many elements we are actually intended to remove and we will use stack so this is the variable that is maintaining that count how many elements are to be removed and uh let's iterate through the input array we got two the stack is empty pushed it into the queue then we got four uh pushed it into the queue since it is of higher value i will push it into the queue then we got three and three is of the lower value than the peak element that means we found one element that can be rejected up front because we are interested in this in the numbers that are of lower value so we'll compare the peak with the current element it is lower we'll remove this element and we'll add three to it decrease uh the count that we are the number of elements that are actually to be removed because we have removed one element and the count becomes three we move ahead in the next iteration we got three three gets added we got five five get started and then we have four we we compare the top peak element with four it is of lower value it can be safely removed we add 4 and we decrease this count so now the number of elements that are to be removed is 2. you move ahead in the iteration you got 9 9 gets added to the stack and let's move ahead we got six we compare nine with six nine is of greater value can be safely removed we removed nine added six and reduce the count to one so what remains is one now and then what we have uh we have an increasing sequence in the stack so it's two three three four and six till the time uh till the time the the size of the stack doesn't become equal to k uh the input number that is given to us keep on removing uh the from the top top of the stack so we were intended to have only four elements so we keep on removing other topmost elements because it will always be in a decreasing fashion so we removed this and this becomes our answer two three three four so we identified the increasing subsequence of lowest value that is present in the stack and once we have that we removed all the elements from its top because it will be greater than a greater at the top and at the bottom we'll have the lower elements that are of size k and we can generate the answer using this these elements in the stack so i'll tell you i'll code in exactly the same fashion as i have talked about the algorithm and let's walk through the code now defining a new variable number of elements to be removed equals to nums.length integer st integer st new stack and new stack and let's start the iteration while the stack while the stack is not empty till the time is not empty till the time the stack is not empty and the number of the stack is not empty and the number of elements are to be removed elements are to be removed is greater than greater than zero is greater than greater than zero and nums and nums and st dot the top element of and st dot the top element of the stack turns out to be greater than the stack turns out to be greater than the current element the current element what we'll do we'll remove elements from what we'll do we'll remove elements from the stack the stack and we'll reduce the number of elements and we'll reduce the number of elements to be deleted because we to be deleted because we we found one element that is not the we found one element that is not the potential candidate potential candidate for our answer once we are done with for our answer once we are done with this this we'll add all the elements in the stack we'll add all the elements in the stack which is the primary step which is the primary step and in case the stack size and in case the stack size is still greater than k keep on removing is still greater than k keep on removing from the stack from the stack next we'll build an answer array new int and what will be the size side would be k for integer i equals to k minus 1 i is greater than equal to 0 i plus i minus minus anus of i will adding in the backward direction because the top most element would be there on the top of the stack st dot pop and once we are done with this i'll return n s pretty simple and looks good let me just submit this accept it let me just talk about the time complexity of this approach time complexity order of n since you are iterating through the input array once the space complexity is also similar order of n because at max the stack can hold all the elements uh all the elements that are there in my input array if they if all of them are in increasing fashion thanks for watching video hope you | 2024-03-20 10:50:46 | 1,673 | Find the Most Competitive Subsequence | Leetcode 1673 | Live coding session |
|
AwdhYMmpfEo | hello friends welcome back to the channel channel hope you are doing great if you haven't hope you are doing great if you haven't subscribed to my channel yet please go subscribed to my channel yet please go ahead and subscribe i have created bunch ahead and subscribe i have created bunch of playlists to cover various of playlists to cover various categories of the problems such as trees categories of the problems such as trees graphs dynamic programming graphs dynamic programming stacks queues linked list breadth first stacks queues linked list breadth first search search depth first search binary search and so depth first search binary search and so on please check them out on please check them out i have put all the playlists in the i have put all the playlists in the description description section below also i have uploaded the section below also i have uploaded the code for this particular problem to the code for this particular problem to the github repository you can get the github repository you can get the link from the description below this link from the description below this video video let's jump into today's problem course let's jump into today's problem course schedule schedule 4 there are a total of n courses you 4 there are a total of n courses you have to take have to take label from zero to n minus one some label from zero to n minus one some courses may have direct prerequisites courses may have direct prerequisites for example take course zero you have to for example take course zero you have to take take course one which is expressed as a pair course one which is expressed as a pair one 0. one 0. so basically there are 0 to n minus 1 so basically there are 0 to n minus 1 courses so courses so n courses basically and there are n courses basically and there are prerequisites for prerequisites for for some courses that's what it says for some courses that's what it says right some courses may have right some courses may have prerequisites so the prerequisites are prerequisites so the prerequisites are given as given as uh in in the form of like a two uh in in the form of like a two dimensional array one dimensional array one zero that means in order to take course zero that means in order to take course zero right you have to take the course zero right you have to take the course one first that's what it is one first that's what it is so you need to take course zero but so you need to take course zero but before taking zero you need to take before taking zero you need to take course course one right so after taking one then only one right so after taking one then only you can take course you can take course zero that's what that's what it means zero that's what that's what it means given the total number of courses and a given the total number of courses and a list of direct prerequisite pairs and a list of direct prerequisite pairs and a list of query pairs list of query pairs you should answer each for each query you should answer each for each query whether whether the course query of i0 is a the course query of i0 is a prerequisite of course i 1 or not prerequisite of course i 1 or not written a list of boolean the answers to written a list of boolean the answers to the given queries the given queries so please note that if a course a is a so please note that if a course a is a prerequisite of b prerequisite of b and if course b is a prerequisite of c and if course b is a prerequisite of c then course a is a predicate of c then course a is a predicate of c so basically there is a transitivity so basically there is a transitivity relation that we are relation that we are talking about here right so it says talking about here right so it says a is a prerequisite of b so that means a is a prerequisite of b so that means you you have to go through a you you have to go through a to go through b right and then b is a to go through b right and then b is a prerequisite of prerequisite of c right so so that means a is c right so so that means a is a becomes a prerequisite of c so it's a becomes a prerequisite of c so it's not a direct not a direct so you will not so you probably will be so you will not so you probably will be given with ac given with ac and b c that's it and b c that's it so from here you need to actually deduce so from here you need to actually deduce saying ac saying ac right so in the input this is only given right so in the input this is only given input is only this one right only up input is only this one right only up till this till this but we have to deduce this ac right but we have to deduce this ac right sorry a b this one a b is given and bc sorry a b this one a b is given and bc is given is given but you need to deduce ac is also a but you need to deduce ac is also a valid uh prerequisite saying in order to valid uh prerequisite saying in order to take take c you need to take a also that is also c you need to take a also that is also a prerequisite that's what it says right a prerequisite that's what it says right please note that if a course a is please note that if a course a is prerequisite of b prerequisite of b and course b is a predictive set of c and course b is a predictive set of c then course a is a then course a is a of c right so essentially c has of c right so essentially c has two prerequisites that is a and b two prerequisites that is a and b right but between a and b you should do right but between a and b you should do a first and then b right so that's what a first and then b right so that's what it is right it is right so there are transitive predictions so so there are transitive predictions so we just we just looked at only these three right so this looked at only these three right so this this could be going further this could be going further right this can be going further so you right this can be going further so you need to reduce need to reduce some of them will be given here but not some of them will be given here but not all of them right so all of them right so you need to deduce some of those uh you need to deduce some of those uh relationships right relationships right the prerequisite relationship right so the prerequisite relationship right so what we are going to do for this what we are going to do for this particular problem is we are particular problem is we are we are going to have some slight we are going to have some slight imagination so imagination so imagine all the courses are nodes in a imagine all the courses are nodes in a graph graph okay so all the courses so 0 to n minus okay so all the courses so 0 to n minus 1. so that means 1. so that means your graph has n nodes labeled your graph has n nodes labeled 0 to n minus 1 and prerequisite 0 to n minus 1 and prerequisite each prerequisite we are going to each prerequisite we are going to imagine it as a imagine it as a edge okay so that means there is an edge edge okay so that means there is an edge from from one to zero or in this particular case one to zero or in this particular case there is an edge from a to b there is an edge from a to b a b to c c to d d to e something like a b to c c to d d to e something like that so there are four edges in here in that so there are four edges in here in this case right this case right so so likewise there are so so likewise there are prerequisites we are going to imagine prerequisites we are going to imagine them as edge them as edge in the graph and each course is a in the graph and each course is a node in the graph right so those are the node in the graph right so those are the prerequisites for our prerequisites for our problem solving for this particular problem solving for this particular question okay question okay we are saying we are saying we will have we are saying we are saying we will have a graph where a graph where nodes are courses and edges are nodes are courses and edges are prerequisites right so let's go and try prerequisites right so let's go and try to understand to understand uh through an example so let's take a uh through an example so let's take a good example from whatever that is good example from whatever that is available okay let's go available okay let's go with example three this this actually with example three this this actually looks looks better graph than others the first or better graph than others the first or second right so second right so so we have essentially three courses so we have essentially three courses named zero one and two named zero one and two so one so one need to be taken first before taking need to be taken first before taking zero zero and 1 need to be taken before taking 2 and 1 need to be taken before taking 2 and 2 need to be taken before taking 0 and 2 need to be taken before taking 0 right so that's what it is right so that's what it is so how many relationships are given here so how many relationships are given here 3 so 1 2 so that means there is an edge 3 so 1 2 so that means there is an edge from 1 to 2 from 1 to 2 this is the one and there is an edge this is the one and there is an edge from 1 to 0 this is from 1 to 0 this is 1 going up so 2 to 0 so this is also 1 going up so 2 to 0 so this is also going to 2 to 0 going to 2 to 0 and these are the prerequisite courses and these are the prerequisite courses we will we are given with some queries we will we are given with some queries to answer whether those are to answer whether those are prerequisites or not prerequisites or not right so let's say let's say input is a b ah and bc right so with that we will have only this right so we are given with a b b c we came up with this graph right so let me extend just so that's a graph right for our graph so a to b b to c that's a graph and now the input was this one so now the query given we are given with query right so that's what we need to answer right so query if we are given with ac we should actually return true for this because a is a prerequisite of c by following this right so we written a true so that's what we have to return so the written what we are returning essentially here is the written list of boolean for given query so given there are some specific queries given for those queries we need to answer whether that is actually true a is a prequel of c so for this case yes we need to written true this is what we are going to deduce i said right so those things we are asked to deduce so in this particular case this is a graph so 1 is a prerequisite of 0 yes right so that is straight away since it is already given but 1 is a prerequisite of that is also true that is also given here right one is a prerequisite of 2 one is a prerequisite of 0 let's say let's say 0 1 is there right let's say 0 1 for this particular zero one right so is zero prerequisite of one right is zero predicted of one from this graph it doesn't look like right so we will return a false right so that's uh that's what we need to come up with so there are since there are n different nodes right and there could be any number of uh edges right between those nodes so minimum will be at least n minus 1 edges will be there right minimum but maximum could be anything so there will be any number of edges that could be possible so in this case we have three nodes but three edges are there right in order to have them connected we need to have at least n minus one edges but in this part like a particular case we have more than n minus one or n edges in this case right so now what we are trying to do is if there is a path from given one node to another node so in since we are imagining the courses as nodes and prerequisites as edges what are those queries we can transform we have to see whether there is a path from a to c here in this case so we input is a to b b to c and queries is ac right so that means what we are essentially trying to say is is there a path from given node to the given given node a to given node c so we we know we have a path from a to b right a to b and we know we have path from b to c we have b to c but do we have a path from a to c yes a to b and b to c so that is a path from a to c also right so this itself is a path to a to c right so we will say that's the reason why we will say true right so let's say if a query was ba right so that means is there a path from b to a no so we will written false right so if the query was ba then is there a path of course there is a path from a to b but is there a path from b to a no in that case we will say written false so this is what we need to come up with so we don't uh actually limit the relationships to the whatever they are given in the input but we have to come up with whatever the possible transitive relationships also that is one task and then answer the queries whether there is a path from one node to another node in other words in other words in the for the description right is there any prerequisite for prerequisite relationship between those two uh courses that are given as part of the queries so what we are going to do is for this particular problem we are going to employ a algorithm called floyd warshall's algorithm okay so floyd versus algorithm so this algorithm is known for ah finding the paths between more than one input node to more than one output nodes right so we are we are given with several queries right it's not just one query if it is a one query then we could go with a depth first search or best first search algorithm then we can just oh okay there is a path between two nodes or not and then be done with it right but we are given with bunch of queries not just one so in that case what we could do is we could do in a different approach also we could get a graph and then do uh depth for search for the queries queries of i 0 to i 1 is there a path between those two so we could go that way also right so we can do in two different ways build a and do depth for search do dfs and do depth for search do dfs between between the between between the query nodes right query nodes right that's one approach this is first that's one approach this is first approach we will say approach we will say and we this is second approach we will and we this is second approach we will say right so for flood versus one say right so for flood versus one one approach second one is building a one approach second one is building a graph and doing a dfs graph and doing a dfs between the query nodes so the the between the query nodes so the the reason why i did not reason why i did not uh showcase this uh the second approach uh showcase this uh the second approach in this particular uh video is in this particular uh video is if you are doing do dfs between two if you are doing do dfs between two nodes right you will need to do nodes right you will need to do uh you will probably need to traverse uh you will probably need to traverse the same paths the same paths multiple times so that's why that multiple times so that's why that algorithm becomes algorithm becomes much much slower than the flawed much much slower than the flawed versions algorithm versions algorithm right so we you need to possibly right so we you need to possibly do the dfs between those nodes so many do the dfs between those nodes so many number of times we don't know number of times we don't know how many of them right so we have to how many of them right so we have to cross through cross through so many nodes so for example in this so many nodes so for example in this particular tracer you particular tracer you start from a and go to b and then go to start from a and go to b and then go to b to c right b to c right but what if there is something called so but what if there is something called so from b from b to ah from b to d is there and from d to e is there from e to f is there and not just there and from d let's say there is something called g right so from g till h right so if there is that kind of graph is there then you will have to traverse through all those different nodes right you come to a to b now you for all the b nodes so b d so you need to traverse d c let's say the a to c it's not a to c but it is a to f let's say right in this case yes there is a path you will say true but if there if there is no path let's say right in that case you don't say it right so a to b and you transfer a to b to c a to b b to d d to e e to f d to g d g to h so you'll need to traverse so much of the graph for a given two set of phase so in some cases you might have to traverse the entire graph for given two nodes right one graph one thing could be so let's say a and h right so you need to traverse the entire graph almost to come to a conclusion saying okay a to h there is a uh there is a path right so for each dfs you will have to travel through all the n nodes right so you have to build a graph that is that is going to take some time and then you do dfs between each of those uh nodes in the queries right so it becomes a much slower approach that's the reason why i did not showcase as part of this video so we will look at the floyd versions algorithm as part of this video right so what is the floyd versus algorithm so this algorithm is known for count known for coming up with the paths between any two nodes in the graph if there exists of course right if there if there doesn't exist it doesn't come with the path but if there exists it it's going to come with a path okay there is a path and if you want if there are weights in the path or if there are like things like that right so in this particular case there is no weight it's just the connectivity whether they are just connected or not true or false but floyd warf's algorithm has much more applications to find out whether there is a minimum or the shortest path between any two nodes so you will be able to use the flawed versus algorithm to calculate the shortest path between two nodes two given nodes uh in a graph but imagine it's not if you are if you are given with only just two nodes and try to calculate the path right floyd warface is not the way to go just do a dfs you will be done with it because you all you have to do is just only one iteration of dfs but if you have many many things like in our queries array we have to come up our answer many queries not just one query if it is one query get done with dfs that's it but if there are more queries dfs is not feasible since you will have to traverse almost entire graphs through the dfs that's the reason why we will go with flood virtuals right so it is good application good algorithm to come up with the paths between any two nodes assuming you are doing that multiple times okay let's get into the algorithm and the code right so for this flawed versus algorithm i am going to declare a two dimensional array which is equal to the length of n by n right we have declared a boolean boolean ah we have declared a boolean boolean ah two dimensional array which is called two dimensional array which is called reachable reachable which is equal to n by n right so i am which is equal to n by n right so i am initializing all of them initializing all of them saying okay they are not able to reach saying okay they are not able to reach from one node to another node that is from one node to another node that is the initialization right the initialization right so now by going through the so now by going through the prerequisites prerequisites whatever they are there in this right in whatever they are there in this right in this fashion this fashion one zero i will going to mark those one zero i will going to mark those nodes nodes as true right so now i know as true right so now i know those courses are prerequisites imagine those courses are prerequisites imagine so i am talking in terms of the graph so i am talking in terms of the graph basically saying reachability and all basically saying reachability and all but in the graph but in the graph courses are nodes and prerequisites are courses are nodes and prerequisites are edges edges right so now reachability of right so now reachability of prerequisite to the course prerequisite to the course is true that means for this course that is true that means for this course that is a prerequisite i am marking it as a is a prerequisite i am marking it as a true right so that is the initialization true right so that is the initialization so still we are in the initialization so still we are in the initialization approach only approach only so we have initialized the reachable all so we have initialized the reachable all of them to false but only of them to false but only turn the prerequisites to turn the prerequisites to true so now we will go through the flood true so now we will go through the flood version right so that's the flood version right so that's the flood virtual we are going to go through virtual we are going to go through so it's a simple fl algorithm so so it's a simple fl algorithm so what it it's going to say is see if what it it's going to say is see if two nodes are already connected or not two nodes are already connected or not if two nodes are already not connected if two nodes are already not connected try to see if any name try to see if any name if you can connect through any neighbors if you can connect through any neighbors right right so the neighbors are not just so the neighbors are not just the same node or the other node but all the same node or the other node but all other n minus two other n minus two nodes are neighbors right so if you have nodes are neighbors right so if you have n nodes you have uh node one and node n nodes you have uh node one and node two two you are trying to see if they are you are trying to see if they are connected right so connected right so if they are connected you would have if they are connected you would have already got from the prerequisites array already got from the prerequisites array but now that we you don't have the but now that we you don't have the previous previous you've already filled it that means you've already filled it that means these two are not connected and you're these two are not connected and you're trying to find trying to find if there is a connection possible so you if there is a connection possible so you are going to take the help from are going to take the help from all the different neighbors of all the different neighbors of n1 and n2 and come up with if there is a n1 and n2 and come up with if there is a connection connection so that's what is flood version right so so that's what is flood version right so so you have the node i and j so that so you have the node i and j so that means means you have a node i and node j you have a node i and node j and you made sure they are not connected and you made sure they are not connected that's what i am saying so if they are that's what i am saying so if they are not reachable if they are reachable not reachable if they are reachable already already don't worry about it so they are don't worry about it so they are reachable you do not have to enter this reachable you do not have to enter this for loop or whatsoever right so flawed for loop or whatsoever right so flawed versions algorithm versions algorithm need not be applied since they're need not be applied since they're already connected but if they're already connected but if they're already connected means already directly already connected means already directly connected okay connected okay so when i'm saying already connected so when i'm saying already connected already directly connected already directly connected if they are not connected directly or if they are not connected directly or indirectly indirectly that's when we are going to enter that's when we are going to enter this if loop right so what we are saying this if loop right so what we are saying is is take a neighbor okay take a neighbor okay and see if that neighbor is and see if that neighbor is connected to node connected to node 2 so this is node 1's neighbor node 1's 2 so this is node 1's neighbor node 1's neighbor right so neighbor right so node 1 never that same neighbor with node 1 never that same neighbor with node 2 right so it's something like this node 2 right so it's something like this let me represent n1 right so there is some k node right so from k to n2 right so if there is a connection like that what we are going to say is yes if these two connections are true just put all this that result saying okay n one and two can be connected so this is a simple understanding of the flood versions right so now that if you go through this particular algorithm right you come up you have all the nodes which can be connected directly or indirectly from floyd balsals algorithm right so now after this execution you know in reachable what are reachable from i to j now what you're doing to do is you have just queries right just see if they are connected right if they're connected just put true if they are not connected put false that's it so now go through the length of the queue right and from and to so just check in the reachable if they are true or false just put it there in the answer finally written the answer that's it so that's how we are going to solve this particular uh problem with the help of the flawed virtuals algorithm let's go ahead and look at the time and space complexity right before going right so time [Applause] space time what is the time so we know there are n nodes right that is given in the description itself right so there are n nodes so in order to fill this particular matrix reachable we are taking n by n right n into n so order of n square that is the time complexity for this and that is the time complexity for this and here here we are going through all the we are going through all the prerequisites so plus prerequisites so plus m right m right plus m and plus m and so coming down we are going through so coming down we are going through these three for loop right so that these three for loop right so that will be r of n into n into n right will be r of n into n into n right so order of n so order of n n right and then we are going through n right and then we are going through the number of queries which we don't the number of queries which we don't know right so the number of queries know right so the number of queries i'll just i'm just going to call it as i'll just i'm just going to call it as order of q order of q right so that will be the total time right so that will be the total time complexity for this complexity for this particular algorithm if you say so order particular algorithm if you say so order of n of n n plus m plus order of n n n plus q so n n plus m plus order of n n n plus q so n square plus square plus m plus n cube plus q so ah m plus n cube plus q so ah for a given n ah for a given n ah assuming q is less than assuming q is less than n cube right then we will say the n cube right then we will say the maximum time complexity is going to take maximum time complexity is going to take is order of n cube is order of n cube right because floyd versus is order of right because floyd versus is order of enqueue we are trying to enqueue we are trying to find the paths between all the possible find the paths between all the possible nodes right nodes right so if you have n nodes you are trying to so if you have n nodes you are trying to see if there is a path from see if there is a path from any node to any node like like that any node to any node like like that that's why the floyd marshall's that's why the floyd marshall's algorithm is going to take algorithm is going to take order of n cube time so you could simply order of n cube time so you could simply say the time say the time complexity for this particular algorithm complexity for this particular algorithm will be order of n cube but will be order of n cube but it depends on the number of queries it depends on the number of queries right and the number of right and the number of uh prerequisites also so you cannot rule uh prerequisites also so you cannot rule out out m and q so one thing that you can rule m and q so one thing that you can rule out from here is since this is much out from here is since this is much better better bigger much smaller than order of n cube bigger much smaller than order of n cube you can possibly take this away you can possibly take this away right you can possibly take this away right you can possibly take this away and call this as a total time complexity and call this as a total time complexity so i am going to leave so i am going to leave like right there for that time like right there for that time complicated complicated let's go to space complexity so are we let's go to space complexity so are we using an extra space here using an extra space here so obviously we are using the reachable so obviously we are using the reachable that is the extra space that is the extra space and we are using m and is there anything and we are using m and is there anything yes we are using the answer array right yes we are using the answer array right so so right so we are good using right so we are good using order of n into n space order of n into n space right that is for the reachable right that is for the reachable and this is just a variable irrespective and this is just a variable irrespective of the length it does not matter of the length it does not matter and then is there any more space we are and then is there any more space we are using yes so q q is just a variable we using yes so q q is just a variable we don't we do not care much don't we do not care much but this is answer array we are using but this is answer array we are using right so what is the length of the right so what is the length of the answer array answer array since we don't know the number of since we don't know the number of queries it is going to have we are going queries it is going to have we are going to call it as order of q to call it as order of q right so the space complexity for this right so the space complexity for this particular algorithm is order of n particular algorithm is order of n square plus square plus q right so since we don't know q right so since we don't know q if q is like very minimal right we q if q is like very minimal right we just say order of n square but just say order of n square but since q is unknown yet we will keep since q is unknown yet we will keep right there right there order of n n plus q as the space order of n n plus q as the space complexity complexity right so if you have any further right so if you have any further questions for this questions for this particular problem right please post particular problem right please post them in the comment section below this them in the comment section below this video i will get back to you as soon as video i will get back to you as soon as i can i can i have posted the code for this i have posted the code for this particular problem to the github particular problem to the github repository repository you can find the link in the description you can find the link in the description below this video also below this video also all the playlists are also available in all the playlists are also available in the description the description you can check them out if you haven't you can check them out if you haven't subscribed to my channel subscribed to my channel please go ahead and subscribe and share please go ahead and subscribe and share among your friends as much as you can among your friends as much as you can please click on the bell icon so that please click on the bell icon so that you will be notified you will be notified about all my future videos thank you for about all my future videos thank you for watching i will be back with another watching i will be back with another video video very soon till then stay safe goodbye | 2024-03-21 02:53:10 | 1,462 | Course Schedule IV (Leetcode 1462) |
|
nSmUUo_lMfc | all right so this question is the skyline problem so uh if you have time skyline problem so uh if you have time just real quick but uh the problem is just real quick but uh the problem is pretty much uh simple so you have pretty much uh simple so you have building eye so uh building a ray right building eye so uh building a ray right i mean the beauty and eye is going to i mean the beauty and eye is going to represent left right and height okay so represent left right and height okay so i'm going to start the drawing so this i'm going to start the drawing so this is about 2 2 represent the left is about 2 2 represent the left and i represent the indian so starting and i represent the indian so starting andy and this is h which is high which andy and this is h which is high which is 10 right so this is pretty much the is 10 right so this is pretty much the idea right so idea right so so how do we actually need to do this so so how do we actually need to do this so uh the problem is that when we uh just uh the problem is that when we uh just imagine there imagine there there is a light like shiny from the there is a light like shiny from the left right left right so so basically it's like this basically it's like this and then um you want to know where is and then um you want to know where is the point the point uh uh top top of the top point of the top point uh uh where you where your building ends right where you where your building ends right so it definitely is right over here so it definitely is right over here right you're building right you're building top left top left point point and uh and and uh and end with here right and then you go over end with here right and then you go over here and this is not the top left here and this is not the top left building so the top left building is building so the top left building is right over here right over here and then you keep going and then you keep going and just imagine the light you would and just imagine the light you would just keep shining right something here just keep shining right something here right so just imagine there's a light right so just imagine there's a light okay and now you just keep going and okay and now you just keep going and then up right right over here is where then up right right over here is where the light ending right then keep going the light ending right then keep going keep going keep going keep on and then keep going keep going keep on and then here you hear the light and here's the here you hear the light and here's the light light keep going keep going this is light and keep going keep going this is light and this is the light right this is the light right so this is a solution so you want to so this is a solution so you want to return one two three four five six seven return one two three four five six seven point right two four six seven yes point right two four six seven yes so now we want to know how do we so now we want to know how do we actually do this question actually do this question so again so again i'm gonna draw this uh draw this again i'm gonna draw this uh draw this again so uh you need to return what you need so uh you need to return what you need to return this of this so this is the to return this of this so this is the main thing right and then main thing right and then uh uh but beforehand right we need to know how but beforehand right we need to know how uh we have to sort this building rate uh we have to sort this building rate based on the height right so um i'm based on the height right so um i'm going to have a list and then inside of going to have a list and then inside of this is an array and just pushing every single uh building array right building array i into the uh just i mean just just pushing the height okay so i'm going to name this off in array height right and then i'm going to just sort i mean sorry i'm going to push the in 1d array building to height when the when you're starting when the starting point i will say what the starting index right i will say what the starting index right start this with what negative height start this with what negative height index so i'm going to just push negative index so i'm going to just push negative h for the start index and the ending h for the start index and the ending with the positive h okay with the positive h okay so so this is actually helping me this is actually helping me at the end i when i want to at the end i when i want to when i want to find out why is the the when i want to find out why is the the the the minimum height i mean because we're minimum height i mean because we're pushing a negative right so minimum pushing a negative right so minimum height is going to be sorting it's going height is going to be sorting it's going to be from negative to positive right to be from negative to positive right so uh this would be the pretty so uh this would be the pretty uh helpful when you have a negative edge uh helpful when you have a negative edge and polish distinguished right and polish distinguished right so uh once again i'm gonna i'm going to so uh once again i'm gonna i'm going to just draw it again so just draw it again so um um so so i have a list of in right so list so so i have a list of in right so list of thing is pretty important of thing is pretty important also what also i need to sort also what also i need to sort to solve the h to solve the h which is height which is height uh based on what uh basically in this a uh based on what uh basically in this a bit based on the in this uh indexes bit based on the in this uh indexes right because the index 0 is what right because the index 0 is what in this zero is either what starting and in this zero is either what starting and or ending right so there are two or ending right so there are two scenarios right scenarios right when the index are not intersect right when the index are not intersect right so you want to say okay smallest two so you want to say okay smallest two graders okay so which is what uh graders okay so which is what uh a zero minus b zero right and but for a zero minus b zero right and but for what happens if the if index are the what happens if the if index are the same same if the a0 and b0 are the same we want to if the a0 and b0 are the same we want to know which one is what know which one is what which one we want to keep right because which one we want to keep right because because because uh uh there are actually two point you you you there are actually two point you you you want to know which one you should keep want to know which one you should keep and definitely not this one right and and definitely not this one right and then then when we when we add into the when we when we add into the list of array right list of array right we add a negative value right so this is we add a negative value right so this is what just imagine this is what just imagine this is uh uh just just imagine this is what negative just just imagine this is what negative alpha alpha so imagine this one is going to be one so imagine this one is going to be one negative 10 negative 10 this one is negative 5 something like this one is negative 5 something like this right sorry negative 7 so negative this right sorry negative 7 so negative 10 is that definitely less than negative 10 is that definitely less than negative 7 right so when we uh when we are 7 right so when we uh when we are comparing right we we want negative ten comparing right we we want negative ten first then negative seven seven seven first then negative seven seven seven seconds right so this is how it is right seconds right so this is how it is right so it's still going to be one so it's still going to be one uh the smallest two graders right uh the smallest two graders right so once we have it then we need a so once we have it then we need a priority queue so priority queue is priority queue so priority queue is going to be what going to be what sort based on the integer right and this sort based on the integer right and this is going to push is going to push my my height my index one so in this one my my height my index one so in this one is height is height in this video is what sorting ending in this video is what sorting ending right this is index and then this is in this one height all right and then i need to push p q into the height into the priority queue but in the priority queue it's going to be what the positive number so we will just push the negative value negative negative index one value into the pq and then when you remove that it's going to be about pop all the height positive all right because pq is always positive number right so this is a tricky point and then we basically just keep comparing right and then we will definitely have one we will definitely have a current maps and pre-maps so pre-maps and maps will start pointing zero right starting from zero and if if i have if i have a send uh send x i mean sorry same coordinate i i i'm not worried about but if i have different height right i need to update right so this is 10 so when my current current max current max that's not equal to the pre max right but that's not equal to pre max i need to work i need to add a coordinate add a coordinate which is for starting with the height right so the height is for permanent flat so i would say uh p0 something at least right i would say current into my list of lists and then i will just what i will have to update my free max to the furnace because this transit because this one is updated and this is pretty much it so let me stop recording and then follow along and this is going to be a little bit difficult difficult for sure but don't ever give up so list of this and i definitely need to return result and i definitely need to return result right so i need a list of in right so i need a list of in array right i'm gonna go going to call array right i'm gonna go going to call height height and then i will definitely traverse and then i will definitely traverse my building my building i'm just called b beauty and then i'm going to just add and pass in the video so and pass in the video so the the index 0 is definitely what index 0 is definitely what it's definitely going to be a negative it's definitely going to be a negative value for e2 okay and hi [Music] comma positive b2 right comma positive b2 right so so the zero index is going to be one left the zero index is going to be one left starting and then starting and then this one represents ending this one represents ending uh and there's two represent the height uh and there's two represent the height right so once i have it right i'm gonna right so once i have it right i'm gonna sort based on the height and then i'm going to sort based on the height with the index so if if they are if a if a 0 is equal to b 0 right this is going to be this is going to be based on height right height smallest right so if they are not equal is so much easier so i'm going to say is so much easier so i'm going to say a0 minus p0 but if they are equal i'm a0 minus p0 but if they are equal i'm going to still going to give smallest going to still going to give smallest values values so imagine imagine just imagine so imagine imagine just imagine a0 and b0 so this is what a0 and b0 so this is what this is a0 this is a0 this is also b0 right this is also b0 right and and uh uh this is definitely like maybe the 10 this is definitely like maybe the 10 something like this and this is like something like this and this is like negative seven right negative seven right because we push a negative value into it because we push a negative value into it right and then if if they are not equal right and then if if they are not equal uh it's going to be like this case right uh it's going to be like this case right something like this something like this all right so smaller two greatest so all right so smaller two greatest so this definitely work but this definitely work but uh if they are equal if that equation is uh if they are equal if that equation is is this case right so i need to still is this case right so i need to still comparing as small as the greatest comparing as small as the greatest all right so let's just keep doing this and this is going to be sort based on and this is going to be sort based on the the height right and again this is going to be my mistake this is because i want to push a positive number no matter what into it right and initial value this one is zero and i have a pre max it's gonna be zero i need to traverse i'm sorting um my my sorting height right so i'm gonna say h hi all right so if mine so okay so i'm going to say i another index case here right and height is going to be h1 right i'm saying this right uh actually i cannot say height anymore because i put it pretty well okay sometimes right it's less than zero which is the it's less than zero which is the starting that's right which is which is starting that's right which is which is the starting index right the starting index right uh uh i i i push the negative value into it i i i push the negative value into it right so which is starting this i'm right so which is starting this i'm gonna gonna i'm going to i'm going to push this into the party here so p q push this into the party here so p q so since it's negative value right i so since it's negative value right i need to need to convert it right so i need to say convert it right so i need to say negative h 1 negative h 1 right right which is negative 4 right actually i don't want my timing i don't want to create a local variable so i'm just going to do like this so this is what you add you add a negative negative which is positive value right and then if not so if this is not a negative value which means what is ending right and this is already positive right so i can just say that which is po h1 right okay now i need to know like is my current max is equal to p q p so i'm actually keep checking so uh just imagine so this is high of 10 so right 2 negative 10 and then this is 3 negative 15 and then what seven positive fifteen nine ten so in the priority queue i have a positive value only so i will initially have zero and i will have one i will have ten right and then i will have 15 right i really want so i really want so when i push the proof when i add a pq when i push the proof when i add a pq the the first interval so the pq.p is the the first interval so the pq.p is definitely 10 right because it's sorted definitely 10 right because it's sorted right right i'll sort it so 10 i'll sort it so 10 so i would say current mass equal to 10 so i would say current mass equal to 10 so 10 that's not equal to probability of so 10 that's not equal to probability of pre-max right pre-match was 10 i pre-max right pre-match was 10 i premixed was zero right zero doesn't premixed was zero right zero doesn't equal to ten right so i need to add this equal to ten right so i need to add this point into this right three max uh i will have to add a result so it's uh i will have to add a result so it's something like this something like this uh this this was right i would say b uh this this was right i would say b uh h h u right comma uh h h u right comma comma current max comma current max i'm i'm adding the coordinate coordinate into it adding the coordinate coordinate into it right and then right and then once i have it once i have it right right i need to update my pre-maps i need to update my pre-maps into my current right so if there's into my current right so if there's another point which is starting at the another point which is starting at the same current height current current same current height current current height of a diagram so i'm not going to height of a diagram so i'm not going to add in right because this is my top left add in right because this is my top left right just imagine if there is a point so this is my top left so if there is a point right over here i'm not going to add i'm not going to add this accordingly into the result because this is not this is not the top top left in the diagram and this is going to be pretty much the solution so just keep traversing traversing traversing so you're adding you're removing you're adding removing and then you pick and to check the let me run it it might be a error somewhere oh no error okay something all right so let's talk about the timing space so this is what this is a space this is also a space this is space but it's constant so the space is going to be these two so it's going to be all of them right the space is all of them so time is just time this is time this is time this is also time so the time this is also b b represent end of the building and this is going still going to be what all of uh all of b log b is sorting right b log b and this is what this is uh you determine the height right and i would say it's shorter uh shorter than this one right collection dot store because for this one you have every single interval and this one is only for height and in this one this is all of all of h all of h represent this one right and in the remove it's going to be log uh it's going to be logan right so you can say although all of h logan and i mean sorry h is actually equal to n right and represent at the end of the building so it's going to be unknown and then space is all of n so this is pretty much my solution solution and it's a little bit it's a little bit hard to understand and stop holding and you have to know the logic right so this is a tricky part and i i read over all the people answer so i kind of like struggle a lot for this question and this this is my my solution um how i understand all the people answer | 2024-03-22 10:47:37 | 218 | LeetCode 218 | The Skyline Problem | Sweep Line | Java |
|
AieeTBP9YqQ | hey hey everybody this is larry this is me golfing q4 of the bi-weekly contest me golfing q4 of the bi-weekly contest 50 50 uh 51st closest room uh hit the like uh 51st closest room uh hit the like button in the subscribe button join me button in the subscribe button join me on discord let me know what you think on discord let me know what you think about this farm and about this farm and and on this contest and so forth um so and on this contest and so forth um so this is basically this is basically so this is a pattern that comes up in so this is a pattern that comes up in lead code but to be honest lead code but to be honest it's a little bit awkward because it it's a little bit awkward because it doesn't really come up that much in real doesn't really come up that much in real life in life in in a way because in a way because because in real life um if you have because in real life um if you have these kind of problems these kind of problems um the queries are usually not given to um the queries are usually not given to you all at the same time you all at the same time meaning that these queries are not live meaning that these queries are not live these are these are kind of dead curries so and one kind of dead curries so and one and and the cool thing about that and and the cool thing about that queries is queries is that you can process them in any way that you can process them in any way that you want that you want so with with that in mind um because so with with that in mind um because because if these are live queries this because if these are live queries this become a much harder problem but because become a much harder problem but because these are dead queries these are dead queries the way to to answer the queries is that the way to to answer the queries is that we we come up with another way of we we come up with another way of entering the queries entering the queries we basically go we basically answer the queries in in the order of of going from max to min or in terms of room size um for example 3 3 we put nothing in the set yet um and then rather two so then now we we go okay room two is room two id is good one one id is good one three id is good so then this one has an answer and then lastly we process the one and everything's in so that's basically the idea the idea is just the idea is just processing the the queries in that way and then we slowly add in the rooms to be available and then we do a binary search on that array and i'll show you how i did in code but that's basically the idea um yeah so basically i i sold them into events and i wanted to sort by uh max room size so that's hence the negative uh so my events have you know um so that's the room size that's the type that's the index the index of the room and and this is just i needed an extra thingy it doesn't have anything um while on for queries we sort by room size we have a type of one for queries and then p is um the preferred uh i from id so this is what we're going to look at and then index is the index of the query so that we can know where to put the answer and that's basically the core idea we saw all the events we keep track of all the the all the numbers um all the room numbers that we care about if it if the and of course we have this type here um that we also sort by to keep in mind so that the zero will always come before the first meaning that if the room size are the same we process all the rooms first before we run the curse and that's deliberate um but yeah so if the type is zero we add it to the available room so this is this sl it's just available rooms that we can uh go to um otherwise if type is one then this is a query if this is a query we go okay let's do a binary search on the available rooms um and if this is inside the list because if this is either because i think this can return the length of sl which means that it is um c is bigger than the largest element then we set it to the uh element otherwise it's uh negative one and then i and then basically because if you do a binary search you um the idea here is that we do binary search you you you want to look at the next number and the previous number because you're in between two numbers so i just do index minus one i do the same thing to see if it's uh whatever uh this is within bounds and if it is and then if then i just check to see the distance um and the distance is smaller than you go to then we set this to the current index um and because this index is always going to be smaller because sf index is always going to be smaller than this index we just set it to this index if it's equal to um and then we just set the answer and of course you know we call that c in this case is the it is the preferred thing so that's what we search because that's the prefer uh id um and d is the index in it for a query so then we um yeah we put it back in in the answer way in the right place and that's pretty much it at the very end we return the answer which is the entire right and that's pretty much it so what is the complexity of this right well we we do so defense so that is going to be and you can actually technically uh sort these independently and then just do some uh math to kind of keep track i sometimes do it that way this time i did it this way so yeah um but in any case let's say n is equal to the number of rooms and q is equal to queries then this is this sorting is going to be o of um n plus q log n plus q uh just for the sorting and for each of um these operations this is going to be o of log n just by adding it it's going to be log n and two binaries are just a log n so so for this is going to be o of q but i guess over q times log n so it gets dominated by the sorting of all these events as i mentioned you can actually do a little bit better and get this down um to n log n plus q log q um or something like that by sorting these independently uh these are just like very minor factors so yeah in terms of space well it's going to be linear space because we just keep track of the uh well linear for q and we have you know defense will have one item for uh the size of the input which is the number of items in rooms and cues so it's going to be linear um and this is just you know yeah um that's all i have for this problem let me know what you think and you can watch me solve it live during the contest right ideas at least so so so so let's call this so backwards cool looper slaughter cool looper slaughter uh yeah thanks for watching hit the like uh yeah thanks for watching hit the like button as a subscriber and join me in button as a subscriber and join me in discord let me know what you think about discord let me know what you think about today's barman contest and so forth and today's barman contest and so forth and whatever whatever uh i will see y'all later bye bye take uh i will see y'all later bye bye take care of yourself stay good stay healthy care of yourself stay good stay healthy and take good mental health bye bye | 2024-03-25 10:29:21 | 1,847 | 1847. Closest Room (Leetcode Hard) |
|
fikdT0AI5z4 | whenever you see any problem on arrays what do you think we can start what do you think we can start traversing the array from the beginning traversing the array from the beginning or we start reversing the array from the or we start reversing the array from the backwards right backwards right but we often forget that we can traverse but we often forget that we can traverse this array from both the starting and this array from both the starting and the end simultaneously right the end simultaneously right and sometimes this approach can give you and sometimes this approach can give you an efficient solution an efficient solution there is one such problem on lead code there is one such problem on lead code squares of a sorted array that explores squares of a sorted array that explores this example hello friends welcome back this example hello friends welcome back to my channel to my channel first i will explain you this problem first i will explain you this problem statement and we will look at some statement and we will look at some sample test cases sample test cases next we will see how you can approach next we will see how you can approach this problem using a brute force method this problem using a brute force method and then we will see how you can and then we will see how you can optimize this solution optimize this solution going forward we will also do a dry run going forward we will also do a dry run of the code so that you understand how of the code so that you understand how all of this actually works in action all of this actually works in action without further ado let's get started without further ado let's get started [Music] [Music] let us quickly try to make sure that we let us quickly try to make sure that we are understanding the problem statement are understanding the problem statement correctly in this problem you are given correctly in this problem you are given an integer array that is in a an integer array that is in a non-decreasing order that means the non-decreasing order that means the elements are arranged in an ascending elements are arranged in an ascending order correct order correct now you need to return me an array now you need to return me an array that has the squares of each number and that has the squares of each number and that is also in a ascending order right that is also in a ascending order right what does that mean this looks pretty what does that mean this looks pretty straightforward right let us look at the straightforward right let us look at the sample test cases now in our first test sample test cases now in our first test case i have the array 2 4 7 and 9. case i have the array 2 4 7 and 9. you can see that this array is in a you can see that this array is in a non-decreasing order correct so now if i non-decreasing order correct so now if i have to return an array that has the have to return an array that has the square of each number in a square of each number in a non-decreasing order what will i do i non-decreasing order what will i do i will just square each number correct will just square each number correct and you can see that this array is also and you can see that this array is also in an ascending order and all the in an ascending order and all the elements are squared so this will be elements are squared so this will be your answer right your answer right but there is a catch but there is a catch this array is an integer array right this array is an integer array right and integers could be both negative and and integers could be both negative and positive positive for example in a test case number 2 we for example in a test case number 2 we have this array right and you can see have this array right and you can see that it has negative elements and both that it has negative elements and both positive elements positive elements right now this array is sorted in an right now this array is sorted in an ascending order correct but what happens ascending order correct but what happens when you square each of the elements when you square each of the elements this will become 16 then 1 then 0 then 9 this will become 16 then 1 then 0 then 9 and then 100 right and then 100 right if you notice this array is no longer in if you notice this array is no longer in an ascending order right an ascending order right and that is because when you find the and that is because when you find the square of a negative number it will square of a negative number it will become positive become positive so the square of minus 4 will be 16 this so the square of minus 4 will be 16 this is a positive number right is a positive number right so the correct answer to this test case so the correct answer to this test case would be where you took care of all the negative numbers in a correct manner right now if you want to try this problem once again on your own feel free otherwise let us dive into the solution and see what we can do about it a good developer always tries to come up with a brute force solution first that is because a brute force solution guarantees you if a solution to a problem exists right so given this array what is the most naive or the brute-force way to approach this problem you need to find the squares right so in the first step what i'm just gonna do is i will square each of the elements and then i get this resultant array right now this array is not sorted what you can do as step number two as step number two you can just sort your array right and as soon as you sort it you will get your final resultant array right and this will be your answer but what is the problem with this approach this is a correct answer right when you try to sort your array the best time complexity that you can get would be order of n log n that will be the quick sort algorithm technique right but if you notice we never take any advantage of the fact that this array is already sorted right even if this array was in any order you would get your solution in order of n log n correct so definitely we need to find an optimal solution okay so let us take up one more sample array this array is even bigger and we will try to approach this problem in an efficient manner right so what is the first thing that you notice first of all you're gonna see that okay this array is in an ascending order right to the left you have the smallest element and to the right you have the largest element correct but if you notice closely there is a certain point or you can say somewhere middle in the array if you look closely all the elements towards the left are sorted in an increasing order where all of them are negative and towards the right all the elements are positive and they are sorted in a ascending order correct so what i have here is all these elements are sorted and all the elements to the left of this midpoint are sorted now you want the squares of all the elements right so first of all let us just square each element correct if you notice the same point once again all the elements to the right of this are sorted and all the elements to the left of this point are sorted correct now what can you do you can use the approach of two pointers to arrive at your ultimate sorted array what i am gonna do is i will have two pointers one that starts at the head and the other pointer that starts at the tail and using these head and tail pointers i can start to populate my final array to populate this array what i'm going to do is i will compare the head and the tail because i know that the most extreme elements will be on both of these ends right so either this will be the largest element or this will be the largest element right so i compare 49 and 100 100 is greater than 49 so what i'm just gonna do is i will copy 100 to the end of this result array and i will move my tail pointer one position back now repeat this process compare tail and head this time 49 is greater than 36 so what are you gonna do you will take this 49 and add it as the second last element in your result array and once you have added it move your head pointer one step ahead once again just repeat the same process compare 16 and 36 because 36 is larger i will put 36 in the next available position of my output array and i will take the tail pointer one place back just keep on repeating this process compare 16 and 9 16 is larger so place 16 over here so you can see how these head and tail pointers will keep on moving and ultimately they will converge at this middle point and this is where your iterations would stop and you will have ultimately retrieved your final output array just try to fill in these additional elements that i just added as an exercise for you now if you have understood this approach let us do a dry run of the code and see how this actually works on the left side of your screen you have the actual code to implement this solution and on the right i have an integer array that has both negative and positive integers and it is passed in as an input parameter to the function sorted squares oh and by the way this complete code and its theft cases are also available on my github profile you can find the link in the description below moving ahead with our dry run first of all we create a result array that will store all of our squares in a sorted order and its length will be the same as the input area length right so this is the array where i will store all of my results correct now what is the first thing that we do first of all we will square all of our elements so as soon as i square all these elements it will become 16 1 0 9 and 100 right now in the next step we assign two pointers a head and a tail so the head pointer points at the first element and the tail pointer points at the last element right that is where the zero and num length minus one comes from moving on what i need to do i need to place all of these elements in their correct positions right and to do that i will start a for loop which starts at the last position in my result array and goes all the way to 0. so i will be filling this result array from last all the way to the first element correct now what i'm going to do is i will compare this head and tail right we know that 100 is greater than 16 right so what do i do i will land in my else condition and i will assign this tail number to the last position once i do that 100 gets assigned at the last position and then what do i do i do a tail minus minus this will move the tail pointer from the last position to the second last position correct in the next iteration this loop runs again and this time i will be comparing 16 and 9. once this happens i will get 16 in my resultant array and the head pointer will move one step ahead similarly this loop will continue to go on and ultimately you will fill up your entire array right now the time complexity of this solution is order of n that is because we iterate through the entire array only once and the space complexity of this solution is also order of n that is because we create a result array that will store all of our squares i hope i was able to simplify the problem and its solution for you as per my final thoughts i just want to say two things first of all whenever you see any array or any problem that is given to you in a sorted order trust me you have to take advantage of that fact if you try to approach this problem in any conventional way or try to come around with a different solution there is a very high chance that you will exceed your time limits so always watch out for the fact that the problem is sorted and try to take advantage of it the next thing is whenever you are given two sorted lifts it is always a good idea to iterate through them simultaneously they could be in the same direction they could be in the reverse direction or they could be in a convergent direction and when you take advantage of these facts there is a very high chance that you will land at an efficient solution did you see any other problems which used the same two-pointer approach one such problem is merging of two sorted lifts right what other problems did you see can you come up with any other solutions tell me everything in the comment section below and i would love to discuss all of them with you you would be also glad to know that a text-based explanation to this content is available on the website studyalgorithms.com a pretty handy website for your programming needs as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where i can simplify programming for you also let me know what problem do you want me to | 2024-03-25 14:18:50 | 977 | Squares of Sorted Array (LeetCode 977) | Full Solution with examples & animation | Study Algorithms |
|
nKff7vM3KDA | Hai [Music] [Music] Tu ok hai, something special before this deception and if we Tu ok hai, something special before this deception and if we want to talk, our channel want to talk, our channel is sponsored by Spots and Akhilesh Nice day, it does not come on its own, okay then you a job, you have to pay YouTube 29337 jobs After salary, you must subscribe to these many benefits After salary, you must subscribe to these many benefits channel because Ling Ling Ling Ling send that I am fine then you go 56001 pimp tube looking our questions 50 love basically this is quite distracting if you if you find some of your Now in the good points of this Now in the good points of this Now in the good points of this year's time like if you ignore year's time like if you ignore a little then the soldiers engaged in centos a little then the soldiers engaged in centos became top hindi then here the Italian is given became top hindi then here the Italian is given fast like because it is very good egg fast like because it is very good egg point question so now as many as point question so now as many as this this you will get this question from the same question for 10 minutes you will get this question from the same question for 10 minutes because next is its meaning, you will because next is its meaning, you will see here in which it is not called, see here in which it is not called, in that you will withdraw, add this question as in that you will withdraw, add this question as platform here. platform here. platform here. better that in the committee and in such a situation in the company's Robert, today my wife is free, pain is fine, this cream, we will roll it here, we do all the work, after this interview, we will see what is a question, meaning you have questions but certificate Let me print the express Let me print the express Let me print the express what is my entry that setting what is my entry that setting it here and stuffing and break down it here and stuffing and break down that Greece has to Institute of Management that Greece has to Institute of Management Institute and what we have to do is here to Ajay Ajay okay okay okay Look at Look at Look at this, if you see what it is saying to us is this, if you see what it is saying to us is that we have to tell the index like this. If you are that we have to tell the index like this. If you are standing on this next side, then like its A, standing on this next side, then like its A, we have to tell the address. If you are standing here then on the we have to tell the address. If you are standing here then on the right side of it, whoever the person is right side of it, whoever the person is with him and laddu. with him and laddu. with him and laddu. heart, here I take this induction heater, lifting or zero one two three Lord Vishnu took oath to go to school, if you cross here, stand at a little distance you cross here, stand at a little distance here. here. here. side boils, then it is getting friends for this, how much is their time, okay, but understand in these, label, dip function in the internet, how much one is organized, what happened to it, should it be intact, which protein or else you will say, I will talk about For Equilibrium Intact, For Equilibrium Intact, For Equilibrium Intact, I have written this here and I have written this here and that this has become liquid on Amazon. If you that this has become liquid on Amazon. If you talk about the recipe, then search for the question paper talk about the recipe, then search for the question paper Thandak Thandak Singh. You Singh. You can see this here, here we have to subscribe to such and such. So let's subscribe that subscribe that you turn it on here and you turn it on here and from here Okay, now let's see how to do this question So one time and let's make this water and put it on it Sugar and our value character value Sugar and our value character value Sugar and our value character value our tea our tea 173 and 666 676 will work, first of all we will take out a lot of time, 676 will work, first of all we will take out a lot of time, put a lot of our time, put a lot of our time, prefix, now I write in it prefix, now I write in it that this much will come, complete 1783 level plug 6560, subscribe Read and what will we do, we will start daily wear look Read and what will we do, we will start daily wear look and area austerity, okay, and area austerity, okay, just used to be intoxicated, just used to be intoxicated, do strategic and protesting against do strategic and protesting against ad, and will amaze our lips, if you ad, and will amaze our lips, if you refuse to kill your ad in the chapter, then refuse to kill your ad in the chapter, then left or only 2000 in April left or only 2000 in April seventh seventh seventh and he will remove the bank from this time. Even after becoming 28th, he has become seven. Okay, now send it in the lips, it is set and right time, remove the scrubbing, it is twenty, okay, relax, add the committee, how many eleven Rajasthan message free remove kitna 117 Rajasthan message free remove kitna 117 Rajasthan message free remove kitna 117 now left semester course in it now left semester course in it electromagnetic shockwave kitna ka 17th electromagnetic shockwave kitna ka 17th like did your next election left side like did your next election left side written on this index first capability and if you written on this index first capability and if you die at night then you take it here die at night then you take it here second when run it will add saffron and second when run it will add saffron and Like I will add to right commission, Like I will add to right commission, before removing the negative, hair can be removed, before removing the negative, hair can be removed, before doing this, decide that your lips subscribe before doing this, decide that your lips subscribe button is clicked, if they are equal, then the button is clicked, if they are equal, then the use of fun is diet, the problem is so much here, use of fun is diet, the problem is so much here, we had to apply here, okay so we had to apply here, okay so we had to apply here, okay so break it here, then it's okay, not here, I do plus caret and remove it. Increase it. Dear friend, that Android Vinod Khanna, consider it as 120 phase elections My favorite song is Scooter Karta. My favorite song is Scooter Karta. My favorite song is Scooter Karta. APS machine, so this is done, okay, okay, I'll take out the printer, Mithali, you check the phone, fix your right 0 toe preparation, you will get the qualification, you go to one side, I'll look at where. ladies. Check what time is ladies. Check what time is happening and remove this potato from the right time. happening and remove this potato from the right time. I have removed it from the item on the left. I have removed it from the item on the left. Now see what. Now see what. Now see what. only got liter of item, like we return curd and CID fuel, make roti and from here, done photo and no, if not found anywhere then we will get registration, but if we go here and there, then we will So what So what So what I am doing is that I am reading and checking that it is I am doing is that I am reading and checking that it is doing the right thing or not. It is okay. Contact Aishwarya. That's why I am installing the sample. Let's wait and see whether I am able to pass it or not. Seeing the treatment, am I able to understand it or Yes, yes, it is okay to do the right thing, that is a Yes, yes, it is okay to do the right thing, that is a very basic question, after that very basic question, after that even you are a supporter, that is, there is tension as to even you are a supporter, that is, there is tension as to how to do it, is it okay, all this will go, thank you so how to do it, is it okay, all this will go, thank you so much much [music] do it is done | 2024-03-21 10:58:11 | 724 | Find Pivot Index || Leetcode 724 |
|
wiGpQwVHdE0 | what solve leak code 3 longest substring without repeating characters or back to without repeating characters or back to a classic leak code problem the third a classic leak code problem the third one so this one's pretty simple we're one so this one's pretty simple we're just given a string and we want to find just given a string and we want to find the longest sub screen without any the longest sub screen without any repeating characters right like how repeating characters right like how these three don't have any duplicate these three don't have any duplicate characters ABC this one has two A's so characters ABC this one has two A's so this would not count as a substring this would not count as a substring without repeating characters and we only without repeating characters and we only need to return the length of this need to return the length of this substring so the first idea that comes substring so the first idea that comes to my mind at least is so just check to my mind at least is so just check every single substring check if it has every single substring check if it has any duplicates if it doesn't then it any duplicates if it doesn't then it then we're just going to take the then we're just going to take the longest one of those strings and return longest one of those strings and return the length so how would that algorithm the length so how would that algorithm run okay first we'd start at a we want run okay first we'd start at a we want to get every substring starting at a so to get every substring starting at a so just this one a well that doesn't have just this one a well that doesn't have any duplicates a B that doesn't have any any duplicates a B that doesn't have any duplicates a C that doesn't have any duplicates a C that doesn't have any duplicates either and then we get to duplicates either and then we get to this first duplicate a we have two A's this first duplicate a we have two A's now but remember we're checking every now but remember we're checking every single sub screen starting at this first single sub screen starting at this first a so we're gonna keep this algorithm a so we're gonna keep this algorithm going even though we don't have to every going even though we don't have to every substring we get after that like see how substring we get after that like see how we're doing it every single substring we're doing it every single substring after is also gonna have duplicates so after is also gonna have duplicates so do we even need to check all of these do we even need to check all of these starting at value a this is the repeated starting at value a this is the repeated work that we're gonna eliminate with our work that we're gonna eliminate with our very fundamental technique the sliding very fundamental technique the sliding window so we want to only check sub window so we want to only check sub strings without any repeated characters strings without any repeated characters so let's actually just do that let's so let's actually just do that let's make sure that our window right our sub make sure that our window right our sub array our substring is always not array our substring is always not containing any duplicates so once we get containing any duplicates so once we get to this next a we're gonna say well now to this next a we're gonna say well now we have to a so we need to start we have to a so we need to start removing from the left wing to start removing from the left wing to start shrinking our sliding window until we no shrinking our sliding window until we no longer have duplicates so I'm gonna say longer have duplicates so I'm gonna say remove this one from our substring now remove this one from our substring now our substring runs from here from the B our substring runs from here from the B all the way to the a now it's perfectly all the way to the a now it's perfectly valid so now we can keep going it's valid so now we can keep going it's still only length three though so now still only length three though so now so we're gonna add this bead but wait a so we're gonna add this bead but wait a minute now we have two bees but my minute now we have two bees but my question is how would we even know question is how would we even know instantly whether we had a duplicate or instantly whether we had a duplicate or not well we can use a set for that sets not well we can use a set for that sets will only contain one of each character will only contain one of each character so we'll automatically know if we have a so we'll automatically know if we have a duplicate we can check it instantly so duplicate we can check it instantly so we're going to check that we have two we're going to check that we have two bees so now we're going to keep popping bees so now we're going to keep popping from the left we're going to keep from the left we're going to keep shrinking our window from the left until shrinking our window from the left until we don't have until we remove a bee and we don't have until we remove a bee and we're gonna see that the first one we we're gonna see that the first one we remove is the Beast and now we're done remove is the Beast and now we're done so now our substring runs from this C so now our substring runs from this C all the way to this D now we're gonna all the way to this D now we're gonna add another character once again we have add another character once again we have a duplicate and once again we can a duplicate and once again we can literally just remove the farthest left literally just remove the farthest left character and now we're valid again no character and now we're valid again no more duplicates we're running all the more duplicates we're running all the way from A to C next we add a B the way from A to C next we add a B the interesting thing about this is that now interesting thing about this is that now we have to remove this a because we have we have to remove this a because we have to shrink our window our sub string has to shrink our window our sub string has to be contiguous so we have to remove to be contiguous so we have to remove this a but notice we still have two bees this a but notice we still have two bees in our substring so we got to remove in our substring so we got to remove another character we have to remove this another character we have to remove this B so now our substring runs from C to B B so now our substring runs from C to B so we are valid again but now our so we are valid again but now our substring is only length two next we'll substring is only length two next we'll get to the last B last character we're get to the last B last character we're adding and C yep it's a duplicate again adding and C yep it's a duplicate again and don't forget that as we're removing and don't forget that as we're removing these characters from the left we're these characters from the left we're removing a C we're not just removing it removing a C we're not just removing it from our window but we also have to from our window but we also have to remove it from our set because our set remove it from our set because our set is going to correspond to all the is going to correspond to all the characters inside of our substring that characters inside of our substring that we're at so we have to remove our see we're at so we have to remove our see from the window and move it from the set from the window and move it from the set we have to take this B and do the same we have to take this B and do the same thing and now we have no more characters thing and now we have no more characters to add with this sliding window to add with this sliding window technique which is a very fundamental technique which is a very fundamental technique that you'll probably see a lot technique that you'll probably see a lot more in a lot of different problems we more in a lot of different problems we can cut the time complexity down to Big can cut the time complexity down to Big O of n we just have to go through the O of n we just have to go through the entire list well we might have to add entire list well we might have to add and remove values from our set but and remove values from our set but that's a very quick operation the memory that's a very quick operation the memory complexity because of our set is also complexity because of our set is also going to be Big O of n because potential going to be Big O of n because potential every character and the string could be every character and the string could be unique and will add all of them to our unique and will add all of them to our set and I didn't really show it while we set and I didn't really show it while we were going through the problem but we were going through the problem but we would want to maintain what's the would want to maintain what's the longest substring we found in our case longest substring we found in our case it was obvious that the long as we found it was obvious that the long as we found was of length three so I remember the was of length three so I remember the first thing we need to do is get a set first thing we need to do is get a set to make sure we have all the characters to make sure we have all the characters in our window so I'll call it character in our window so I'll call it character set and we're going to do a sliding set and we're going to do a sliding window so any week so we need two window so any week so we need two pointers a left pointer and a right pointers a left pointer and a right pointer to determine our sliding window pointer to determine our sliding window our left will be initialized to zero and our left will be initialized to zero and our right pointer is going to our right pointer is going to continuously be changing as we visit continuously be changing as we visit every character so I can just use it in every character so I can just use it in this for loop so the right pointer is this for loop so the right pointer is going to go through every single going to go through every single character now remember if we get to a character now remember if we get to a duplicate character that means we have duplicate character that means we have to update our window and our set so to update our window and our set so while this character that we just visit while this character that we just visit at the right pointer s of R is equal is at the right pointer s of R is equal is already inside our character set meaning already inside our character set meaning it's a duplicate then we got to update it's a duplicate then we got to update our window so we have to take the left our window so we have to take the left character and remove it from our set so character and remove it from our set so character set dot remove the leftmost character set dot remove the leftmost character and then of course we have to character and then of course we have to update that left pointer incremented by update that left pointer incremented by 1 and we're going to keep doing this 1 and we're going to keep doing this while that duplicate remains in the while that duplicate remains in the character set after we've removed all character set after we've removed all duplicates then we can just add this duplicates then we can just add this rightmost character to our set and since rightmost character to our set and since at this point we know for sure that our at this point we know for sure that our substring doesn't have any duplicates we substring doesn't have any duplicates we can potentially update ours our result can potentially update ours our result variable which I never declared so let variable which I never declared so let me declare it up here result is me declare it up here result is initially going to be 0 and now we can initially going to be 0 and now we can update our results so we can potentially update our results so we can potentially make it larger than it is if the current make it larger than it is if the current window size is greater than what it is window size is greater than what it is right now which we can compute by right right now which we can compute by right minus left plus 1 and then at the end minus left plus 1 and then at the end once we've gone through the entire or once we've gone through the entire or substring we can return the result if substring we can return the result if this was helpful leave a like in this was helpful leave a like in subscribe and thank you for watching | 2024-03-18 10:29:57 | 3 | Longest Substring Without Repeating Characters - Leetcode 3 - Python |
|
hbzdyIlvBKI | hey so welcome back in this another daily code problem so today it was daily code problem so today it was called longest zigzag path in a binary called longest zigzag path in a binary tree and it's a medium level uh tree tree and it's a medium level uh tree question where you're gonna do exactly question where you're gonna do exactly that actually so you just want to find that actually so you just want to find whatever zigzag path and that's just you whatever zigzag path and that's just you have to alternate between going left have to alternate between going left right left right or starting at right right left right or starting at right then going left right left right so you then going left right left right so you just have to alternate between going just have to alternate between going left and right left and right and so the only other catch here is that and so the only other catch here is that you don't actually have to start at the you don't actually have to start at the root node here this is an example where root node here this is an example where the longest path does begin at the root the longest path does begin at the root node but it doesn't actually have to you node but it doesn't actually have to you can see in this case where the output is can see in this case where the output is three and that can only be achieved by three and that can only be achieved by not starting at the root node not starting at the root node okay so it's actually started here and okay so it's actually started here and that allows you to get three edges here that allows you to get three edges here okay and so okay and so what we're going to give you is a o of n what we're going to give you is a o of n time and space complexity solution so time and space complexity solution so you just travel to every node at most you just travel to every node at most once and because this is going to be a once and because this is going to be a recursive solution we will have at most recursive solution we will have at most o of n on the stack okay and so to do o of n on the stack okay and so to do this we're just going to return the this we're just going to return the result of result of a helper function that we're going to a helper function that we're going to create create and here we're just going to pass in the and here we're just going to pass in the node that we're looking at and then node that we're looking at and then whether or not we previously went left whether or not we previously went left so we can kind of maintain okay do we so we can kind of maintain okay do we want to go right this time or do we want want to go right this time or do we want to go left this time and that depends on to go left this time and that depends on whether or not we went left or right whether or not we went left or right last time last time and then we just want to maintain what and then we just want to maintain what the current depth of this path that the current depth of this path that we're considering at this current moment we're considering at this current moment in time in time okay and so the base case is okay if our okay and so the base case is okay if our root is none root is none so if there's nothing here then let's so if there's nothing here then let's just return our depth and this just just return our depth and this just allows us to kind of propagate that allows us to kind of propagate that result back to the top of the tree result back to the top of the tree and so what we're going to do is we want and so what we're going to do is we want to return the maximum to return the maximum of this helper function you just want to pass in two recursive calls this one where you start at going left and one where we start going right so we can say okay we can either go left and so because this one's going right and so because this one's going right then we say okay is it left no that's then we say okay is it left no that's false right this is left here so false right this is left here so previously do we go left no we started previously do we go left no we started right right and then here on this side and then here on this side we're going to pass in true we're going to pass in true and in Python these have to be uppercase and in Python these have to be uppercase and so next what we want to do is we and so next what we want to do is we initially have our depth to zero initially have our depth to zero and so that's just to show okay we're and so that's just to show okay we're starting at zero at the row because we starting at zero at the row because we haven't traversed any edges just yet haven't traversed any edges just yet okay okay and so from there it shows an error but and so from there it shows an error but I think this is okay turn the max of root dot rate which false zero root dot rate which false zero awesome awesome okay and so from here why don't we go okay and so from here why don't we go ahead and say there's two different ahead and say there's two different paths that we can go down paths that we can go down one of them is if we went left one of them is if we went left previously otherwise we previously went previously otherwise we previously went right so otherwise right so otherwise we previously we previously went right went right and so then at the end of this we want and so then at the end of this we want to return the maximum depth to return the maximum depth which will be this okay so we're just which will be this okay so we're just going to update this current depth with going to update this current depth with it with whatever is the maximum path it with whatever is the maximum path that we can get from these two paths that we can get from these two paths that we can go down and we just return that we can go down and we just return at the end at the end and so the first one is we want to set and so the first one is we want to set our depth equal to the maximum of either our depth equal to the maximum of either itself itself or we can recursively call itself or we can recursively call itself but this time since we previously went but this time since we previously went left next time let's go right so we do left next time let's go right so we do root dot right root dot right and then is left well that's now the and then is left well that's now the negation of it is not is left negation of it is not is left and so that will be okay this will now and so that will be okay this will now be since this is true this iteration be since this is true this iteration will then I'll be false will then I'll be false and then we just want to increment our and then we just want to increment our depth by one because now we're going depth by one because now we're going down another node and so we just down another node and so we just increment it by one increment it by one okay and so from here okay and so from here we're going to do the exact same thing we're going to do the exact same thing but for when we go right so now we want to go left this time so now we want to go left this time this is now true this is now true and we still want to increment it by one and we still want to increment it by one so there's one other case that we have so there's one other case that we have to consider for both of these paths and to consider for both of these paths and that's what will allow us to actually that's what will allow us to actually consider the case where the root node consider the case where the root node doesn't actually have the longest zigzag doesn't actually have the longest zigzag path path but actually like a node further down but actually like a node further down the tree the tree and we can do that by just simply and we can do that by just simply performing another recursive call performing another recursive call but say if we previously went left we but say if we previously went left we can actually go left again but we'll just reset our depth back to zero oh undo we want to say true here because we're going left this time so what this does is this allows us to do the case where okay it allows to go right again after we previously went right and so that allows us to consider the cases where okay say if the longest route path was like this node here in order to get to this part and start here you actually have to go right twice and all you have to do is just reset back to zero in order to begin from there so that allows you to kind of start at this root node and to hop there by going right twice otherwise you'll just be forced to go down this right left path always and not being able to do like right right and begin at this particular note okay and so you want to do that exact same thing but for the alternate case let's go ahead and run that let's go ahead and run that and yeah so that's the algorithm so it's and yeah so that's the algorithm so it's a recursive solution with once again o a recursive solution with once again o of n time and space complexity because of n time and space complexity because you're going to go through every single you're going to go through every single node at most once and at the worst case node at most once and at the worst case the application stack will have n nodes the application stack will have n nodes and number of nodes on it so yeah I hope and number of nodes on it so yeah I hope that helped a little bit and good luck that helped a little bit and good luck with the rest of your algorithms thanks with the rest of your algorithms thanks for watching | 2024-03-21 00:46:19 | 1,372 | Longest ZigZag Path in a Binary Tree - LeetCode 1372 - Python Solution |
|
4olB4YAts9E | hey guys welcome back in today's video we're going to look at Elite code we're going to look at Elite code problem and the problem's name is KD problem and the problem's name is KD fairs in an array in this question we fairs in an array in this question we are given an array called nums we're are given an array called nums we're also given an integer K we have to also given an integer K we have to return the number of unique creative return the number of unique creative face in the array a creative fair is an face in the array a creative fair is an integer pair consisting of norms of Phi integer pair consisting of norms of Phi and nums of J and it holds true only and nums of J and it holds true only when I and J are between 0 and nums dot when I and J are between 0 and nums dot Len and I is always less than J and the Len and I is always less than J and the absolute difference between the two absolute difference between the two numbers present at I and J should be numbers present at I and J should be equal to K so in this question as you equal to K so in this question as you can see this is the nums array and K is can see this is the nums array and K is the difference we have to find out the the difference we have to find out the pairs which have difference equal to 2 pairs which have difference equal to 2 here I can see one pair where the here I can see one pair where the difference is equal to 2 also the difference is equal to 2 also the difference between this and this number difference between this and this number is also 2 so we have two unique pairs is also 2 so we have two unique pairs here one comma 3 is invalid because PSI here one comma 3 is invalid because PSI is present here and J is present here is present here and J is present here they have mentioned that I should be they have mentioned that I should be less than J but here it is not passing less than J but here it is not passing so you can't consider this pair and also so you can't consider this pair and also you might notice that 3 comma 1 can be you might notice that 3 comma 1 can be formed here and also 3 comma 1 can be formed here and also 3 comma 1 can be found here but that will give you two found here but that will give you two same pairs but we are only allowed to same pairs but we are only allowed to return the unique pair so you should return the unique pair so you should count only one among them so let's take count only one among them so let's take a look at the logic we need to follow to a look at the logic we need to follow to solve this problem you might notice that solve this problem you might notice that this problem is very similar to the this problem is very similar to the first problem on lead code that is 2 sum first problem on lead code that is 2 sum two sum we are taking one number and two sum we are taking one number and checking if its complement is equal to checking if its complement is equal to the Target and we are checking that that the Target and we are checking that that complement number is present inside the complement number is present inside the map or not here also we are going to map or not here also we are going to follow the same logic we are going to follow the same logic we are going to create a hash map where both the key and create a hash map where both the key and value are integers the keys will value are integers the keys will represent the array elements and the represent the array elements and the value will represent their frequency value will represent their frequency next we have to create a integer next we have to create a integer variable count and initialize it to zero variable count and initialize it to zero so this variable will keep track of the so this variable will keep track of the number of pairs so initially it is 0 so number of pairs so initially it is 0 so this will be our result so let's take this will be our result so let's take this example and fill the map first I'm this example and fill the map first I'm going to start from here that is the key going to start from here that is the key and set its frequency to 1. next element and set its frequency to 1. next element is 1 add it into the map and set its is 1 add it into the map and set its frequent c21 next element is 4 you add frequent c21 next element is 4 you add it into the key and set its frequency to it into the key and set its frequency to 1. the next element is 1 which is 1. the next element is 1 which is already present inside the map so you already present inside the map so you increment its current frequency with one increment its current frequency with one so now the value of 1 is 2 the last so now the value of 1 is 2 the last element is 5 which is not present so you element is 5 which is not present so you add it inside the map and set its add it inside the map and set its frequency to 1. now our task is to frequency to 1. now our task is to eliminate one of the conditions I have eliminate one of the conditions I have mentioned that we have to ignore mentioned that we have to ignore duplicate pairs like this 3 1 is present duplicate pairs like this 3 1 is present here 3 1 is present here so what we can here 3 1 is present here so what we can do is that instead of iterating through do is that instead of iterating through the nums array you can iterate through the nums array you can iterate through the keys present inside the map so this the keys present inside the map so this will eliminate checking for duplicate will eliminate checking for duplicate number so we can only iterate through number so we can only iterate through the keys by making a set of keys using the keys by making a set of keys using the keysight method so if you use the the keysight method so if you use the key set method on the map it will give key set method on the map it will give you the set of keys present inside the you the set of keys present inside the map so now the key set will contain map so now the key set will contain these elements now you can iterate these elements now you can iterate through the key set and you won't through the key set and you won't encounter duplicate numbers by this you encounter duplicate numbers by this you can eliminate duplicate pairs now while can eliminate duplicate pairs now while we are iterating through the key set you we are iterating through the key set you have to divide the checking into two have to divide the checking into two parts that if value of K is greater than parts that if value of K is greater than 0 and value of K is equal to zero first 0 and value of K is equal to zero first let's check for this condition next time let's check for this condition next time walk through through this condition if K walk through through this condition if K is greater than 0 K is 2 so we have to is greater than 0 K is 2 so we have to check for this condition now we have to check for this condition now we have to check if I the key plus K is present check if I the key plus K is present inside the map or not ith key is this 3 inside the map or not ith key is this 3 plus K is equal to 5 we have to check if plus K is equal to 5 we have to check if 5 is present inside the map yes it is 5 is present inside the map yes it is present so you increment the count so present so you increment the count so you found one pair so 3 comma 5 you have you found one pair so 3 comma 5 you have already formed a pair so increment one already formed a pair so increment one count now it will keep checking for the count now it will keep checking for the next element present inside the key set next element present inside the key set 1 plus k k is 2 so 1 plus 2 is equal to 1 plus k k is 2 so 1 plus 2 is equal to 3 we have to check if 3 is present 3 we have to check if 3 is present inside the map 3 is present inside the inside the map 3 is present inside the map you can increment count so notice map you can increment count so notice that 3 comma 1 is a pair now so this is that 3 comma 1 is a pair now so this is one pair and this is one pair now we are one pair and this is one pair now we are checking for 4 plus 2 is 6 6 is not checking for 4 plus 2 is 6 6 is not present inside the map so you don't present inside the map so you don't increment count count Remains Two now increment count count Remains Two now five five plus two is seven seven is not five five plus two is seven seven is not present inside the map so 2 remains as present inside the map so 2 remains as the final answer and you return two as the final answer and you return two as the output which is the expected output the output which is the expected output as you can see here now let's check for as you can see here now let's check for this input one is not present inside the this input one is not present inside the map so you add one and add its frequency map so you add one and add its frequency as one three is not present inside the as one three is not present inside the map so you add three and set its map so you add three and set its frequency as one one is already present frequency as one one is already present inside the map so you increment its inside the map so you increment its current count plus one it will become current count plus one it will become two I is not present inside the map so two I is not present inside the map so you add 5 and set its frequency to one you add 5 and set its frequency to one or is not present inside the map so you or is not present inside the map so you add 4 and set its frequency to one so we add 4 and set its frequency to one so we have completed the steps still here now have completed the steps still here now we have to declare account variable we have to declare account variable initialize it to zero I've created a initialize it to zero I've created a count variable and initialize it to zero count variable and initialize it to zero now we have to iterate through only the now we have to iterate through only the keys inside the map so you can do that keys inside the map so you can do that by making a set of keys using the key by making a set of keys using the key set method so the key set will give you set method so the key set will give you this value now so this is the key set this value now so this is the key set you can eliminate duplicates using the you can eliminate duplicates using the key set so you are iterating through the key set so you are iterating through the key set now the value of K is equal to 0 key set now the value of K is equal to 0 that means that there shouldn't be any that means that there shouldn't be any difference between the pairs so you can difference between the pairs so you can find two numbers here one and one the find two numbers here one and one the difference between them is equal to zero difference between them is equal to zero so you get the expected output as one so you get the expected output as one you have to check this condition because you have to check this condition because K is equal to 0 so whenever K is equal K is equal to 0 so whenever K is equal to 0 we have to check if the value to 0 we have to check if the value frequency of ith character is greater frequency of ith character is greater than one we have to check if frequency than one we have to check if frequency of I I key is 1 we have to check the of I I key is 1 we have to check the frequency of 1 if it is greater than 1 frequency of 1 if it is greater than 1 yes it is greater than 1 so you yes it is greater than 1 so you increment the count variable so this is increment the count variable so this is the pair Form 1 and 1 is the pair form the pair Form 1 and 1 is the pair form now again K is equal to 0 you're now again K is equal to 0 you're checking if the frequency of 3 is checking if the frequency of 3 is greater than 1 no it is equal to 1 so greater than 1 no it is equal to 1 so you don't increment count similarly you don't increment count similarly frequency of Phi is 1 which means that frequency of Phi is 1 which means that there is no duplicate present of it there is no duplicate present of it which will satisfy the difference as which will satisfy the difference as zero also you can relate to the logic zero also you can relate to the logic that we are only checking if the value that we are only checking if the value is greater than and one for example if is greater than and one for example if you take one more one the frequency is you take one more one the frequency is three three one more one and now the frequency is one more one and now the frequency is four you can't make these two as another four you can't make these two as another pair this hash set does not encounter pair this hash set does not encounter one more one to check for these two one more one to check for these two pairs you're only checking for one value pairs you're only checking for one value at a time and next this number won't at a time and next this number won't appear again because you are not appear again because you are not iterating through the original nums you iterating through the original nums you are iterating to the key set so only one are iterating to the key set so only one time this number will occur inside the time this number will occur inside the key set because there are no duplicates key set because there are no duplicates present in the case of the hash map so present in the case of the hash map so if this value is equal to 100 also it if this value is equal to 100 also it will only check for one pair so you're will only check for one pair so you're only checking for one pair by checking only checking for one pair by checking only ones that it is greater than one I only ones that it is greater than one I hope you understood the logic so let's hope you understood the logic so let's code this logica recall the steps I've code this logica recall the steps I've mentioned in the word document we have mentioned in the word document we have to implement those steps in an order so to implement those steps in an order so the first step is to create a hash bar the first step is to create a hash bar where the key and value are going to be where the key and value are going to be integers now we have to fill the hash map with the keys being the array elements and the values being the frequency of those Arrow elements for that let's iterate now we have to check using the contents now we have to check using the contents key method if the array element present key method if the array element present at the ith index position is present at the ith index position is present inside the map as key if map dot inside the map as key if map dot contains key contains key of nums of I of nums of I if that array element is present inside if that array element is present inside the map you have to increment its the map you have to increment its current frequency by one as I've showed current frequency by one as I've showed you for one there were two ones present you for one there were two ones present in the last example so if it is checking in the last example so if it is checking if one is already present inside the map if one is already present inside the map if it is already present increment its if it is already present increment its current frequency with one for that you current frequency with one for that you have to use the put method the key will have to use the put method the key will be the array element the error of I and be the array element the error of I and get the current frequency using the get get the current frequency using the get method and incremented frequency with one and in the else block it means that that array element is not present inside the map so map dot contents K of nums of I this will return false not present inside the map you have to set its frequency to 1 so this is actually nums so Norms of I comma 1 so this else block statement will be executed for every unique element and from the next time whenever you find that element inside the map increment is frequency by one now we have filled the map the third step is to create a counter and count equal to 0 which will be our result now let's create a key set and iterate through it first let's declare a set the keys are integer so the set will also contain integer so map Dot keysight now let's access each element present inside the set so I'm using a for each Loop pull iterate through the set now this num will represent each number from left to right inside the set now coming to the check the first part of the if statement is that if K is greater than 0 and num plus K is present inside the map that is what I explained right map dot contains Key by checking if num plus K is present inside the map so num plus K is present inside the map then you have to increment count and we also have to check for second statement if K is equal to 0 and map dot get frequency of that num should be greater than 1 whenever K is the map dot get of num is greater than 1. so in this case also you have to increment count and finally outside the for Loop you can return the variable count which will be our result so let's run the code we're getting the expected output Let's test for all the test cases we are getting the expected output let's submit the code there you have it a solution has been accepted the time complexity of this approach is often because you are iterating through the array where n will represent the length of the array the space complexity is also often because you are using a map where in the worst case if all the elements are distinct the map will be filled with the length of nums that's it guys that's the end of the program thank you for watching and | 2024-03-19 15:46:23 | 532 | Leetcode | 532. K-diff Pairs in an Array | Medium | Java Solution |
|
56qUe5E0QNc | hello so today while doing this problem called binary sub-array with some it's a called binary sub-array with some it's a medium difficulty problem and it's we medium difficulty problem and it's we get an array of 0 and once only and want get an array of 0 and once only and want to count how many non-empty sub arrays to count how many non-empty sub arrays that have the sum s so for example have that have the sum s so for example have this array and s is equal to 2 so the this array and s is equal to 2 so the sub array that we can construct our list sub array that we can construct our list of that sum to two are this one and this of that sum to two are this one and this one in this one so in this one so that's one in this one so in this one so that's four for our sub arrays so our goal four for our sub arrays so our goal basically is to come to these with with basically is to come to these with with a value of s so and these are the a value of s so and these are the construct you know that a the values of construct you know that a the values of a are either zero point one and the sum a are either zero point one and the sum is between zero and the length of of the is between zero and the length of of the array so we don't need to hand on a case array so we don't need to hand on a case where it's bigger and yeah that's about where it's bigger and yeah that's about all that we are given so this problem is all that we are given so this problem is similar to a little problem called sub similar to a little problem called sub race the number of sub arrays with some race the number of sub arrays with some K except here it's a lot of special K except here it's a lot of special while it's a zero and one only while it's a zero and one only but we can solve this problem in the but we can solve this problem in the same way which is using just a hash map same way which is using just a hash map using a map to to count so basically we using a map to to count so basically we will use a math and in it will put us will use a math and in it will put us some as a key so our cube is that some some as a key so our cube is that some in the valley would be how many number in the valley would be how many number of the carats of of occurrences of desam of the carats of of occurrences of desam so basically what we will have is let's so basically what we will have is let's just write the Sun and we'll have a just write the Sun and we'll have a count that comes how many sub arrays we count that comes how many sub arrays we have so this is our map the sums have so this is our map the sums occurrence and count is zero occurrence and count is zero we'll go through the array call this day we'll go through the array call this day and we'll have an accumulative some so and we'll have an accumulative some so just a value with that kind of for for just a value with that kind of for for an array like one zero one zero one it an array like one zero one zero one it would just keep track so here for would just keep track so here for example it would be so here it would be example it would be so here it would be one and then if we advance one plus zero one and then if we advance one plus zero to one and then if we advance again it to one and then if we advance again it will be 2 so just a cumulative sum so will be 2 so just a cumulative sum so that means same shall I sit here - yes that means same shall I sit here - yes and yeah we can just each time add the and yeah we can just each time add the new value like we did here and the point new value like we did here and the point of this is basically if we have a summer of this is basically if we have a summer say or say some here at this value let's say or say some here at this value let's call this value G and then we have some call this value G and then we have some somewhere else say there are lots of somewhere else say there are lots of values here and we have this sum this values here and we have this sum this point earlier pointing at I and the idea point earlier pointing at I and the idea basically is that if the difference basically is that if the difference between some j minus sum I is equal to K between some j minus sum I is equal to K what that means is that the the values what that means is that the the values here their sum is equal to K so here their sum is equal to K so basically us call these bodies between basically us call these bodies between so that means that the sum between I and so that means that the sum between I and J I plus 1 and J is equal to K so J I plus 1 and J is equal to K so basically that means that we found this basically that means that we found this sum that satisfies the condition let's sum that satisfies the condition let's call this K here to avoid confusion so call this K here to avoid confusion so that means that we found an interval of that means that we found an interval of body that sounds - K so whenever we'll body that sounds - K so whenever we'll find something that but if that gives us find something that but if that gives us this that means we found an interval this that means we found an interval that means we can increase our count by that means we can increase our count by 1 and so how can we find this so the way 1 and so how can we find this so the way we can find this is since we have a map we can find this is since we have a map of some in their value of occurrence of some in their value of occurrence every time we encounter with this every time we encounter with this technology of value or a new Sun we can technology of value or a new Sun we can just check if the if it if already in just check if the if it if already in the map that is a value that is a sum the map that is a value that is a sum mindscape if that if that value exists mindscape if that if that value exists that means that since this basically that means that since this basically means means some of the eye is equal to K some of J some of the eye is equal to K some of J minus K so if you find this son that minus K so if you find this son that means would found this one that means we means would found this one that means we found the interval and we can count so found the interval and we can count so basically that means when we increase basically that means when we increase the son by the new value thank you much the son by the new value thank you much if someone can just check if this sum if someone can just check if this sum minus K so essentially this condition is minus K so essentially this condition is already in the map then we have this already in the map then we have this appearance and we have this interval appearance and we have this interval that sounds to care and as a result of that sounds to care and as a result of that we can increase count so if this is that we can increase count so if this is the case we can increase count by by how the case we can increase count by by how much so we can say 1 but that's not much so we can say 1 but that's not actually the case because maybe the actually the case because maybe the number of accounts is 2 so there are 2 number of accounts is 2 so there are 2 such sons in that case we can associate such sons in that case we can associate this interval with the J on one of the this interval with the J on one of the Sun and we can associate it with the J Sun and we can associate it with the J of the other son so it's actually the of the other son so it's actually the number of occurrences of that of this number of occurrences of that of this sum here is minus K and then after doing sum here is minus K and then after doing this we can just populate some map with this we can just populate some map with the new some so that would be 4 for the the new some so that would be 4 for the values that will arrive after after this values that will arrive after after this a basically so this would be since this a basically so this would be since this counts the number of occurrence we need counts the number of occurrence we need to say sums of map has plus 1 but since to say sums of map has plus 1 but since this may be it's not in the map yet so this may be it's not in the map yet so we need you just don't get s and the we need you just don't get s and the default value is 0 and with this we can default value is 0 and with this we can return it out we are expecting for but return it out we are expecting for but we get 2 yep so there is one case that I didn't handle which is saying we have K is equal to 1 right so we need to count this array but since there is no Sun before it is this one here there is no Sun before it will counted as 0 so in order to avoid that we can just put in the map and map 0 2 to 1 so that this case can be added to +1 and so the way we do that is we can just say sums of math of 0 is equal to 1 or alternatively ok now it passes see if this okay so ok now it passes see if this okay so this passes now this solution can work this passes now this solution can work with anybody who's not necessarily 1 & 0 with anybody who's not necessarily 1 & 0 so we didn't take advantage of that so so we didn't take advantage of that so let's say how can we take advantage of let's say how can we take advantage of this one just before actually explaining this one just before actually explaining that I can make this a little bit more that I can make this a little bit more efficient so since this is just counting efficient so since this is just counting I can use counter so I can just use I can use counter so I can just use counter yeah which is a Python 2 library counter yeah which is a Python 2 library utility that can just count the number utility that can just count the number of occurrences and the benefit of this of occurrences and the benefit of this one is that if verbling is not in this one is that if verbling is not in this in the counter yet then it just returns in the counter yet then it just returns 0 so with that we can avoid the need to 0 so with that we can avoid the need to check here so that means we can just do check here so that means we can just do count and if the value we didn't put the count and if the value we didn't put the value yet then we'll just get 0 and we value yet then we'll just get 0 and we will add nothing to our counter so that will add nothing to our counter so that works so this is counter and since by works so this is counter and since by default is 0 we don't need to explicitly default is 0 we don't need to explicitly say that so we just can't do this and say that so we just can't do this and this is the same as doing it plus 1 and this is the same as doing it plus 1 and we need to just handle the case where 0 we need to just handle the case where 0 & 1 0 is Method 2 1 so that we can do & 1 0 is Method 2 1 so that we can do this on these passes now let's get back to on these passes now let's get back to the solution that works of nobles - that the solution that works of nobles - that takes advantage of the fact that the takes advantage of the fact that the array contains only zeros and one and array contains only zeros and one and once so how can we do that so so the way once so how can we do that so so the way we can explain this is same we have a we can explain this is same we have a set of bodies we all must say a a just set of bodies we all must say a a just to map a structure of a random array to map a structure of a random array that that we may have and then we can that that we may have and then we can have let's say B B and then something have let's say B B and then something like this and then we maybe have other like this and then we maybe have other values let's say instead 0 and so when values let's say instead 0 and so when this happened here and we traverse the this happened here and we traverse the array what we can do is so basically array what we can do is so basically what we want is these volumes of us say what we want is these volumes of us say are once so once you find if K is equal are once so once you find if K is equal to 4 for example say if K is equal to 4 to 4 for example say if K is equal to 4 then we need to count this array but then we need to count this array but also all the zeros before it can also all the zeros before it can construct an array because they still construct an array because they still sound too far so this one can get added sound too far so this one can get added and then we can have this one and then and then we can have this one and then we can have this one so for each to 0 we we can have this one so for each to 0 we can have one more array that sums to K can have one more array that sums to K and the same thing to the right so the and the same thing to the right so the way we can do this is we can have so we way we can do this is we can have so we just need we just need to know where the just need we just need to know where the the first 0 is so that we can count all the first 0 is so that we can count all of these this as occurrences of a number of these this as occurrences of a number sub-arrays we increase by one so we just sub-arrays we increase by one so we just need to find this place here and in need to find this place here and in order to find this place we can just order to find this place we can just keep track of the last one we keep track of the last one we encountered so we can keep track of that encountered so we can keep track of that using prep and in order to know this sum using prep and in order to know this sum here we need to keep track of the start here we need to keep track of the start of it the start of the first value that of it the start of the first value that is not zero so let's call that low and is not zero so let's call that low and we need to keep track of the value that we need to keep track of the value that gives us the sum equal to K let's call gives us the sum equal to K let's call that time so high can be first here and that time so high can be first here and then we can find that the value is three then we can find that the value is three so we haven't reached it K yet so so we haven't reached it K yet so increase so it will do so our sum is increase so it will do so our sum is less than K so we need to increase high less than K so we need to increase high to reach a body bigger and then here to reach a body bigger and then here founder is equal to four and we need to founder is equal to four and we need to start counting this this this and this start counting this this this and this right and this is the the main idea so right and this is the the main idea so in this case here if K is equal to four in this case here if K is equal to four how can we count all of these so all of how can we count all of these so all of these is basically just this Plus this these is basically just this Plus this right the the values here and the values right the the values here and the values here so the van is here arms at what are here so the van is here arms at what are low - crap - one right minus one so that low - crap - one right minus one so that we can delete this one so this one is we can delete this one so this one is here in our loan - prayer - one and here in our loan - prayer - one and these values here they count for just these values here they count for just one sub array because if you take less one sub array because if you take less than that just these that's less than than that just these that's less than than K so it's counts only for one party than K so it's counts only for one party so it's plus one so these are type T is so it's plus one so these are type T is no - prayer right and so this here we no - prayer right and so this here we handle the case where the sum is equal handle the case where the sum is equal to K now what if the Sun is plus the to K now what if the Sun is plus the value that we just encountered is less value that we just encountered is less than K and what if it's the other cases than K and what if it's the other cases when it's bigger than K here we already when it's bigger than K here we already handled the case where it's equal to K that's the case that we handle all right so if it was like a that means that the Sun is lost okay that means that we need means this pointer forward so that we can find say when we are here it's three we need to move forward so that we can reach a bigger value that may be equal to K so this means that we need to reach a bigger so now if it's bigger than K that means that we need to find a smaller value and so we can leave K to reach a smaller value light the sorry we there is one thing we need to handle for there is one thing we need to handle for this case so if we move low so let's say this case so if we move low so let's say we love was here and that was zero so we we love was here and that was zero so we need to take care of need to take care of keep moving low until we find the value keep moving low until we find the value that is not zero so that we can start that is not zero so that we can start counting there is no need to count this counting there is no need to count this our values so here we need to do our values so here we need to do something where while the value at low something where while the value at low is equal to zero keep increasing is equal to zero keep increasing increasing right because otherwise if increasing right because otherwise if it's zero we haven't changed anything so it's zero we haven't changed anything so it won't help us much right so but still it won't help us much right so but still how can we do this and also the how can we do this and also the calculations that we did here reply on calculations that we did here reply on low being the first one value so we need low being the first one value so we need to make sure that that's always the case to make sure that that's always the case okay so let's start doing this solution okay so let's start doing this solution so there is one case where if all the so there is one case where if all the bodies are zeros then we don't know bodies are zeros then we don't know where to put low and high so our where to put low and high so our solution here won't work so we need to solution here won't work so we need to handle that separately so let's say if K handle that separately so let's say if K is equal to zero we need to handle that is equal to zero we need to handle that so here we just forgot to do so here we just forgot to do we can handle later now must initialize we can handle later now must initialize the bodies that we describe it's Elmo we the bodies that we describe it's Elmo we need I and we need just this to have a need I and we need just this to have a length of the array and was initialized length of the array and was initialized prep so first our low would be here so prep so first our low would be here so crappy we just can mark it with minus crappy we just can mark it with minus one anything before so that would be one anything before so that would be minus one for breath bonus star to zero minus one for breath bonus star to zero and I was stopped also to zero and n is and I was stopped also to zero and n is the length of array let's also have the length of array let's also have something a cumulative sum that just something a cumulative sum that just calculates the sum so that we can know calculates the sum so that we can know if it's less than K or not so that if it's less than K or not so that initializes to zero and we need the initializes to zero and we need the account for how many sub arrays we have account for how many sub arrays we have right so that would be 0 2 and now so right so that would be 0 2 and now so while this is not at the end of the while this is not at the end of the array yet and the value at low is equal array yet and the value at low is equal to 0 we to just keep advancing because to 0 we to just keep advancing because our formula here needs absurd when there our formula here needs absurd when there is nothing to zero and so in that case is nothing to zero and so in that case we can just keep increasing low and keep we can just keep increasing low and keep increasing advancing high to go to the increasing advancing high to go to the so first they start out as 0 0 if the so first they start out as 0 0 if the value is say 0 here we need to keep value is say 0 here we need to keep advancing until we find one that is not advancing until we find one that is not 0 and so we advance both and then after 0 and so we advance both and then after that so we keep make sure that we are that so we keep make sure that we are still within the bumpers and now start still within the bumpers and now start doing these conditions so check if s plus the bubble hat high is equal to K so our I'm here is just this value right here so if is equal to this and the other cases are if it's some bigger than 10 and comes to choose when it's like a so this case here we'll find the volume so we need to count this basically that our count so that we can just say oh my spray possibly as we calculated before and we need to advance both high so that we can check the next okay let's say we had another one here and in that case we need to also count count the occurrences of so if you had another one that I need to count also this okay let's write and so we are going to do my plus one and there's some increase it by right now for this case when it's bigger than K we need to move hello toe so that we can get a smaller value and we take care of this and so moving along this list and since we moved hello so now the Sun has one less value so the body and allow is not all getting the Sun and so you can think of this sum here as moving along P along with the values mo it in hi lower and higher based in we to handle the case that we that we said we are so pregnant to be always the first value that the first occurrence of the previous ones based way actually the last index of the occurrence of the previous ones so that means that we need to put trip to a low here and we if Y I'll always equal to two zero weight 200 this case with me to keep increasing it hasn't said yet and we also make sure that we didn't so beyond the length of the arrow and now if it's less than K we need to move higher to it should bigger son so we need to do this and we need to increase since it's not this and that's basically it and at the end make a 10 count so yeah we need to hand on this case if this sum is equal to zero so let's just define a function and we can find this one so so for this one we can just go through so we have and we have some and we can just go through the array and if a is equal to 0 then our count is plus 1 and our risk the final result was call it it's going to please both count so why is it going to increase by count is because say if we had 0 0 we need to count 1 2 & 2 & 3 and so first it was just zero so this is just 1 if we add another 0 then the number of zeros is 0 1 here 2 and then 3 so it's the previous count plus the the new then you count so otherwise we can just search like the counter because we encountered the body that is not 0 so we can't construct any sub arrays between that sum to 0 between these basically so whenever reach of 1 we can just start recounting from 0 and then in Clinton County and still eight this I can have 26 yeah I need to do else--if because this yeah I need to do else--if because this is um she didn't happen if it this one is um she didn't happen if it this one is vomit right so much Ventus is vomit right so much Ventus okay we I have a wrong answer for this okay we I have a wrong answer for this case here Selma's try and see why we are case here Selma's try and see why we are expected to get 15 because the sum is expected to get 15 because the sum is zero so that means that so when the Sun zero so that means that so when the Sun is zero we call this helper sum which is zero we call this helper sum which means our solution here is totally wrong means our solution here is totally wrong yeah we don't we should return count yeah we don't we should return count because this is rich initialized during because this is rich initialized during the accumulative result is in result the accumulative result is in result here so that and self else did it not that's interesting not sure is happy PLC that's interesting not sure is happy PLC so just to make sure that I didn't miss so just to make sure that I didn't miss out any invitation I'm wrong so I'll out any invitation I'm wrong so I'll pass ei with the value zeros and we'll pass ei with the value zeros and we'll go through them and we check if the go through them and we check if the value 0 increase count and we had come value 0 increase count and we had come to result and otherwise said count to 0 to result and otherwise said count to 0 and with a 10-0 run so this seems like and with a 10-0 run so this seems like reasonable and if K is equal to 0 it has reasonable and if K is equal to 0 it has returned that listen Kristen must print we'll just print here to see if it doesn't oh yeah I see so I just called this but I didn't write on it which is really dumb so it goes through here and this doesn't handle that case so it should be okay cool turned this and the solution okay cool turned this and the solution passes so yeah so this basically second passes so yeah so this basically second solution here uses two pointers and take solution here uses two pointers and take advantage of the fact that we have just advantage of the fact that we have just a zero in one in the array and yeah so a zero in one in the array and yeah so basically the lesson from this one is basically the lesson from this one is using two pointers and basically listing using two pointers and basically listing all the use cases possible and have the all the use cases possible and have the 90 each one separately yeah that's so 90 each one separately yeah that's so for now see you next time | 2024-03-25 11:32:44 | 930 | Leetcode 930. Binary Subarrays With Sum |
|
gkssX4evzkM | Premature Ejaculation Sir, welcome back to the series Australia, today we will talk about the balance Australia, today we will talk about the balance body, which is a body, which is a very good question in itself. Those who have put the concept in deposit, very good question in itself. Those who have put the concept in deposit, then then like every time I would please request you like every time I would please request you that that that if you do not know the regulation of this year, then let me tell you that at this time whenever someone comes, everyone catches the question, before that he has to set it for 5 minutes, 10 minutes and 15 Give it but before that, Give it but before that, Give it but before that, think of something for the attempt, do it think of something for the attempt, do it while doing it in the corporate office and then while doing it in the corporate office and then look at the question, Vikas Sikha, everyone Robert, if look at the question, Vikas Sikha, everyone Robert, if you want to learn, then let's start, what are you doing by asking video you want to learn, then let's start, what are you doing by asking video and technical questions? Aayi Ho, and technical questions? Aayi Ho, don't lie to yourself. don't lie to yourself. don't lie to yourself. tried it. Balance body is disconnected from the balance point. One is that it gives time to anything. We do not mean that we deposit this term from the market that we are saying what is the meaning of imbalance body? This note is given that its height This note is given that its height was on the left side, one or you can say it like this, if you correct the note then what is its height, its lineage and what is its height, then for this If I talk about If I talk about this note, what is its difference? One is okay, if I talk about this note, what is its left height? Seat kitne zero episode Seat kitne zero episode Seat kitne zero episode difference kitna ka yeh zero allotment of flats difference kitna ka yeh zero allotment of flats that if I talk about it, it's havan isk he got - karenge jitna zero then zero against against ka 08 means that we are the people and every node by taking out the left and right side of every note. Apps loot has been removed right and that we are checking what is coming now the question is given that we are checking each note number and the difference that is coming is the difference that your note should come greater than one it means There should not be one greater than the other, it There should not be one greater than the other, it There should not be one greater than the other, it should be equal to one that should be equal to one that if there is wealth then we will not give it a balance point if there is wealth then we will not give it a balance point battery. For the question, if I am giving battery. For the question, if I am giving you the second example then you the second example then what is the second example saying. Look, what is the second example saying. Look, now Shanno, tell me now. now Shanno, tell me now. now Shanno, tell me now. coming? How much is its hit coming on the left side? One two three live where two? So wrong, this is where the throttle will be pressed and will stop here. In these systems, we will have to check every single note. Okay, one of its height is how much difference. Its edifice is zero, how much is this yagya, two, and this is done, one, clothes, it's fine, it's fine, it's fine, it's fine, it's fine, but after failing this, we have to Day tech Day tech Day tech every node is subscribing to this condition every node is subscribing to this condition what is the condition that loot the apps of left height - what is the condition that loot the apps of left height - right height right height that the license should be 121 that the license should be 121 a clear-cut now see it seems to be of two concepts a clear-cut now see it seems to be of two concepts so if I get confused find out the correction what is it so if I get confused find out the correction what is it so if I get confused find out the correction what is it loot of left height of the app should be 121 from the right side. Take out the left height of the meat, take out the right one and do both. Okay, so one concept of height has been used. Brother, we will have to find out the height. What will be the second concept? One question. It was further written that we should not check the condition of the fruit. We have to check itch and every old node to see whether every note is subscribing to this thing So So So every node it means that we every node it means that we should also meet, so every node it means the should also meet, so every node it means the method, every note is the way to do drivers, method, every note is the way to do drivers, inverter traversal, preorder inverter traversal, preorder traversal 126 and whatever we have traversal 126 and whatever we have kept on it, okay Vinu, definitely kept on it, okay Vinu, definitely do the latest video. do the latest video. do the latest video. please Apna Satellite Krishna Kumari is from the industry, play the playlist, check, everything will be clear to you, I am moving from Macrame Basic to Advanced, so that those who will be consistent in this series from its seat, will benefit the animals. What is that, there is no such thing, I talk to the right side that you got the doubt from here, it's sequence, okay, I ignore example, then 10 and 7 attacks, if you have to catch every single note, then 10 and 7 attacks, if you have to catch every single note, then his his his put this traversal right. We have to check this condition in every note. For those who are confused that this condition should be checked, then this is the condition. What did these attacks do that this is this condition? This is the notice. This note should also be called, this note should be returned, this note should be visited, this note should be tight, this note should be returned to Mittu. Understand that every node should return towards this condition in itself. It is okay if even one false in between then true end. Mishra, what is false, remember till 500, this is just sure, always remember that true and false, we have false, there is no problem till it is ripe, now look, now I say one thing, The The The question must have been clear to you question must have been clear to you that after coming to the question, Times that after coming to the question, Times mixed these two concepts mixed these two concepts and made the question Next It means and made the question Next It means that we will have to find out the height in people. Do that we will have to find out the height in people. Do you know how to find the height? you know how to find the height? The code to calculate the height is very The code to calculate the height is very simple, we have done this using the height function root, simple, we have done this using the height function root, just like how we calculate the height of any note, so we calculate the height and now I have understood that a calculate the height and now I have understood that a page has been attacked by the root. page has been attacked by the root. page has been attacked by the root. fear, Annette Schwarz, mistake, what did he put in the question, what did he give, this is the balance that the tree node, what do we do, it creates an answer, the words, which use the boolean type, return it, that the films assume that, Yes, Yes, Yes, it must be working and let's make a loop it must be working and let's make a loop n order you tell check what will we change in it what will we n order you tell check what will we change in it what will we check then pass the route during check then pass the route during this time pass the head ok this time pass the head ok and return a answer and return a answer no problem no problem no problem created a dialect and depressed it, we will create a function, we have inverted and passed the answer in it and they have taken this height code, there is no problem till now, we have prepared the option, you use the most important function, Are going to do an in Are going to do an in Are going to do an in order you tell what did they take inside it Tree order you tell what did they take inside it Tree and Root and a satire and Root and a satire Why do they take E.M. Pregnant Answer Ambassador Why do they take E.M. Pregnant Answer Ambassador I have told you this thing and I have told you this thing and explained it many times so that people who are lions will also explained it many times so that people who are lions will also see it, they will get the idea. see it, they will get the idea. Show the list of such must have been done, now let's take it so that we are Show the list of such must have been done, now let's take it so that we are connected to the roots, just before this whiskey connected to the roots, just before this whiskey and declare somewhere in the main function, and declare somewhere in the main function, this is not changing frequently, the this is not changing frequently, the innovative driver can be attacked on the institute call, innovative driver can be attacked on the institute call, what is this recceive what is this recceive what is this recceive do, let's pick up this root is not equal to null, write it like this, no problem, have called in order, inverter you tell, call, sorry, what is the root of the call, left, I have explained the method Till the minute, Till the minute, Till the minute, first left, then left and passed the node fruit research first left, then left and passed the node fruit research institute loot, institute loot, opposition, whatever thing is there in the minute, right, opposition, whatever thing is there in the minute, right, made a last here, en order you, this made a last here, en order you, this root's right, a root's right, a tract and answer, now look, whoever tract and answer, now look, whoever comes here, then we comes here, then we now this is where we get every single note, get now this is where we get every single note, get notification, get note, like notification, get note, like if you talk about such an interview, then note or if you talk about such an interview, then note or meet people, talk about this data, sum meet people, talk about this data, sum gets root. gets root. gets root. node, we work on this note, see how, then I will take this color, then come here, after this, it is finished, now we will check this note, we will check the beans of this, that We will We will We will check this, if you can, check check this, if you can, check what we said that in our route we what we said that in our route we had kept Guru value had kept Guru value in the answer, keep in mind that the route mention has been kept in Roman, no problem, what in the answer, keep in mind that the route mention has been kept in Roman, no problem, what we did was that we took out a function one and one we did was that we took out a function one and one day one day one can take out that day one day one can take out that day one day one can take out that route left, no problem pant d2h Height of the route right, 6 difference taken out pant difference or ABS fennel d1 - due toe, checked that then the difference on the track in the village. on the track in the village. on the track in the village. look at this note, the set up of the note will be on this note, how will the note be first in inorder traversal, 9039 has passed, now we are here, then on this will come the f-18 Fraganate way or will seven But we have to check whether But we have to check whether But we have to check whether this is coming or this is coming or not, the network not, the network is guaranteed, if even one mistake is made in between is guaranteed, if even one mistake is made in between then ultimately the whole game then ultimately the whole game will fail and that's it. will fail and that's it. will fail and that's it. I said that you can use any other inverter family poster, I have asked for inverter in Australia, it's your choice, you make a voice that we have to make drivers and check each note, I have taken I have taken I have taken out the element ninth 1527 of the inverter. Now, when I have a out the element ninth 1527 of the inverter. Now, when I have a normal route on this route, what did I do that normal route on this route, what did I do that on the Noida route, it went there, here and there, what is the on the Noida route, it went there, here and there, what is the digestive thing, this thing is digestive thing, this thing is where I am, its ex is the where I am, its ex is the best, so what did I do with this data. best, so what did I do with this data. Shroud is of no use, I meant fruit in the bus, so what Shroud is of no use, I meant fruit in the bus, so what I have done is that for this route, I have I have done is that for this route, I have calculated the height of each route, I had to calculated the height of each route, I had to calculate the left height of each route and I had to calculate the right calculate the left height of each route and I had to calculate the right height of each foot. Thanks for rooting, height of each foot. Thanks for rooting, fight for. fight for. fight for. add it in 20112 or do RH, take care difference, we have taken out a chakli difference of greater than by admin that this note has failed, cooked, will pause it, let's pause it, This meter This meter This meter is all true, this one's answer is with metro, is all true, this one's answer is with metro, comment, I put one percent on it, right, comment, I put one percent on it, right, whatever is happening in the main function, which is in the root, whatever is happening in the main function, which is in the root, will be included, which is fruit, it will call last here, will be included, which is fruit, it will call last here, this one needs equal answer, this one needs equal answer, equal answer, MP cent. equal answer, MP cent. equal answer, MP cent. through, but when the antecedent is implicated in it, what does the end operator and theorem do that if one goes to the Air Force, then the ultimate traps him. Ultimately, in whatever form Salman is in, then what will be false and true will The whole game The whole game The whole game will run if you get the codes just by worrying, that's why will run if you get the codes just by worrying, that's why I kept this incident in the answer I kept this incident in the answer because ultimately the answers to the because ultimately the answers to the main function main function keep changing if you don't know the details of what is happening. keep changing if you don't know the details of what is happening. Who is this? I Who is this? I selected BJP. I was explaining that if I selected BJP. I was explaining that if I don't use embedded then every time a new very high for don't use embedded then every time a new very high for will go. It is important to keep right from present will go. It is important to keep right from present because it changes in the roots and because it changes in the roots and less changes in the roots by self-publicity. less changes in the roots by self-publicity. you have understood this game clearly, it is not very rocket science, it was very Reversal ka game Reversal ka game Reversal ka game tha ok ab school bhawan isko code tha ok ab school bhawan isko code jhal simple hai height ka code and the chief jhal simple hai height ka code and the chief renault route ok no after vote old is gold renault route ok no after vote old is gold channel simple return hai channel simple return hai a reader maximum of what jo bhi a reader maximum of what jo bhi told in this series that direct in this video told in this series that direct in this video told in this series that direct in this video planning to do so, I would request you to first watch the old video, then this trick would have been clear to you. Okay, no problem, now we have to forget to make the answer here, which will be made through You tell while calling, You tell while calling, You tell while calling, retention means so much support, tell me the retention means so much support, tell me the support function, its function name, it doesn't support function, its function name, it doesn't matter anything, I am just telling, so matter anything, I am just telling, so general works by taking comments, if you general works by taking comments, if you read the code at many places, you will see that if you read the code at many places, you will see that if you use digital, then it means tight. use digital, then it means tight. use digital, then it means tight. I create the world in this routine here, Root and Boolean and Sentences, if you don't send, then whenever this inverter calls this function again, a new variable will be created inside Gary Kirsten, Answer Tech, we want that Slam Slam Slam episode episode looks good must be clear by now looks good must be clear by now this root not equal toe no top enter inside and this root not equal toe no top enter inside and inverter will absolutely do this twice one for inverter will absolutely do this twice one for whom left of the root and answer whom left of the root and answer how a robot for how a robot for torch light adventure like and torch light adventure like and there there there how will the left come out first, remove the left key and right end of the IGST root, anoint the one which is ABS, first middle - R8, then it should be the Base St. Paul's David Base St. Paul's David Base St. Paul's David is nothing and is nothing and do two times associated with the True AND operator so you understand do two times associated with the True AND operator so you understand that things are running I'm telling the truth to that things are running I'm telling the truth to hate again if this hate again if this condition will study and we guys condition will study and we guys Please Please comment like share thank you [ Music] Jhala's Shri Ram Radhe-Radhe | 2024-03-21 10:35:34 | 110 | Balanced Binary Tree | Tree Data Structure playlist C++ | Hello World |
|
QmGQImp6vtM | [Music] hello everyone welcome to day second of hello everyone welcome to day second of march heat code challenge and i hope all march heat code challenge and i hope all of you are having a great time the of you are having a great time the question that we have in today's is question that we have in today's is subsequence here in this question we are subsequence here in this question we are given two strings s and t we need to given two strings s and t we need to identify whether s happens to be a sub identify whether s happens to be a sub sequence of d or not sequence of d or not for example here they have provided us for example here they have provided us with few cases where s is a b c t is a h with few cases where s is a b c t is a h b b g d c as you can see a g d c as you can see a b b and c and c all three characters occur in the same all three characters occur in the same order order in t in t as present in s as a result of which we as present in s as a result of which we have to return to it's a subsequence have to return to it's a subsequence here we have s as a x c and since x is here we have s as a x c and since x is not present in t we have to return false not present in t we have to return false if subsequence lead code 392 it's an if subsequence lead code 392 it's an easy level question on lead code and i easy level question on lead code and i totally feel the same totally feel the same so so let's take the same example that was let's take the same example that was specified in the question and by specified in the question and by definition of subsequence all the definition of subsequence all the characters in s should occur in the same characters in s should occur in the same order in t order in t so what do we do we take two pointers so what do we do we take two pointers i and j to keep track of i and j to keep track of the characters that we are currently the characters that we are currently visiting in both of them visiting in both of them what do we see first the is character in what do we see first the is character in s happens to be equal to jth character s happens to be equal to jth character in t in t as a result of which will increment both as a result of which will increment both of them so i and i point points to b and of them so i and i point points to b and j points to h j points to h what are we gonna do next we will keep what are we gonna do next we will keep searching for b in t searching for b in t till the time the jth character in d till the time the jth character in d doesn't match with the ith character in doesn't match with the ith character in s s so is h equal to b it's not equal as a so is h equal to b it's not equal as a result of which we'll have to increment result of which we'll have to increment e so t gets incremented to this position e so t gets incremented to this position and let's proceed ahead here we see that and let's proceed ahead here we see that both the characters have turned equal as both the characters have turned equal as a result of which we'll together move a result of which we'll together move them ahead now i points to c them ahead now i points to c and and j points to g j points to g so are these two equal these are not so are these two equal these are not equal as a result of which what we have equal as a result of which what we have to do we simply have to increment the to do we simply have to increment the jth pointer jth pointer till the time we don't see an ac so it till the time we don't see an ac so it gets incremented to d d is also not gets incremented to d d is also not equal to c equal to c again it gets incremented to c here we again it gets incremented to c here we see that see that it's a matching case c matches with c it's a matching case c matches with c as a result of which what we will do as a result of which what we will do we'll simply increment the s pointer we'll simply increment the s pointer which is i which is i and since we have found out all the and since we have found out all the elements of s in t it's the happy case elements of s in t it's the happy case we have to return true we have to return true in case after the complete iteration of in case after the complete iteration of t some characters still goes missing we t some characters still goes missing we have to return false in those cases have to return false in those cases without further ado let's quickly walk without further ado let's quickly walk through the coding section and i'll through the coding section and i'll exactly follow the same steps as i have exactly follow the same steps as i have talked here talked here as told in the presentation here i have as told in the presentation here i have taken two pointers i corresponds to s taken two pointers i corresponds to s string j corresponds to three string string j corresponds to three string till the time i haven't exhausted any till the time i haven't exhausted any one of them i keep on checking if my is one of them i keep on checking if my is character in s happens to be equal to th character in s happens to be equal to th character ajith character in t if such a character ajith character in t if such a case is found i increment the i get case is found i increment the i get pointer otherwise i keep on incrementing pointer otherwise i keep on incrementing j pointer searching for matching cases j pointer searching for matching cases in the end i simply check if my i in the end i simply check if my i happens to be equal to s dot length if happens to be equal to s dot length if it does that simply means that all the it does that simply means that all the characters in s have been found out in t characters in s have been found out in t and and it would be happy case it will it would be happy case it will automatically take care of returning automatically take care of returning true and false appropriately also there true and false appropriately also there is one of the corner case which i have is one of the corner case which i have specified if s dot length happens to be specified if s dot length happens to be 0 i have to return true because that 0 i have to return true because that signifies the input string is empty in signifies the input string is empty in nature the time complexity of this approach is order of and space complexity is constant time we and space complexity is constant time we are not using anything extra are not using anything extra this brings me to the end of today's this brings me to the end of today's session i hope you enjoyed it if you did session i hope you enjoyed it if you did please don't forget to like share and please don't forget to like share and subscribe to the channel thanks for subscribe to the channel thanks for being here have a great day ahead and being here have a great day ahead and stay tuned for more updates from coding stay tuned for more updates from coding decoded i'll see you tomorrow with decoded i'll see you tomorrow with another fresh question but till then another fresh question but till then good bye | 2024-03-24 12:07:41 | 392 | Is Subsequence | Leetcode 392 | Easy Two Pointer | Live coding session 🔥🔥 |
|
HehiIRa4geE | everyone so today we are looking at leak code number 48 code number 48 it is a question called rotate image and it is a question called rotate image and so we are given an so we are given an n by n 2d matrix representing an image n by n 2d matrix representing an image and we want to rotate the image by 90 and we want to rotate the image by 90 degrees clockwise degrees clockwise we want to do this in place and we do we want to do this in place and we do not want to allocate another 2d matrix not want to allocate another 2d matrix to do the rotation so here we have one to do the rotation so here we have one two three four five two three four five six seven eight nine we're going to six seven eight nine we're going to rotate this rotate this clockwise and so we can see that one two clockwise and so we can see that one two three three uh is on the last column four five six uh is on the last column four five six is in the middle column is in the middle column and seven eight nine is in the first and seven eight nine is in the first column okay so column okay so if you're not familiar with matrices if you're not familiar with matrices this problem can seem a little daunting this problem can seem a little daunting it can definitely seem very very it can definitely seem very very difficult but it's actually difficult but it's actually not that bad another question i not that bad another question i highly suggest looking i made a video on highly suggest looking i made a video on it it's called transpose matrix it it's called transpose matrix that kind of deals with a little bit of that kind of deals with a little bit of what we're gonna do to solve this what we're gonna do to solve this so here we are going to have so here we are going to have this uh array here this matrix this uh array here this matrix with one two three four five six seven with one two three four five six seven eight nine okay eight nine okay and so what we could do is we could and so what we could do is we could let's say we have our let's say we have our rows here and we're going to have rows here and we're going to have our columns here okay now what we could our columns here okay now what we could do do is we could initially go ahead and swap is we could initially go ahead and swap everything from the row and column okay everything from the row and column okay so let's say we went ahead and so let's say we went ahead and swapped two and four three and seven swapped two and four three and seven and six and eight okay so what's that and six and eight okay so what's that going to look like going to look like our new matrix is going to be one our new matrix is going to be one four and seven four and seven um two five um two five and eight and then we're going to have and eight and then we're going to have three uh six three uh six and nine okay and nine okay and we can do that with one pass we can and we can do that with one pass we can just iterate through just iterate through the the matrix and just swap the rows the the matrix and just swap the rows from the columns from the columns okay and so now that we have that okay and so now that we have that what we can see here is if you look at what we can see here is if you look at the solution here the solution here it is one two three four five six seven it is one two three four five six seven eight nine eight nine and if you look at after that first swap and if you look at after that first swap we have the answer it's just in reverse we have the answer it's just in reverse order right what we're trying to if we order right what we're trying to if we reverse all reverse all the rows what we're going to get is the rows what we're going to get is we're going to get 7 we're going to get 7 4 1. 4 1. eight five and two eight five and two and nine six and three and nine six and three which is our solution which is our solution okay and so what is our time and space okay and so what is our time and space complexity complexity um it depends on how you want to look at um it depends on how you want to look at it if you want to look at the size of it if you want to look at the size of the array the array then it's going to be quadratic but if then it's going to be quadratic but if we're looking at the we're looking at the the number of cells it's linear so we the number of cells it's linear so we can just say this is going to be can just say this is going to be linear time or o of m as as many cells linear time or o of m as as many cells there are there are in the matrix so time complexity we can in the matrix so time complexity we can get get o of we'll just say of n and then space complexity we're not creating any new space all we're doing is just swapping the variables as we traverse through and then we're reversing it okay so space complexity we can say of okay which isn't bad okay so let's go okay which isn't bad okay so let's go ahead and jump into the code ahead and jump into the code so what we want to do first is we just so what we want to do first is we just want to swap the rows and the columns want to swap the rows and the columns okay so we want to say 4 let okay so we want to say 4 let row equal 0 row is less than okay and so now when we jump into the columns we don't want to go through each column we want to go through the adjacent column to the adjacent row so if we're going to be in row 1 then we want a row 0 then we want column 0. if we're going to go into row 1 we want column 1 and if we're going to go into row 2 we want column 2 as well okay so we're going to set column to row where column is less than matrix of okay and so now all we're doing here is okay and so now all we're doing here is we're just swapping we're just swapping we're just swapping out the values so we're just swapping out the values so matrix of row column matrix of row column is going to be matrix at column row all right so all we did there is we just all right so all we did there is we just went in and we just swapped this we we went in and we just swapped this we we started here started here then we're coming here and we're then we're coming here and we're swapping these two then we're swapping swapping these two then we're swapping this seven with this three this seven with this three and then this eight with this six okay and then this eight with this six okay and now we just need to iterate through and now we just need to iterate through all the rows and reverse them okay and that's all we need to do and that's the solution not too bad not too bad if if you just kind of look at how matrices work and if you can kind of step through each iteration of the like each transformation of the matrix if we transform it by swapping all the rows and columns and then we can see that we have the solution we just need to reverse the let's go ahead and run that and let's go ahead and run that and and we are good okay so we and we are good okay so we we are doing this in constant space and we are doing this in constant space and then o of uh then o of uh the cells o o of n time um the cells o o of n time um and so that's not bad so yeah that is and so that's not bad so yeah that is lead code number 48 lead code number 48 rotate image i hope you enjoyed it and i rotate image i hope you enjoyed it and i will see you all on the next one | 2024-03-20 09:45:39 | 48 | LEETCODE 48 (JAVASCRIPT) | ROTATE IMAGE |
|
oMAeBWdIJ2o | hi everyone welcome to lenovo in this video we will discuss about another video we will discuss about another liquid problem that is the matchsticks liquid problem that is the matchsticks to square to square this is the middle level problem i don't this is the middle level problem i don't see what this question is asking us to see what this question is asking us to do and how we can think of finding a do and how we can think of finding a solution like solution like for this type of questions so uh we'll for this type of questions so uh we'll look into the exact questions but moving look into the exact questions but moving on if you haven't subscribed to this on if you haven't subscribed to this channel make sure to subscribe to this channel make sure to subscribe to this channel for regular lit code videos like channel for regular lit code videos like this this [Music] [Music] so the question says uh look even in dj so the question says uh look even in dj array mastic so this is our masters into array mastic so this is our masters into that given to us and while mastics of i that given to us and while mastics of i like each of the uh elements in the like each of the uh elements in the matrix is that length of i is matrix is that length of i is matchsticks like it says like each of matchsticks like it says like each of the uh like each of the elements in this the uh like each of the elements in this array is the length of uh iphones okay array is the length of uh iphones okay now you want to use all the mastering so now you want to use all the mastering so you need to use uh all the messages you need to use uh all the messages you're gonna request any uh to make one you're gonna request any uh to make one square okay so you need to build a square okay so you need to build a square out of it using all the massive square out of it using all the massive okay i also need to mention that you okay i also need to mention that you shouldn't break any matchsticks that you shouldn't break any matchsticks that you you shouldn't break any matrix okay and you shouldn't break any matrix okay and uh further you can uh link them up uh further you can uh link them up like uh like uh and each matrix must be used exactly and each matrix must be used exactly once so what it exactly means so if if once so what it exactly means so if if there's a matrix of say uh length four there's a matrix of say uh length four over here okay over here okay that's a matchstick of length four uh that's a matchstick of length four uh you cannot do something like you break you cannot do something like you break it in half like a normal sticks of it in half like a normal sticks of length three and a stick of length one length three and a stick of length one you cannot do that or a message of two you cannot do that or a message of two to each you cannot break them in any to each you cannot break them in any order but you need to use the whole order but you need to use the whole mastics uh in a fashion already what you mastics uh in a fashion already what you can do you can uh you can link them up can do you can uh you can link them up that is you have a massive length four that is you have a massive length four so you can have a rustic of length four so you can have a rustic of length four and honestly some other matchsticks same and honestly some other matchsticks same as domestic of length uh one as domestic of length uh one and you can link them up to make a a and you can link them up to make a a bigger one like a five length okay so bigger one like a five length okay so you can link them up you cannot break you can link them up you cannot break them okay them okay but it says you each matchsticks must be but it says you each matchsticks must be used exactly one so you cannot uh use used exactly one so you cannot uh use one matrix multiple times obviously if one matrix multiple times obviously if you are making up a square you cannot do you are making up a square you cannot do uh one message multiple time right so uh uh one message multiple time right so uh ultimately what it asks us to return uh ultimately what it asks us to return uh the ask is uh return true if you can the ask is uh return true if you can make a square or false otherwise so you make a square or false otherwise so you need to check like if you can make a need to check like if you can make a square out of it okay square out of it okay square in the sense what does exactly square in the sense what does exactly mean look here if there are bicycles in mean look here if there are bicycles in the one one two two and two uh then the one one two two and two uh then if we need to make up a square we are if we need to make up a square we are sure that the square has all of its sure that the square has all of its length is equal right so the first thing length is equal right so the first thing we should need to check like was the sum we should need to check like was the sum over here the sum is one plus one plus over here the sum is one plus one plus two plus two plus two so that says uh two plus two plus two so that says uh eight eight being is length so eight eight eight being is length so eight being is left if we just check for the being is left if we just check for the first thing that eight divided by four first thing that eight divided by four is uh our two right so if the is uh our two right so if the modulo of this eight mod four is zero or modulo of this eight mod four is zero or not we can check to find that whether we not we can check to find that whether we can actually do it or not like the first can actually do it or not like the first thing first it can be like this okay now thing first it can be like this okay now see uh if if our length was something see uh if if our length was something like sum of something like nine then how like sum of something like nine then how what would have been so 9 by 4 would what would have been so 9 by 4 would have resulted in 2.25 right so we cannot have resulted in 2.25 right so we cannot break any mastic so how can we go ahead break any mastic so how can we go ahead with the 2.25 value right uh so that's with the 2.25 value right uh so that's not possible so we cannot divide uh like finding the sum and realizing whether we can uh like whether we can actually do it or not like whether is it even possible or not rather before even moving into a solution of moving into the stuff we like what are the difference of what we need to do we can actually realize that if the sum is divisible by 4 then we are sure that we can think of finding a solution to that but if the sum is not divisible by 4 we cannot think of any solution let's do that so 9 is not the case in our example one let's understand what's uh what the case we have away okay we exactly uh like what we did exactly we uh put the two one one on one side but remember this is square so it doesn't matter whether to put it on the left or it would be on the top bottom right okay like it doesn't matter but something you need to realize that you need to keep a note of that but doesn't mean uh you need to check whether our uh particular matrix works in the like if we place two metrics on the right so other matching like massive size shouldn't be equal so you you can place them based on what size they have and where we can put them so this actually there to understand like that we don't have any uh challenge with putting any messages like this one plus one is put two on the right so this can be good on but but that is not the way you should think you that is not the way you should think you should think that if one plus one like should think that if one plus one like if while putting the masking if you are if while putting the masking if you are putting one unit mastics on the left putting one unit mastics on the left the other one will basically can be put the other one will basically can be put on the top bottom can be put on the top on the top bottom can be put on the top can we put on the right can we put on the right exactly so this can happen for the other exactly so this can happen for the other one unit so that is the kind of check one unit so that is the kind of check you need to have over here like if we you need to have over here like if we put one if we exactly put one and one on put one if we exactly put one and one on one side it doesn't matter if the other one side it doesn't matter if the other square is like this or the other square square is like this or the other square is like this or how is exactly square is like this or how is exactly square okay the final answer is actually the okay the final answer is actually the same but we can keep a check while we same but we can keep a check while we are going ahead with this are going ahead with this now uh what exactly we are doing over now uh what exactly we are doing over here we simply place the matrix like here we simply place the matrix like let's understand this example we simply let's understand this example we simply place the matrix and we find that the place the matrix and we find that the square of length 2 so we can have a square of length 2 so we can have a target of like this like 2 being the 8 target of like this like 2 being the 8 by 4 is like sum by 4 is uh our number by 4 is like sum by 4 is uh our number we got so our target value of length we got so our target value of length will be that one early okay so there's a will be that one early okay so there's a square of length two we found and one square of length two we found and one side of the square can uh uh came two side of the square can uh uh came two sticks with length one okay so it says sticks with length one okay so it says that one side of the square is a two that one side of the square is a two strings of lengthwise so let's uh try to strings of lengthwise so let's uh try to understand this uh further okay understand this uh further okay what i mean is so you were given over what i mean is so you were given over here one one uh like this area okay so here one one uh like this area okay so i'm just writing it down in a bigger i'm just writing it down in a bigger format one one uh two two and then two format one one uh two two and then two fine now what exactly we need to do say fine now what exactly we need to do say you see you just took up like uh uh just you see you just took up like uh uh just uh let's see in this manner that you uh let's see in this manner that you just took say there are four corners just took say there are four corners okay so one uh two and then okay so one uh two and then three three okay and then this four so this is the okay and then this four so this is the four corners of our square we have over four corners of our square we have over here five now what we're trying to do we here five now what we're trying to do we uh took up this one uh took up this one fine for this one we now have four fine for this one we now have four positions to place them we can place positions to place them we can place them exactly at this position right we them exactly at this position right we can place them over here we can place can place them over here we can place them over here we can place them over them over here we can place them over here so this was the exact thing i was here so this was the exact thing i was trying to tell my minute earlier that uh trying to tell my minute earlier that uh this initially it doesn't matter like this initially it doesn't matter like the fourth step you may say is all the the fourth step you may say is all the same step yeah so that's true the all same step yeah so that's true the all the four steps are exactly the same but the four steps are exactly the same but it matters when you are going into the it matters when you are going into the further division so like for the first further division so like for the first one we we actually came across four one we we actually came across four places to uh put the first one okay places to uh put the first one okay one in the left one being the right all one in the left one being the right all right okay one being the top one being right okay one being the top one being the uh bottom fine so these are the four the uh bottom fine so these are the four places we have to uh put our uh one like places we have to uh put our uh one like first one can you put in this power okay first one can you put in this power okay so say you say we just went right with so say you say we just went right with this left one for understanding we went this left one for understanding we went ahead with this left one fine ahead with this left one fine now uh let's uh let's see what are the now uh let's uh let's see what are the other cases how we can replace the other other cases how we can replace the other values over here so once we put our left values over here so once we put our left over here now uh we come across the next over here now uh we come across the next one fine now the next one can be again one fine now the next one can be again we have four options for us fine four we have four options for us fine four options for us say we uh uh sorry i just options for us say we uh uh sorry i just took the top one for this case so so took the top one for this case so so let's uh let's change this this is the let's uh let's change this this is the left and this is the top fine left and this is the top fine so this is the top i just i'm just going so this is the top i just i'm just going there first we place it in the top okay there first we place it in the top okay now now we uh find the left right now now we uh find the left right uh left right uh top and bottom fine uh left right uh top and bottom fine now after press the first one we say we now after press the first one we say we took the took the left path forward placing the next one left path forward placing the next one fine for the next one this next one so fine for the next one this next one so we just placed the next one over here we just placed the next one over here fine that's why we place our next one fine that's why we place our next one now we like we had actually four places now we like we had actually four places to put this we can put it in the top as to put this we can put it in the top as well the left right top and bottom is well the left right top and bottom is also available for us now we push the also available for us now we push the next one in the left next we next one in the left next we went to our two right after going to a went to our two right after going to a two two we know that uh it will again have like we know that uh it will again have like four options to be placed right uh four options to be placed right uh that's the that's the two we are trying to place okay so first two we are trying to place okay so first is the left can you put two in the left is the left can you put two in the left okay can you put two in the left no we okay can you put two in the left no we cannot so we look at the right that's cannot so we look at the right that's the second place we have we can put two the second place we have we can put two in the left so we put the two in the in the left so we put the two in the right okay we went ahead with this right okay we went ahead with this particular format now now we again got particular format now now we again got four different uh uh parts to go that is four different uh uh parts to go that is with the second two okay with the second two okay that is with this particular two we got that is with this particular two we got this and again we got four options we this and again we got four options we can you put it in the left no can you can you put it in the left no can you put in the right no now can i put it in put in the right no now can i put it in the top no now we need to put it in the the top no now we need to put it in the button that's the two being placed over button that's the two being placed over here fine so now after this uh we place here fine so now after this uh we place this in the bottom right so once it this in the bottom right so once it places in the bottom we will go ahead places in the bottom we will go ahead with again four step for this uh last with again four step for this uh last two we have over here fine two we have over here fine for this last two we have also four for this last two we have also four options can i put in the left can i put options can i put in the left can i put in the right can i put in the top can in the right can i put in the top can you put it in the bottom no so we find you put it in the bottom no so we find that all the options are closed for us that all the options are closed for us fine so we cannot place our last element fine so we cannot place our last element at any of the places without even at any of the places without even breaking the stick okay but we shouldn't breaking the stick okay but we shouldn't break the stick right so without break the stick right so without breaking the stream we're gonna place it breaking the stream we're gonna place it so the problem is not here problem is so the problem is not here problem is going ahead with the other solution or going ahead with the other solution or with the particular way we chose so we with the particular way we chose so we will simply uh will simply uh we'll simply go back okay we'll simply we'll simply go back okay we'll simply go back each of the steps to find out go back each of the steps to find out what was the step we had over here so what was the step we had over here so initially we took the left for this one initially we took the left for this one but now we find that this is not a case but now we find that this is not a case so we'll so we'll we'll take the right again so we'll take we'll take the right again so we'll take a right for this one we'll again end up a right for this one we'll again end up finding that this is not the case we finding that this is not the case we took the uh top for this one okay we took the uh top for this one okay we will take this path will take this path and i will find four solutions so we and i will find four solutions so we took uh top for this one fine and then took uh top for this one fine and then we found four solutions place the two at we found four solutions place the two at the first two at the left then second to the first two at the left then second to the right the next two will find that the right the next two will find that the left right is not uh failed the top the left right is not uh failed the top is also filled then you'll find the is also filled then you'll find the bottom is limited so once you find that bottom is limited so once you find that all of the uh all of the uh sticks are being placed and all the sticks are being placed and all the sticks are fully uh placed then you find sticks are fully uh placed then you find okay it's possible so we'll find our okay it's possible so we'll find our ultimate solution to equation and then ultimate solution to equation and then we need to return back our answer to we need to return back our answer to this fine so that's the question over this fine so that's the question over here but uh think of some other corner here but uh think of some other corner cases say the length is eight find the cases say the length is eight find the length over here is given as eight but length over here is given as eight but pick up a condition where our stick is pick up a condition where our stick is something like um something like um three three one one two and two two and two can we make a square out of it without can we make a square out of it without breaking breaking no we cannot now like if we sum this up no we cannot now like if we sum this up and divide by four we know the maximum and divide by four we know the maximum length of our stick is uh two that is length of our stick is uh two that is possible uh like two and the two we find possible uh like two and the two we find that we cannot place three anyway fine that we cannot place three anyway fine so this is the kind of corner classes so this is the kind of corner classes that may be there in our equation so we that may be there in our equation so we need to tackle this kind of things also need to tackle this kind of things also so uh so the first thing we need to go so uh so the first thing we need to go ahead with we need to find the sum and ahead with we need to find the sum and divide it by four so we just got a divide it by four so we just got a target say uh t being the what is your target say uh t being the what is your target under me who will be your answer target under me who will be your answer like two will be taking this key so once like two will be taking this key so once you're finding something greater than you're finding something greater than our target we're going to place that our target we're going to place that value so once you cannot place that value so once you cannot place that value that means we cannot find a form value that means we cannot find a form of square out of it okay of square out of it okay but once we can place out the value that but once we can place out the value that is if it's less than our target so we is if it's less than our target so we can place the value and we'll keep going can place the value and we'll keep going with the other all the four uh paths so with the other all the four uh paths so we are getting and we'll keep traversing we are getting and we'll keep traversing on this part so uh this is more or less on this part so uh this is more or less a tree like a structure are you going as a tree like a structure are you going as with the dfs format we are going to the with the dfs format we are going to the depth first and try to finding a depth first and try to finding a solution to that but then you realizing solution to that but then you realizing if it is a lot of solution you go back if it is a lot of solution you go back and then try to form the solution in and then try to form the solution in another format so this is the way you another format so this is the way you will keep traversing keep traversing and will keep traversing keep traversing and ultimately trying to find a solution ultimately trying to find a solution okay okay so that's more or less the kind of so that's more or less the kind of solution we are looking forward to and solution we are looking forward to and now uh let's try to uh run this for like now uh let's try to uh run this for like write this code exactly what how we are write this code exactly what how we are discussing this and uh write this code discussing this and uh write this code so you remember to write exactly this so you remember to write exactly this kind of put you you will need some kind kind of put you you will need some kind of additional memory additionally you of additional memory additionally you need a how many additions we did and like uh another area of length four the fire will place each of the stick at each of the particular indexes so that we can place all the sticks like we are actually dividing with all the sticks in groups of four okay so it's uh just dividing the six in groups of four so let's write this book and again i will explain how the code is working with so here is a solution for over here okay so here is a solution for over here okay so uh what exactly we are doing over so uh what exactly we are doing over here we're doing exactly what we say we here we're doing exactly what we say we are doing we just checked for say which are doing we just checked for say which is the initial one we are finding a sum is the initial one we are finding a sum fine then we are checking like the first fine then we are checking like the first thing was if the mastic is null or thing was if the mastic is null or massive the length is zero so if it's massive the length is zero so if it's zero if there is no massive then there's zero if there is no massive then there's no way we can find the solution right no way we can find the solution right then one time we'll find the sum of all then one time we'll find the sum of all the matrix like all the elements in the the matrix like all the elements in the mastic terms mastic terms and actually finding the sum of four is and actually finding the sum of four is not zero that is if it's uh we find that not zero that is if it's uh we find that uh it's not equally divisible by four uh it's not equally divisible by four like without equality divided both sides like without equality divided both sides then there's no way of going right we then there's no way of going right we just returned a false to that right uh just returned a false to that right uh father what would you do we just sorted father what would you do we just sorted our array to sorted out in the sense uh our array to sorted out in the sense uh so that we can have all the bigger so that we can have all the bigger elements and all the smaller elements in elements and all the smaller elements in the front the reasoning we can place the the front the reasoning we can place the first we can place the first we can place the bigger elements that all the bigger bigger elements that all the bigger elements are up first and then we can elements are up first and then we can place the smaller elements at places place the smaller elements at places where we can actually place them so if where we can actually place them so if this saves our complexity if we just see this saves our complexity if we just see over here uh if i just uh over here uh if i just uh take uh take uh if you just notice over here if we have if you just notice over here if we have something like this something like this that we have uh like a solid like three that we have uh like a solid like three one okay and then four uh four one okay and then four uh four uh the four fine if you have something uh the four fine if you have something like this what you can do is is it good like this what you can do is is it good like if you place one somewhere and then like if you place one somewhere and then find why to place a four it's always find why to place a four it's always better if you just go ahead it's fine better if you just go ahead it's fine placing the four you'll go ahead and placing the four you'll go ahead and replacing the fourth we'll go ahead and replacing the fourth we'll go ahead and placing all the four that's the bigger placing all the four that's the bigger values we have so you place all the values we have so you place all the bigger values now what we are left with bigger values now what we are left with we are actually left with uh facing we are actually left with uh facing three and one so now we are we know that three and one so now we are we know that uh like if we if you look into we don't uh like if we if you look into we don't have multiple choices to place three and have multiple choices to place three and one so for three we can have only one one so for three we can have only one choice to place over here and for one we choice to place over here and for one we can have only one choice in case we can have only one choice in case we cannot place one in case there are some cannot place one in case there are some value like two or something like that or value like two or something like that or something something that we cannot place something something that we cannot place so we know that by default we cannot so we know that by default we cannot place and we cannot place it over here place and we cannot place it over here right so once you're gonna place it over right so once you're gonna place it over here that means it's not possible and here that means it's not possible and there's no there's no point going there's no there's no point going further but if you go ahead with placing further but if you go ahead with placing one at a place fine and then you go one at a place fine and then you go ahead and placing three now three can be ahead and placing three now three can be over here we can place t over here we over here we can place t over here we can uh like three over here or we can can uh like three over here or we can place three over here right or we can place three over here right or we can place three over here so we are going place three over here so we are going under multiple choices for us fine so under multiple choices for us fine so the choice becomes so much more so to the choice becomes so much more so to reduce that kind of small complexity we reduce that kind of small complexity we just uh like to reduce some of the small just uh like to reduce some of the small cases we get so we just place all the cases we get so we just place all the bigger values we have all the bigger bigger values we have all the bigger values we have in our array so let's go values we have in our array so let's go ahead and place them fill all the places ahead and place them fill all the places and now whatever is left with us is we and now whatever is left with us is we will press like a smaller whole place in will press like a smaller whole place in the other corners so that we can find a the other corners so that we can find a better solution like on a faster fellow better solution like on a faster fellow we can go out with it we can go out with it right uh so that's more or less the right uh so that's more or less the question is all about i hope question is all about i hope this i will go ahead i'll tell you that this i will go ahead i'll tell you that okay next week okay next week we took a we took a for the length four so that we can keep for the length four so that we can keep each of the side in our place next we've each of the side in our place next we've got the massive minus one so that we can got the massive minus one so that we can start with our uh right most elements so start with our uh right most elements so that's what that means is the index we that's what that means is the index we are going with and then some by fours on are going with and then some by fours on my phone being a target we shouldn't uh my phone being a target we shouldn't uh put any of the uh sides being greater put any of the uh sides being greater than our target right so that's our uh than our target right so that's our uh objective over here now if our index is objective over here now if our index is minus one like if we uh keep on minus one like if we uh keep on traversing from the right to the left if traversing from the right to the left if we traverse this this and after that if we traverse this this and after that if you read something like minus one that you read something like minus one that means we reached our time so we got true means we reached our time so we got true okay fine we need to stop tracking now okay fine we need to stop tracking now what do we do when that is index at this position and we find that the sum plus our matrix index like whatever the matrix index is pointing to okay so if that is greater than target like that this is greater than our target follower we shouldn't go right we should simply continue the value or if the sum i or some i minus 1 is same so that means if our uh sum i i minus 1 is the same value that is we already placed 4 over here 4 over here 4 over here so some i and i minus one are same values then what's the point of going ahead like uh right we already place those first so there's no point at uh position i so we we don't need to go into questionnaire so go ahead with other positions where it is like there is a difference right so that's why i can do this like we just continue the loop this happens when we just placed all the four values so four four four are already there and i find that some i like four plus say three is greater than target we contribute four plus uh like all the focus is here and there is having the last time you have so they are what you need we simply need some i that's messy index index is pointing at three fine sum i plus equivalence will just plus this value we said in this version and then we put uh went ahead with our uh further dfs dfs into what gives us i minus so just move the english a bit lesser fine now uh what for the we are not finding a solution to that we are not finding a solution to that what we will do we will simply subtract what we will do we will simply subtract this like we place the uh stick over at this like we place the uh stick over at this place and then we will remove that this place and then we will remove that stick from the place thinking that can stick from the place thinking that can you find a different way to do that you find a different way to do that fine so we just went ahead with the fine so we just went ahead with the solution like this but ultimately we solution like this but ultimately we will simply do this uh like put up the will simply do this uh like put up the places stick if we're ultimately gonna places stick if we're ultimately gonna find a solution we'll revert back and find a solution we'll revert back and take up the stickers like replace the take up the stickers like replace the stabilizer so that's what the idea is stabilizer so that's what the idea is once you in between if you find that this is a solution possible then we simply go ahead with uh like returning truth to our ultimate answer but in case it is not really done that okay this is not a possible solution this is all our ideas all about so i uh uh [Music] | 2024-03-22 15:21:15 | 473 | Matchsticks to Square | Recursion | Optimization | LeetCode 473 | Learn Overflow |
|
olbiZ-EOSig | hey everyone welcome back and let's write some more neat code today so today write some more neat code today so today let's solve the problem check let's solve the problem check completeness of a binary tree we're completeness of a binary tree we're given the root of a binary tree and we given the root of a binary tree and we just want to check if it is a complete just want to check if it is a complete binary tree which by definition is a binary tree which by definition is a tree where every single level in the tree where every single level in the tree is completely full except possibly tree is completely full except possibly the last level if the last level is not the last level if the last level is not full then it has to be filled from left full then it has to be filled from left to right so here you can see it does to right so here you can see it does have a single missing node but the have a single missing node but the missing node is all the way on the right missing node is all the way on the right side so the existing nodes are filled in side so the existing nodes are filled in from the left side now suppose this node from the left side now suppose this node over here was missing then it's not a over here was missing then it's not a complete binary tree because we have a complete binary tree because we have a node here but we also have a node here node here but we also have a node here they're not filled from left to right we they're not filled from left to right we have a missing one right here now if we have a missing one right here now if we had all four nodes then it is all also a had all four nodes then it is all also a complete binary tree so conceptually complete binary tree so conceptually this problem is pretty simple by looking this problem is pretty simple by looking at it it's pretty easy to tell if we at it it's pretty easy to tell if we have a complete binary tree or not and have a complete binary tree or not and algorithmically we know there's not a algorithmically we know there's not a ton of different algorithms we can run ton of different algorithms we can run on a binary tree usually it's DFS but on a binary tree usually it's DFS but the less common one is breadth first the less common one is breadth first search which one do you think is going search which one do you think is going to be more useful in this case probably to be more useful in this case probably breadth first search which is basically breadth first search which is basically a level order traversal we're going to a level order traversal we're going to Traverse it level by level because Traverse it level by level because that's probably what's going to allow us that's probably what's going to allow us to know if the last level is filled from to know if the last level is filled from left to right so suppose we have the left to right so suppose we have the same binary tree over here well same binary tree over here well structurally the same the values are structurally the same the values are pretty much irrelevant so I'm not even pretty much irrelevant so I'm not even going to put them in here because they going to put them in here because they just serve as a distraction for us in just serve as a distraction for us in this problem as we're doing a breadth this problem as we're doing a breadth first search on this problem we're going first search on this problem we're going to have a Q data structure this is going to have a Q data structure this is going to be inside of our queue we're going to to be inside of our queue we're going to pop this and then add its two children pop this and then add its two children to the queue and then we're gonna pop to the queue and then we're gonna pop the left child over here and then append the left child over here and then append its children to the queue and then we're its children to the queue and then we're gonna pop this next guy over here append gonna pop this next guy over here append its children it has one child here and its children it has one child here and it has null over here and then we're it has null over here and then we're gonna pop this guy and pop this guy and gonna pop this guy and pop this guy and pop this guy and also append their pop this guy and also append their children which are gonna be null and children which are gonna be null and then once we have a cue full of nulls then once we have a cue full of nulls which is what's gonna happen in this which is what's gonna happen in this case that's how our algorithm is going case that's how our algorithm is going to terminate but how do we know at the to terminate but how do we know at the end is it a complete binary tree or not end is it a complete binary tree or not well think about it like this for the well think about it like this for the last level we expect that eventually we last level we expect that eventually we will have some nulls either there's will have some nulls either there's going to be a null here which is going going to be a null here which is going to be the case for this problem or maybe to be the case for this problem or maybe this entire level is going to be full we this entire level is going to be full we have a node over here but then the last have a node over here but then the last level is just going to be full of nulls level is just going to be full of nulls so basically when we reach our first so basically when we reach our first null value we expect that every other null value we expect that every other value we pop after that is also going to value we pop after that is also going to be null that's how you know it's a be null that's how you know it's a complete binary tree whether it's in the complete binary tree whether it's in the last level or whether it's in like the last level or whether it's in like the existing level maybe this node doesn't existing level maybe this node doesn't exist either we have two null values exist either we have two null values over here we expect there not to be a over here we expect there not to be a situation like this where there's an situation like this where there's an existing node here but there's not a existing node here but there's not a node here we pop this guy it's non-null node here we pop this guy it's non-null we pop this guy it's non-null we pop we pop this guy it's non-null we pop this it's a null value and then after this it's a null value and then after that we do not expect to see a non-null that we do not expect to see a non-null value over here if we do then it's not a value over here if we do then it's not a complete binary tree now there's one complete binary tree now there's one last Edge case you might be thinking last Edge case you might be thinking about what if we have a situation like about what if we have a situation like this where yes there's a null in this this where yes there's a null in this level but what if this is not not the level but what if this is not not the last level what if over here this node last level what if over here this node also has a couple also has a couple non-null children does the algorithm I non-null children does the algorithm I just described still work for this tree just described still work for this tree let's test it out let's say we pop all let's test it out let's say we pop all of these and then we get to this level of these and then we get to this level we pop this append its two children pop we pop this append its two children pop this append its two children which are this append its two children which are null pop this append its children and null pop this append its children and then we get here we pop it we see okay then we get here we pop it we see okay it's a null value now we expect that it's a null value now we expect that everything we pop should also be null everything we pop should also be null and if it's not the case that means this and if it's not the case that means this is not a complete binary tree so next is not a complete binary tree so next we're going to pop these two notice how we're going to pop these two notice how it's not null so that means this is not it's not null so that means this is not a complete binary tree so you can see a complete binary tree so you can see that this pretty basic algorithm does that this pretty basic algorithm does work for pretty much every structure it work for pretty much every structure it will tell us whether a tree is a will tell us whether a tree is a complete binary tree or not and since complete binary tree or not and since since we're just doing a pretty basic since we're just doing a pretty basic breadth first search the overall time breadth first search the overall time complexity is going to be Big O of n complexity is going to be Big O of n that's also going to be the memory that's also going to be the memory complexity in the worst case so now complexity in the worst case so now let's code it up so as with every let's code it up so as with every breadth first search you want to start breadth first search you want to start with a Q we're guaranteed that the root with a Q we're guaranteed that the root is going to be non-null but that is going to be non-null but that wouldn't matter the way I'm going to wouldn't matter the way I'm going to code this up anyway but I'm going to code this up anyway but I'm going to initialize this cue with the root value initialize this cue with the root value we have to pass in an array to we have to pass in an array to initialize the queue so next we're going initialize the queue so next we're going to run our breadth first search while to run our breadth first search while the Q is non-empty we're going to pop the Q is non-empty we're going to pop from the queue we pop from the left side from the queue we pop from the left side because we're going to be pushing to the because we're going to be pushing to the right side it's important to do it this right side it's important to do it this way because we want to Traverse every way because we want to Traverse every level from left to right so when we pop level from left to right so when we pop the node we want to take the node's the node we want to take the node's children and append them to the queue so children and append them to the queue so node.left and append node Dot right but node.left and append node Dot right but it's possible as we're appending it's possible as we're appending children to the queue that we end up children to the queue that we end up appending a null value to the queue it's appending a null value to the queue it's also possible that the root could have also possible that the root could have been null so before we try appending its been null so before we try appending its children we have to first make sure that children we have to first make sure that the node itself is non-null so let's the node itself is non-null so let's make sure if the node is non-nulled then make sure if the node is non-nulled then we append its children but what if the we append its children but what if the node is null remember that's important node is null remember that's important because that's what's going to tell us because that's what's going to tell us whether we have a complete binary tree whether we have a complete binary tree or not so when we do have a null node or not so when we do have a null node then we're going to run some different then we're going to run some different logic here at this point we expect every logic here at this point we expect every node that we pop to be null so we're node that we pop to be null so we're going to say while Q let's just do the going to say while Q let's just do the same thing we kind of did up above here same thing we kind of did up above here except we're going to do it slightly except we're going to do it slightly differently we're going to say Q pop differently we're going to say Q pop left we're also going to call this node left we're also going to call this node but that's not really super important but that's not really super important but we want to make sure that this thing but we want to make sure that this thing that were popping and actually we don't that were popping and actually we don't even need to assign it to a variable even need to assign it to a variable we're going to check if this node that we're going to check if this node that we just popped is non-null then we have we just popped is non-null then we have to return false because we were to return false because we were expecting everything to be null but now expecting everything to be null but now we found a non-null node that means this we found a non-null node that means this is not a complete binary tree so we is not a complete binary tree so we return false now if we never execute return false now if we never execute this meaning we never execute this false this meaning we never execute this false we're definitely going to execute this we're definitely going to execute this while loop then our Q is going to be while loop then our Q is going to be empty then we're going to come up here empty then we're going to come up here and we're going to exit out of this loop and we're going to exit out of this loop as well and then out here we can go as well and then out here we can go ahead and return true because we know we ahead and return true because we know we do have a complete binary tree so now do have a complete binary tree so now let's run it to make sure that it works let's run it to make sure that it works and as you can see yes it does it's and as you can see yes it does it's pretty efficient even though the pretty efficient even though the runtimes on leak code are random if this runtimes on leak code are random if this was helpful please like And subscribe if was helpful please like And subscribe if you're preparing for coding interviews you're preparing for coding interviews check out neco.io it has a ton of free check out neco.io it has a ton of free resources to help you prepare thanks for resources to help you prepare thanks for watching and hopefully I'll see you watching and hopefully I'll see you pretty soon | 2024-03-25 12:19:04 | 958 | Check Completeness of a Binary Tree - Leetcode 958 - Python |
|
smTnSl6UKi0 | Hey gas, so today we are going to do dynamic programming playlist. Okay but friend, before I start, Okay but friend, before I start, I want to clear one thing very clearly, the solution means I will tell the question, I will solution means I will tell the question, I will also tell the solution and also also tell the solution and also samjhaunga the solution very well, okay samjhaunga the solution very well, okay but. but. will be a separate place for the concepts and fundamentals of DP. will be a separate place for the concepts and fundamentals of DP. Okay, so in this playlist, I will explain the questions Okay, so in this playlist, I will explain the questions well, samjhaunga solution also well, well, samjhaunga solution also well, how I am how I am approaching it, approaching it, if you want to learn the fundamentals. if you want to learn the fundamentals. if you want to learn the fundamentals. learn the concepts of DP, then there will be a separate place for that. Okay, so moving ahead, today we are going to do medium level question number 135. The name of the question is Minimum Difficulty of Jobs Schedule Dunn's question has been Dunn's question has been Dunn's question has been asked recently in the interview of Amazon. asked recently in the interview of Amazon. Okay, this question has been Okay, this question has been asked recently in the interview of Amazon. asked recently in the interview of Amazon. Okay, so this question is quite good Okay, so this question is quite good and a little bit difficult but if you understand it, it will be solved and a little bit difficult but if you understand it, it will be solved easily. Okay, let's easily. Okay, let's see. see. see. given in the input that you will have one billion. Okay, that shows the difficulty of the job. Okay, that means there is and it is not necessary that it will be sorted, and it is not necessary that it will be sorted, none in descending ascending. none in descending ascending. none in descending ascending. possible that this input has been given in the order and look, look, I have written the important points of the question here. Okay, so first of all, jobs are dependent, what does it mean that today I take You did one job, it You did one job, it You did one job, it is okay and the next day you are saying no, the is okay and the next day you are saying no, the next day you are saying let's do the three, it is next day you are saying let's do the three, it is not so, if you are not so, if you are doing the three, then you will have to doing the three, then you will have to do the same jobs as before. do the same jobs as before. do the same jobs as before. okay, it means it is job dependent, now you okay, it means it is job dependent, now you can do it only when you have completed your four punches and six. can do it only when you have completed your four punches and six. Okay, so the first point is, Okay, so the first point is, let's move ahead and you have to do at let's move ahead and you have to do at least one task every day. You are not someone. least one task every day. You are not someone. least one task every day. You are not someone. can't sit idle even for a day. Let's take someone else's job. If you do three jobs in one take someone else's job. If you do three jobs in one day, it's okay. Whatever difficulty he faces in the day, whatever okay. Whatever difficulty he faces in the day, whatever difficulty he faces in the day, whatever is the difficulty he faces in the day, whatever is the maximum in these three, it is The difficulty of the day is ok, The difficulty of the day is ok, The difficulty of the day is ok, okay, now what you have to do is that you have to okay, now what you have to do is that you have to reduce it every day, it is okay to do the job every day reduce it every day, it is okay to do the job every day and you have to keep the difficulties of every day and you have to keep the difficulties of every day and add the difficulties of all the days, and add the difficulties of all the days, okay okay maybe. 654321. How many days do we have? We have given two days. 654321. How many days do we have? We have given two days. D = 2. Let's D = 2. Let's reduce these two on our first day. If the reduce these two on our first day. If the number is okay in the van, then number is okay in the van, then who is the maximum among the two? It is 6. Okay, that's it. who is the maximum among the two? It is 6. Okay, that's it. who is the maximum among the two? It is 6. Okay, that's it. what did you do that on the second day you have only one day left, now you have to do all the tasks, right, you cannot leave any job, okay, so on the second day you will do all these tasks, which is the maximum among them, then it is four. Add the maximum of both the days, how much will come, 10 will come, 6 plus 4, 10, let's say this is your 10, because initially you did 6 and 5, then you did 4, 3, 2, 1. You changed first you did it. 654321 man, there are three in it, I am getting even less, this is what you have to find out the minimum difficulty of the whole country, then collect from this, if it is done, then collect from all, see, which is our solution, which is our answer, what is that? Okay I have done all this in the first day okay give this equal tu tu mein so who is the maximum of this first day 6 who is the maximum of the second day van so what will be my answer If this is not the If this is not the If this is not the output, then you can do only six on the first day because you do not have to do one task every day, there are other tasks in it, other tasks in it, then you must be having a little idea then you must be having a little idea of solution So it must have been So it must have been So it must have been that there is a question of dynamic programming that there is a question of dynamic programming so I can do so I can do this that first I will start thinking that I just this that first I will start thinking that I just took the first task in the first day in D = took the first task in the first day in D = 1, okay, 1, okay, after that in the remaining days I took the first task. after that in the remaining days I took the first task. after that in the remaining days I took the first task. now what we did was that how many are left, three, two, one, okay, and then made another recursive call, let's solve this function, okay, then in this, we will think the same that in the first day, we then in this, we will think the same that in the first day, we took the punch, only took the punch, only then the rest. then the rest. then the rest. Brother give four three two one nickel. properly, you will understand properly, you will understand what is going on. Here, using this example, let us see how we Okay, now look, right now I have Okay, now look, right now I have Okay, now look, right now I have two days right now and I have a lot of two days right now and I have a lot of jobs to do in these two days. Okay, jobs to do in these two days. Okay, what I said in the beginning that what I what I said in the beginning that what I do, do, I will only pick the one with i = zero. Okay, I will only pick the one with i = zero. Okay, this is my indexing. this is my indexing. What is the maximum difficulty? I did only one job in the first day, so the maximum only one job in the first day, so the maximum difficulty will also be the same, so the maximum difficulty will also be the same, so the maximum difficulty has become six. Okay, the difficulty of the first day has difficulty has become six. Okay, the difficulty of the first day has What's What's left with me, six, now I have taken out six, now I will call Recojan, right, friend, to solve one, what else will I have, five, four, three, one, so on the first day, I have one, so on the first day, I have done six, okay, so in the beginning, my done six, okay, so in the beginning, my done six, okay, so in the beginning, my two days, now I have only one day left, okay, now one day is left, so how is this base, one day is left and you don't have so many jobs, you will have to do all the jobs, otherwise you can do all the jobs, okay? So, now you give it to Max equal to you. There So, now you give it to Max equal to you. There was only one day left, so you punched out and was only one day left, so you punched out and returned it. Here I am 11, the difficulty is It is It is It is clear till now, now see what happens because of man, okay, this one what happens because of man, okay, this one who gives our result, okay, okay, now what I am saying is that I now what I am saying is that I will make it equal to zero also, will make it equal to zero also, okay, so I did this and did this too, okay, so I did this and did this too, okay okay okay punches, then what will be the max difficulty? On the first day, I have done six more punches. If I first day, I have done six more punches. If I come on the second day, then give it come on the second day, then give it equal. There is only one day left, so only one equal. There is only one day left, so only one day. day. day. and Magazine Devan is left, I have only one day left, so how can I do it, you will have to do all the tasks, so now leave for here, you have done all the tasks and you have taken out the Yes, what will happen, Yes, what will happen, Yes, what will happen, which is the maximum among these, if it is three, then three is returned + 3, I have collected more than that, I have collected only from 11, I have I have collected more than that, I have collected only from 11, I have collected only from 10, okay, so let's collected only from 10, okay, so let's see, so see, so now I am saying that it is possible or not, I am 6. now I am saying that it is possible or not, I am 6. now I am saying that it is possible or not, I am 6. will do 5 and 4 and I will also do 3 in the very first day. I will do 3 in the very first day. So I have done 6543 in the very first day and which of these is my max? Hey, Hey, Hey, what are two left for me and one is left, what are two left for me and one is left, and only Devan is left, so this is the base case, okay, then and only Devan is left, so this is the base case, okay, then do both the tasks quietly and do both the tasks quietly and what is the maximum given, I had a base case, so I returned two, Maximum difficulty Maximum difficulty Maximum difficulty added, Maximum difficulty of the first day, added, Maximum difficulty of the first day, six, Maximum difficulty of the second day, you are six, Maximum difficulty of the second day, you are fine, I am fine, I am getting better answers, I getting better answers, I want the minimum of these, isn't it the minimum of the ones that have come after adding the difficulty of the entire country, ok brother. There is only one, I have returned it, I saying that I will complete all the tasks in the first day, because you should not let any day because you should not let any day happen in which you do not have even a single task left. happen in which you do not have even a single task left. Okay, this is clear, Okay, this is clear, so till now you must have understood so till now you must have understood that brother, we have to that brother, we have to write a simple for loop, zero is my index, let's take man, okay I you will have to keep coming out the maximum, okay, you will have to keep coming out the maximum, okay, you will have to keep coming out the maximum, Now my new element will Now my new element will Now my new element will come and I will solve it, once I get a result that brother, if I did only zero intake in the first day, what result will come? Is it okay if I did zero intake on the first I did the job only on the I did the job only on the I did the job only on the first day, so its max di will be first day, so its max di will be added, plus what I was saying is that they will call Recjan, what will I say in that, brother di - 1 that they will call Recjan, what will I say in that, brother di - 1 will be saved for that and the index will increase, okay, the result that came from that, the result that came from that. I will make the final result, the final result is ok and I will keep getting the minimum every time, now I have understood exactly what I have now I have understood exactly what I have written that I started from index i = index written that I started from index i = index zero, ok in the beginning zero, ok in the beginning I just I just I just is fine, you have done the first one, and I am checking, after adding the maximum difficulty of the first job, and then solving the remaining ones, it is okay, who will I catch? and after that I will add six and what will I say this time, so you mean I am saying that you should you mean I am saying that you should solve from index 2 onwards, solve from index 2 onwards, okay then see, what I told you is okay then see, what I told you is doing exactly the same that one- doing exactly the same that one- doing exactly the same that one- took one element first, checked the rest, okay then I am saying no, I will not solve one element, I will solve these two again, then I am saying and checked the rest, then you are seeing the They are increasing, They are increasing, They are increasing, I just checked, after that I just checked, after that I sent it from I Plus van asking you to I sent it from I Plus van asking you to give me the minimum nickel for it, it's okay, it will be like this for us, it's okay and Han Rikjan is calling, so you can also do memories. store the days thing in it, we will store the index thing in it, okay and we will and as the results keep coming, we will and as the results keep coming, we will keep storing the results of our analysis in it and keep storing the results of our analysis in it and as soon as we came to know in any such stage, as soon as we came to know in any such stage, Deepika Before that, you had to understand that this Before that, you had to understand that this Before that, you had to understand that this is the part that I have shown, which is the remaining solution. You are making a recursive call for it and your expecting call will bring me the correct result. Okay, so it is exactly like the story Court also does this, we will Court also does this, we will Court also does this, we will write the code from it, okay and we will do the write the code from it, okay and we will do the memorization in Excel last memorization in Excel last so that we do not get a single set of time limit, it is so that we do not get a single set of time limit, it is okay for us line by line so that it gets cleared better, okay then look, the question is exactly the same as I Okay, now you understand the points that I have Okay, now you understand the points that I have Okay, now you understand the points that I have written, now after written, now after reading this question, you will reading this question, you will start understanding, the question explanation is a bit start understanding, the question explanation is a bit tricky, it is just that, you have to tricky, it is just that, you have to read it carefully to understand, but what I read it carefully to understand, but what I explained in the video. explained in the video. explained in the video. read and understand the points which were told to you while doing the court, then after that a question will start to be understood. Okay, and I had explained it to you with the example, so let's start doing the court exactly as So friend, let's find out the So friend, let's find out the So friend, let's find out the name n which is the difficulty of your name n which is the difficulty of your job. Difficulty variable is very big, so job. Difficulty variable is very big, so I will make it smaller, I will say JD, I will make it smaller, I will say JD, okay, gd.ise, okay, we have found out the size, okay, Yes, an Yes, an Yes, an example has been given that I have a total of three jobs and how many days have I been given, I have been given four days, it means that you will do one job every day, otherwise it means that you will do one job every day, otherwise one day will be left free for you, brother, I have three one day will be left free for you, brother, I have three jobs and four more days. jobs and four more days. jobs and four more days. so in that case you have to return -1. Okay, and what I said is that we Okay, and what I said is that we write a recursive recursive function which write a recursive recursive function which will solve our question. will solve our question. Okay, in that we send JD and send the size. Okay, in that we send JD and send the size. Okay, in that we send JD and send the size. give the index from where to start, the index is zero. First I will say that brother, I have to start from zero. I have chosen the first one, okay and I have sent the number of days. So now let's write its solution. Ok and solve. Vector of end k di Then we will loop out for Then we will loop out for This is the base case here. I comment here. This is the base case here. I comment here. I am the only one in the left remaining jobs Return it's key first I will take I index I 0 or end van take both or index ID index okay so see brick max which is my final result okay I had said possibility is ok saying to check all the possibilities of the van job children's children's jobs in the remaining days then the jobs in the remaining days then the total minimum result that will come to me will be total minimum result that will come to me will be something. Okay, now look, you will have to keep max coming out every time [Music] [ Okay and finally, Okay and finally, after trying all these, I will store my final result and after trying all these, I will store my final result and return it here, final is okay, so Our solution is exactly as told, let's Our solution is exactly as told, let's Our solution is exactly as told, let's run it once and see that our submission has been accepted. Let's see after submitting. Okay, why is the time limit giving one seat Okay, why is the time limit giving one seat because we have not yet done the memorization? There are because we have not yet done the memorization? There are a lot of recension calls. a lot of recension calls. a lot of recension calls. a lot of repetitive results will come, if we reduce one, what did I say that I will take one, look, two parameters are changing, our request is only in the call, two parameters are changing, 1 Ok 1 Ok 1 Ok then it's then it's ok who will store it now see what all the ok who will store it now see what all the changes are happening, if the index is changing then let's check the changes are happening, if the index is changing then let's check the maximum limit of both, maximum limit of both, index from constant means it is going up to 300, so I take it till 301 Do, I took 11. Okay, now I will check before doing the recursive call. Okay, let me initialize it from mines van se, which is ours. I set t - 1 size of t from mines van se, I have not The cash that we have is The cash that we have is The cash that we have is also called cash, either I call it also called cash, either I call it cash or it is fine, I have stored it in cash or it is fine, I have stored it in it, it is fine, now before making the recension call here, it, it is fine, now before making the recension call here, check brother's off check brother's off mines If there If there If there is no mines van here, then it means it has been stored, is no mines van here, then it means it has been stored, then we will attend. Okay, so now if we then we will attend. Okay, so now if we submit it, then most of the family will be submitted submit it, then most of the family will be submitted because I had because I had solved this question a little while ago, look at it, it has been submitted, solved this question a little while ago, look at it, it has been submitted, neither did it come. neither did it come. neither did it come. and this is your memorization technique, okay, there is another good technique, it is called bottom approach, this is top down approach, okay, there is also a bottom up approach, there Banagi But this is the Banagi But this is the Banagi But this is the most basic and best method most basic and best method Reconc Plus Memorization because in DP I Reconc Plus Memorization because in DP I memorize it. Okay, if you have any doubt in this then | 2024-03-20 12:28:43 | 1,335 | Minimum Difficulty of a Job Schedule | Recursion | Memoization | Amazon | Leetcode 1335 |
|
wBPoEm3r3EA | hey everyone welcome back and let's write some more neat code today so today write some more neat code today so today let's solve the problem maximum product let's solve the problem maximum product difference between two pairs a pair is difference between two pairs a pair is defined as two numbers and the product defined as two numbers and the product difference between two different pairs difference between two different pairs is defined as the product of the first is defined as the product of the first pair a * B subtracted by the product of pair a * B subtracted by the product of the second pair which is C * D so this the second pair which is C * D so this is just the definition now in terms of is just the definition now in terms of like the example given an input array like the example given an input array like this which is guaranteed to only like this which is guaranteed to only contain positive integers and is going contain positive integers and is going to have at least four elements in it we to have at least four elements in it we want to choose four distinct elements want to choose four distinct elements from the array such that we maximize from the array such that we maximize this formula initially you might think this formula initially you might think let's just brute force it but actually let's just brute force it but actually this is math and we can try to notice this is math and we can try to notice some patterns which there are here what some patterns which there are here what do you think is going to lead us to do you think is going to lead us to maximize this formula we probably want maximize this formula we probably want to maximize this left side and we to maximize this left side and we probably want to minimize this right probably want to minimize this right side because we're adding this amount side because we're adding this amount and we're subtracting this amount okay and we're subtracting this amount okay how do we do that well when you're just how do we do that well when you're just taking the product of two numbers you taking the product of two numbers you probably want to maximize each probably want to maximize each individual number cuz the product of individual number cuz the product of those then is also going to be maximized those then is also going to be maximized when you want to minimize the product of when you want to minimize the product of two numbers you probably just want to two numbers you probably just want to minimize the those individual numbers minimize the those individual numbers once you understand all of that you once you understand all of that you realize what this problem is really realize what this problem is really asking for is find the two maximum asking for is find the two maximum elements from the array they have to be elements from the array they have to be distinct and also find the two minimum distinct and also find the two minimum elements from the array and they also elements from the array and they also have to be distinct once you've done have to be distinct once you've done that you can pretty much just apply this that you can pretty much just apply this formula and then return the result formula and then return the result because that's what we're trying to do because that's what we're trying to do here return the product difference here return the product difference between these two pairs so so how between these two pairs so so how exactly do we do that your mind might exactly do we do that your mind might jump to just iterating over the two jump to just iterating over the two arrays and try to find the two Max and arrays and try to find the two Max and two minimum elements but there's two minimum elements but there's actually an easier way to do this we can actually an easier way to do this we can rearrange the array if we want the rearrange the array if we want the maximum elements and the minimum maximum elements and the minimum elements it probably makes sense to take elements it probably makes sense to take the input array and sort it because when the input array and sort it because when you do that we have pretty much solve you do that we have pretty much solve the problem because think of it if you the problem because think of it if you had four numbers and you sort them they had four numbers and you sort them they look like this 1 2 3 four what do you do look like this 1 2 3 four what do you do these are the two maximum elements these these are the two maximum elements these are the two minimum elements we can are the two minimum elements we can apply the formula we just solved the apply the formula we just solved the problem the downside of this solution is problem the downside of this solution is the time complexity is going to come the time complexity is going to come from the Sorting which is going to be n from the Sorting which is going to be n log n no extra memory needed though log n no extra memory needed though depending on how the Sorting is depending on how the Sorting is implemented I assume you're not going to implemented I assume you're not going to implement that from scratch you're implement that from scratch you're probably just going to use like a probably just going to use like a library method now can we do better yes library method now can we do better yes we can because as I talked about the we can because as I talked about the solution where we just iterate over the solution where we just iterate over the the array and try to find the two Max the array and try to find the two Max and two minimum elements if we can and two minimum elements if we can implement it correctly is going to be implement it correctly is going to be Big O of N and also no extra space Big O of N and also no extra space needed so that is the target solution needed so that is the target solution before I explain this solution I do want before I explain this solution I do want to mention you might forget that there to mention you might forget that there is another way to sort numbers with a is another way to sort numbers with a data structure called a heap and you data structure called a heap and you might forget that because the Sorting might forget that because the Sorting solution is just so simple but actually solution is just so simple but actually we can solve this problem with a heap we can solve this problem with a heap and I think we'll actually need two and I think we'll actually need two heaps that can actually also be done in heaps that can actually also be done in Big O of end time now the downside is Big O of end time now the downside is since we are using a heap we're going to since we are using a heap we're going to need extra space I'll briefly explain need extra space I'll briefly explain the solution for that what we would do the solution for that what we would do is first create a Max Heap from all is first create a Max Heap from all these elements we would do that with a these elements we would do that with a method called heapify which actually method called heapify which actually runs in Big O of end time and once we've runs in Big O of end time and once we've done that we created the max Heap we can done that we created the max Heap we can easily get the two maximum elements just easily get the two maximum elements just by popping from that Max Heap twice each by popping from that Max Heap twice each pop is going to be log n so the overall pop is going to be log n so the overall time complexity of getting the two Max time complexity of getting the two Max elements is going to be n plus log n and elements is going to be n plus log n and of course n is bigger than login so we of course n is bigger than login so we can just forget this term and we would can just forget this term and we would do pretty much the exact same thing to do pretty much the exact same thing to find the minimum elements only find the minimum elements only difference is we would also create a Min difference is we would also create a Min Heap to do that then we pretty much have Heap to do that then we pretty much have solved the problem once we found these solved the problem once we found these elements we can apply this formula okay elements we can apply this formula okay so that's the Heap solution I won't code so that's the Heap solution I won't code it up because there is a more efficient it up because there is a more efficient solution that doesn't take extra memory solution that doesn't take extra memory it is finding these two elements now the it is finding these two elements now the question is how do we do it well for the question is how do we do it well for the most part I think it's just going to be most part I think it's just going to be easier if I explain it within the code easier if I explain it within the code but I want to give you a bit of the but I want to give you a bit of the intuition so let's say these are our intuition so let's say these are our numbers we're going to keep track of the numbers we're going to keep track of the max element I'm going to call that Max max element I'm going to call that Max one and we're going to keep track of the one and we're going to keep track of the second largest element I'm going to call second largest element I'm going to call that Max 2 and we're going to do the that Max 2 and we're going to do the same thing with the minimum elements the same thing with the minimum elements the most minimum is going to be Min one and most minimum is going to be Min one and I'm going to call the second smallest I'm going to call the second smallest element Min 2 we're going to keep track element Min 2 we're going to keep track of these in these variables since we're of these in these variables since we're trying to maximize these elements let's trying to maximize these elements let's initialize them to small numbers they initialize them to small numbers they will be initialized to zero both of them will be initialized to zero both of them since we're trying to minimize these since we're trying to minimize these let's initialize them to large numbers let's initialize them to large numbers they will be initialized to Infinity they will be initialized to Infinity initially what we're going to do here initially what we're going to do here and I guess I should add the second one and I guess I should add the second one for each of these two at a high level for each of these two at a high level we're going to iterate over every we're going to iterate over every element in the input array by the time element in the input array by the time we've gone through this entire array we we've gone through this entire array we should have picked out the two large should have picked out the two large lest numbers in this case six and seven lest numbers in this case six and seven and assign them to these two variables and assign them to these two variables seven will be first because Max one is seven will be first because Max one is the largest Six will be second cuz it's the largest Six will be second cuz it's uh the second largest and we're going to uh the second largest and we're going to do the same thing with the minimum do the same thing with the minimum elements so two and four are the elements so two and four are the smallest two is going to go here and smallest two is going to go here and four is going to go here the smallest is four is going to go here the smallest is going to be two and second smallest is going to be two and second smallest is four then we found our solution and you four then we found our solution and you notice something as long as we put the notice something as long as we put the two largest numbers here and the two two largest numbers here and the two smallest numbers here we actually smallest numbers here we actually guarantee that there won't be overlaps guarantee that there won't be overlaps between these because how could it be between these because how could it be possible that we did not choose four possible that we did not choose four distinct integers if we do that the only distinct integers if we do that the only way that would be theoretically possible way that would be theoretically possible is if the two largest numbers also is if the two largest numbers also happen to be the same as the two happen to be the same as the two smallest numbers how would that be smallest numbers how would that be possible if we have four integers in the possible if we have four integers in the input it would only be possible if all input it would only be possible if all four of the integers happen to be the four of the integers happen to be the exact same they could be all fours or it exact same they could be all fours or it could be all like threes for example and could be all like threes for example and that would be fine because that would that would be fine because that would mean two of these threes belong to this mean two of these threes belong to this group and the other two threes belong group and the other two threes belong here they technically are distinct here they technically are distinct numbers the numbers aren't distinct but numbers the numbers aren't distinct but the index of each number is technically the index of each number is technically distinct we're not reusing any of these distinct we're not reusing any of these individuals so that's why this solution individuals so that's why this solution will work now in terms of implementing will work now in terms of implementing it I will mostly save that for the code it I will mostly save that for the code but at a high level I'll quickly go over but at a high level I'll quickly go over it for each number the way I'm going to it for each number the way I'm going to code it I'm going to ask myself is this code it I'm going to ask myself is this number larger than the second smallest number larger than the second smallest number and in this case it is next I'm number and in this case it is next I'm going to ask myself is it larger than going to ask myself is it larger than the largest number yes it's larger than the largest number yes it's larger than the largest so what I would do is put the largest so what I would do is put the five in this spot and I would take the five in this spot and I would take whatever number happened to be here and whatever number happened to be here and then move that to the second smallest then move that to the second smallest and in verely I would kind of do the and in verely I would kind of do the same thing with the minimums as well same thing with the minimums as well like for example with five I'd say is like for example with five I'd say is this smaller than Min 2 yes it is so this smaller than Min 2 yes it is so before we now replace this with five before we now replace this with five we're going to ask ourselves is it also we're going to ask ourselves is it also smaller than the smallest number and if smaller than the smallest number and if it is then we actually put that five it is then we actually put that five over here and we would take whatever we over here and we would take whatever we have here and move it over there that's have here and move it over there that's the idea now I'm going to code it up so the idea now I'm going to code it up so here I have just initialized those two here I have just initialized those two variables as we kind of talked about in variables as we kind of talked about in the drawing explanation I don't think the drawing explanation I don't think you want to see me type all that out now you want to see me type all that out now we're going to implement the algorithm we're going to implement the algorithm go through every number in the input go through every number in the input array like I said we're going to first array like I said we're going to first ask is this number larger than the ask is this number larger than the second largest number that we have okay second largest number that we have okay it is so now the question we need to it is so now the question we need to know is should we put n in this spot or know is should we put n in this spot or should we put it in this spot so let's should we put it in this spot so let's find out now is n also larger than Max find out now is n also larger than Max one if it is then we say Max one is one if it is then we say Max one is going to be equal to n and we would also going to be equal to n and we would also say Max 2 is going to be equal to the say Max 2 is going to be equal to the original value of Max one in Python you original value of Max one in Python you can do this double assignment both of can do this double assignment both of these will pretty much be executed in these will pretty much be executed in parallel at least that's how you can parallel at least that's how you can think about it now if this wasn't the think about it now if this wasn't the case then we can't do that then we can case then we can't do that then we can only replace Max 2 with n so that's how only replace Max 2 with n so that's how we do this part now the next part is we do this part now the next part is with replacing the minimums you might be with replacing the minimums you might be thinking should we put an else if here thinking should we put an else if here should we say n is smaller than min2 and should we say n is smaller than min2 and you'd actually be wrong we don't need an you'd actually be wrong we don't need an else and that will make the solution else and that will make the solution incorrect you don't put the else here incorrect you don't put the else here because as we're going through an input because as we're going through an input array for example it might be 1 2 3 four array for example it might be 1 2 3 four initially when we get to the first one initially when we get to the first one this if statement is going to execute this if statement is going to execute because we initialize these to zeros so because we initialize these to zeros so we would end up setting like Max one we would end up setting like Max one equal to 1 if we had an else if here equal to 1 if we had an else if here then this part would not execute but then this part would not execute but that would lead to the wrong solution that would lead to the wrong solution because we know that one actually is the because we know that one actually is the minimum it's not the maximum it might minimum it's not the maximum it might temporarily be set to Max one but it's temporarily be set to Max one but it's not the largest in this array what we're not the largest in this array what we're saying here by having both of these just saying here by having both of these just be if statements is that sometimes at be if statements is that sometimes at some point they might overlap like Min some point they might overlap like Min one might have the same value as Max one one might have the same value as Max one that's okay because we know for sure by that's okay because we know for sure by the end of this array they will be set the end of this array they will be set to distinct integers at least integers to distinct integers at least integers at distinct indices so that's why we at distinct indices so that's why we don't need the else over here to finish don't need the else over here to finish this up if n is smaller than min2 now we this up if n is smaller than min2 now we need to ask ourselves is it also smaller need to ask ourselves is it also smaller than min1 if it is we do pretty much than min1 if it is we do pretty much what we did up above Min one is going to what we did up above Min one is going to be set to N and min2 is going to be set be set to N and min2 is going to be set to the original value of min1 otherwise to the original value of min1 otherwise we just replace Min 2 and set it equal we just replace Min 2 and set it equal to n so that's pretty much the entire to n so that's pretty much the entire code only thing left for us to do is code only thing left for us to do is return the result which they pretty much return the result which they pretty much gave us the formula to do that Max one gave us the formula to do that Max one multiplied by Max 2 subtracted by min1 * multiplied by Max 2 subtracted by min1 * min2 so now let's run this to make sure min2 so now let's run this to make sure that it works and as you can see on the that it works and as you can see on the left yes it does and it's pretty left yes it does and it's pretty efficient if you found this helpful efficient if you found this helpful please like And subscribe if you're please like And subscribe if you're preparing for coding interviews check preparing for coding interviews check out NE code. thanks for watching and out NE code. thanks for watching and I'll see you soon | 2024-03-25 12:37:20 | 1,913 | Maximum Product Difference Between Two - Leetcode 1913 - Python |
|
CKSdHsQyPYk | and today we will be discussing the question how many numbers are smaller question how many numbers are smaller than the current number in this question than the current number in this question we are given the array norms and for we are given the array norms and for each value we need to find out how many each value we need to find out how many numbers are in the array that are numbers are in the array that are smaller than this particular number at smaller than this particular number at the end we need to return the answer in the end we need to return the answer in an array an array so we are given certain example with the so we are given certain example with the problem we'll first understand how this problem we'll first understand how this particular output was generated so the first input that is given to us is 8 1 2 2 and 3. and when we need to return the answer we'll have an array of same length we see the number 8 at first we see that all the numbers are smaller than this particular number so at this start every four numbers which is 1 2 2 and 3. now we'll take number one we can see that there are no numbers which are less than number ones so it will be 0. now we see number two and there is only one number which is less than 2 which is one so we will put one as the answer same for this 2 as well one for this 3 there are three numbers which are less which is one two and two so the answer will be 3 over here that will become the output we are looking for so let's clear all this let's talk about a very Brute Force so in a Brute Force solution so in a Brute Force solution for every number that we have we can for every number that we have we can check how many numbers exist which are smaller than this particular number so when we check this for 8 we'll get there are four numbers which are less so we'll return 4. now for one when we see that there are no numbers so we see that there are no numbers so we'll return 0 and so on so as we know we'll return 0 and so on so as we know that we are checking for each element that we are checking for each element all the other elements so the complexity all the other elements so the complexity in this case will turn out to be of n in this case will turn out to be of n Square Square which is a very high complexity now what which is a very high complexity now what we can do to optimize this particular we can do to optimize this particular approach approach the easiest way of finding out how many the easiest way of finding out how many numbers are there which is less than any numbers are there which is less than any particular number will be when these particular number will be when these array is given to us in a sorted fashion array is given to us in a sorted fashion so if the array would be like this we can simply know with the index of this particular number or any number that there are four values smaller than this particular number three values smaller than this number now in the case when the values are equal we need to take a special things into consideration so from the example we know that in case of duplicates the index will be the first Index this one which we saw so now we see that if we know the index of the values in the sorted array we can easily return the answer so in order to bring down the time complexity from n Square we need to use certain space to hold these particular values so if we hold the index of these particular values somewhere well suppose we hold them like this the value 1 has an index of 0 the value 2 has the first index is 1. value 3 has index of 3 and value 8 has index of 4. so if we have this mapping with us and now when we reiterate from this array we can just put the index value at the resultant array which would be 8 has a value of 4 so we'll put 4 1 has a value of 0 so we'll put 0 2 has the value of 1 we put 1 again 1 and 3 as a value of 3. so this again gives us the same result and now the time complexity is also lower now it's time to code this particular approach we'll start off with having a result array and we can easily create a clone for the input array once we have this array we will just sort the result array in order to find out the indexes and now we need to store this index somewhere so we'll use a map because it is kind of a key value pair we'll put the value if it is absent so we'll put the value if it is absent so by using a function that is provided by by using a function that is provided by the map the map you can do an if else check as well for you can do an if else check as well for the keys if it is present or not once we have this map ready we can again iterate this time on the names array we can now change the value at this index array directly getting the index from this index hashmap position position once we are done we need to Simply once we are done we need to Simply return the return the result array result array and that completes the coding part and that completes the coding part now let's try to run this code now let's try to run this code so it runs successfully let's submit so it runs successfully let's submit this this so it got submitted successfully the so it got submitted successfully the time complexity in this case is n log n time complexity in this case is n log n down from n Square because we are doing down from n Square because we are doing a sorting well space complexity is O of a sorting well space complexity is O of n as we are using in results array so n as we are using in results array so that's all for today's video that's all for today's video do let us know your thoughts comments do let us know your thoughts comments and query in the comment section below and query in the comment section below thanks for watching see you in the next thanks for watching see you in the next one one foreign | 2024-03-21 00:40:58 | 1,365 | How Many Numbers Are Smaller Than the Current Number | Leetcode - 1365 |
|
SpK9m9NaX2Q | hey YouTube Welcome Back and today we have this problem it's called H index uh have this problem it's called H index uh given that if integers called citations given that if integers called citations where citations of I is the number of where citations of I is the number of citations a researcher received for citations a researcher received for their eyes paper return the research on their eyes paper return the research on each index okay and that there is the each index okay and that there is the each index occurred each index occurred a current humidity then a current humidity then is defined as the maximum value is defined as the maximum value of H that the given researcher has of H that the given researcher has published at least published at least um age people that have each been um age people that have each been seated at least eight times seated at least eight times what that means what that means because yeah I read these times multiple because yeah I read these times multiple times try to understand times try to understand however however if you look at this example I guess we if you look at this example I guess we could understand it quite easily so we could understand it quite easily so we have these papers we have and this the have these papers we have and this the output should be three because why output should be three because why because the researcher has right now because the researcher has right now five papers okay and for each paper we five papers okay and for each paper we have have um three what for the first one we have um three what for the first one we have three citations the second zero six one three citations the second zero six one five five and since we the the researcher has and since we the the researcher has three papers with at least three three papers with at least three citations citations each and the remaining two with uh with each and the remaining two with uh with no more than three station each their uh no more than three station each their uh each index is three each index is three so so for this one for this one the index will be one so let's just the index will be one so let's just I know it's sometimes this problem some I know it's sometimes this problem some a lot of people say ah it's it's not a lot of people say ah it's it's not it's not uh it's not easy or maybe it's it's not uh it's not easy or maybe it's not not um um easy to understand so first of all if we easy to understand so first of all if we don't understand anything let's just don't understand anything let's just take a hint take a hint um um so so we said approach to sort what are the we said approach to sort what are the possible values of each indexed possible values of each indexed um um a faster approach is to use extra space a faster approach is to use extra space okay so the old hint is in the problem okay so the old hint is in the problem and I just look at what and I just look at what um and each index so if you order an um and each index so if you order an interview and right now we are in this interview and right now we are in this problem that we don't understand what is problem that we don't understand what is the each index if let's say that I read the each index if let's say that I read it and I didn't understand it so I will it and I didn't understand it so I will ask my interviewer okay can you just ask my interviewer okay can you just describe more because I didn't describe more because I didn't understand this one understand this one so let's just try to read here and this so let's just try to read here and this uh this article okay the name purpose uh this article okay the name purpose okay the H index is defined as a maximum okay the H index is defined as a maximum value of H such the given author or value of H such the given author or Runner has published Runner has published at least eight people's at each at least eight people's at each um um each peoples that have each been seated each peoples that have each been seated at least eight times at least eight times so if we looked at this one and we say so if we looked at this one and we say that the index is designed to improve that the index is designed to improve upon similar measures such that total upon similar measures such that total number we don't care about that so for number we don't care about that so for this example this example we have this would be the the HP force we have this would be the the HP force and this will be the the the most and this will be the the the most um papers that was uh appeared each time um papers that was uh appeared each time so for this one so for this one we have this and we have this so we just we have this and we have this so we just the more density teaching so this this the more density teaching so this this this is what we talk about this is what we talk about so if you don't understand it I guess I so if you don't understand it I guess I hope you understand it right now but hope you understand it right now but let's just let's just try to to to think about it and I'll try to to to think about it and I'll tell you something when I do the tell you something when I do the solution solution um I guess maybe you could understand it um I guess maybe you could understand it better so let's just start in the code better so let's just start in the code so the problem it will be so the problem it will be first first we want to get the H index what is the we want to get the H index what is the eighth index it's defined the maximum eighth index it's defined the maximum value of H certainly the the given value of H certainly the the given researcher has published at least eight researcher has published at least eight times times so let's just say that we want to get a so let's just say that we want to get a number that the publish has uh uh number that the publish has uh uh published at least each time published at least each time touch that given research that has touch that given research that has published at least each time people that published at least each time people that are okay so are okay so for this one for this one we are saying again we have three zero we are saying again we have three zero six one and five and the researcher has six one and five and the researcher has five Clippers as you as you can see five Clippers as you as you can see right now right now and in in total of each of them will and in in total of each of them will have these quotations like each number have these quotations like each number is is is is representing a specific quotation uh representing a specific quotation uh situation sorry situation sorry and since the researcher has three and since the researcher has three papers with at least three citations we papers with at least three citations we have three and five and six have three and five and six and remaining two with no more than and remaining two with no more than three zero and one okay and so uh their three zero and one okay and so uh their H index is is is three so that's it so H index is is is three so that's it so let's just try to to to to try to how to let's just try to to to to try to how to find this H index because if you find this H index because if you understand it okay we understand how we understand it okay we understand how we can find it so can find it so first a good approach I guess is when we first a good approach I guess is when we talk about the maximum it's a good talk about the maximum it's a good approach is to sort and we want to get a approach is to sort and we want to get a hint and with the the good approach is hint and with the the good approach is to sort the array so we will make sure to sort the array so we will make sure that the the the big the pickets are in that the the the big the pickets are in the end and the small cell in the the end and the small cell in the beginning so let's just make a try to beginning so let's just make a try to make a photography make a photography let's to sort this array the sword a and B it will be the E minus B okay so right now we sold the array so what I'm going to do let oil equals zero and I will say while oil is less than citation and and you will understand why I'll and and you will understand why I'll make the other this one citation make the other this one citation of citation let's see the significant length when this one will be in n equals citation.ly minus oi and I will say while oh yeah less than the length and while oh yeah less than the length and uh and the position of on and this um uh and the position of on and this um position is bigger than or position is bigger than or this index is bigger than all this index is bigger than all we'll increase I plus one I plus plus we'll increase I plus one I plus plus and we return on so uh what's going on so first of all let's just try to walk you through the code so we sort the application because right now we want to get to the maximum um the maximum value of of uh of the H index which was being uh like was a period each amount of times so because of that we will just to get we will sort arrays right now let's just talk this one as an example and just try to walk walk you through the solution so first of all we have this array we have this array let's just and we saw this array so the array will equals like that this zero and one and three and five and six okay and we and three and five and six okay and we have the oil you can call it answer have the oil you can call it answer of result is of result is this this or III like it doesn't matter call it or III like it doesn't matter call it whatever you want whatever you want and we have this I and this I will be and we have this I and this I will be the H index that we are going to return the H index that we are going to return so so what I'm going to say that because the what I'm going to say that because the edge index again is uh which index is is edge index again is uh which index is is uh um is the maximum value of H uh um is the maximum value of H that given a researcher has published at that given a researcher has published at least each paper each at least each least each paper each at least each papers that have been seated at least papers that have been seated at least each time so we have this number three each time so we have this number three and the three would at least it was and the three would at least it was publish at least three times and it was publish at least three times and it was the maximum because someone say okay uh the maximum because someone say okay uh maybe we could use one because one it maybe we could use one because one it was was was uh was four times not not was was was uh was four times not not three times so one is more but one is three times so one is more but one is not the maximum three is the maximum not the maximum three is the maximum okay so we search for the maximum so okay so we search for the maximum so right now right now we have in the this maximum The Edge we have in the this maximum The Edge index for this one is three because index for this one is three because three was appeared three times and it's three was appeared three times and it's the biggest one you we can say one the biggest one you we can say one because one was appeared four times but because one was appeared four times but three is bigger than than one so we three is bigger than than one so we would take three so would take three so I will use I will after sorting the I will use I will after sorting the array array I would say that okay I would say that okay um let's just make sure that we are um let's just make sure that we are getting this index let's see that how getting this index let's see that how this works so I will walk you through this works so I will walk you through the code so I first will be zero the code so I first will be zero so so um um let's call the citation of oil for this let's call the citation of oil for this one so if I less than length this I one so if I less than length this I guess this is quite understandable guess this is quite understandable but this one this one we talk about but this one this one we talk about because we want the biggest because we want the biggest again let's just look at where you want again let's just look at where you want the maximum value of H the maximum value of H so I want three I don't want one so I so I want three I don't want one so I want the maximum one so I'll start from want the maximum one so I'll start from the end the end and I'll say Okay and I'll say Okay um um um if citation um if citation of n minus 1 minus i n minus 1 of n minus 1 minus i n minus 1 is um let us make n n minus one is four is um let us make n n minus one is four okay minus I okay minus I will be minus zero so it will be equals will be minus zero so it will be equals um um four four n minus 1 minus i n minus 1 is 4 and n minus 1 minus i n minus 1 is 4 and minus I I zero so equal four so we are minus I I zero so equal four so we are here here so it will be six is six bigger than I so it will be six is six bigger than I or is zero yes okay so increase I plus or is zero yes okay so increase I plus one so right now I will equals one one so right now I will equals one okay so let's make another loop okay so let's make another loop if I less than n yeah I is less than n if I less than n yeah I is less than n okay so if citation of n minus 1 minus I okay so if citation of n minus 1 minus I is bigger than I so is bigger than I so um situation the N minus one in response um situation the N minus one in response four minus I it will be one the value of four minus I it will be one the value of this one is five this one is five it's is it minus bigger than I yep so it's is it minus bigger than I yep so okay add one so it will be two so let's okay add one so it will be two so let's just make a loop again so I'll say okay just make a loop again so I'll say okay uh I is less than in yes oh it's uh I is less than in yes oh it's listening if citation dot uh citation of listening if citation dot uh citation of uh of the index n minus one minus I uh of the index n minus one minus I greater than I so let's see greater than I so let's see um um um um n minus 1 is 4 and the I2 so it will be n minus 1 is 4 and the I2 so it will be two two so it will be three so three yeah three so it will be three so three yeah three is bigger so plus plus so it could be is bigger so plus plus so it could be three when we do this one the last one three when we do this one the last one it will be okay I it's more than in yup it will be okay I it's more than in yup I3 and N is uh in is five I3 and N is uh in is five if citation n minus one minus I bigger if citation n minus one minus I bigger than I let's just see than I let's just see um situation four and three um situation four and three will be one and the index of one is also will be one and the index of one is also one so it will be one no this is not one so it will be one no this is not true so this while loop is in and we true so this while loop is in and we turn I so i3 turn I so i3 and that's it so um are you my search is and that's it so um are you my search is quite good I hope my solution was quite quite good I hope my solution was quite understandable uh if you like my understandable uh if you like my description make sure to subscribe and description make sure to subscribe and hit the notification Bell so you will hit the notification Bell so you will never miss a video and see you in future never miss a video and see you in future problems | 2024-03-22 12:33:02 | 274 | Leetcode | Top Interview 150 | Medium | 274. H-Index | Time: O(N) | Javascript |
|
3e2Ul8KRbsw | hello everyone i hope all of you are having a great time and welcome to day having a great time and welcome to day 20th of february record challenge the 20th of february record challenge the question that we have in today is question that we have in today is removed covered intervals here in this removed covered intervals here in this question we are given an array of question we are given an array of intervals wherein each interval has two intervals wherein each interval has two endpoints the starting index and the endpoints the starting index and the ending index what we call as l i and r i ending index what we call as l i and r i what we need to do we need to remove all what we need to do we need to remove all the intervals that are covered by other the intervals that are covered by other intervals in this interval set intervals in this interval set also we need to return the number of also we need to return the number of remaining intervals that are left after remaining intervals that are left after you have removed all the covered you have removed all the covered intervals up intervals up here in this example they have provided here in this example they have provided us with an interval set as 1 4 2 3 6 and us with an interval set as 1 4 2 3 6 and 2 8 as you can see 2 8 as you can see that that 3 6 is already covered by the virtue of 3 6 is already covered by the virtue of 2 weight as a result we can simply 2 weight as a result we can simply remove 3 6 the number of remaining remove 3 6 the number of remaining intervals tend to be 1 4 and 2 8 intervals tend to be 1 4 and 2 8 and the count happens to be 2. and the count happens to be 2. this is what we need to return without this is what we need to return without further ado let's quickly walk through further ado let's quickly walk through the presentation that i have created for the presentation that i have created for this and i will be walking through the this and i will be walking through the i'll go as well as these examples by the i'll go as well as these examples by the ppt so let's get started ppt so let's get started remove covered intervals lead code one remove covered intervals lead code one two double it it's a medium level two double it it's a medium level question on lead good and i totally feel question on lead good and i totally feel the same the approach that we are gonna the same the approach that we are gonna use to solve this question would be a use to solve this question would be a greedy approach and we have already greedy approach and we have already solved couple of questions in the past solved couple of questions in the past with respect to the same approach to with respect to the same approach to name few i can tell merge intervals was name few i can tell merge intervals was the one minimum arrows to burst balloon the one minimum arrows to burst balloon was another and there are few more which was another and there are few more which i'm attaching in the description below i'm attaching in the description below if you want to try out similar questions if you want to try out similar questions on the same approach do have a look at on the same approach do have a look at them as well now let's get to the point them as well now let's get to the point let's consider a slightly different let's consider a slightly different example to what was specified in the example to what was specified in the question i have added a new entry 1 question i have added a new entry 1 comma 2 to the example that was comma 2 to the example that was specified in the question the total specified in the question the total number of elements that we have is 1 4 3 number of elements that we have is 1 4 3 6 2 8 and 1 2. 6 2 8 and 1 2. what i'm going to do what i'm going to do i'll again follow the greedy approach i'll again follow the greedy approach i'll sort i'll sort these intervals first on the basis of x these intervals first on the basis of x coordinate in the increasing order and coordinate in the increasing order and then decreasingly on the basis of y then decreasingly on the basis of y coordinate whenever there is a clash coordinate whenever there is a clash between x coordinates between x coordinates so one assuming that i have done it so one assuming that i have done it let's see the updated intervals array let's see the updated intervals array you can see that the x coordinate you can see that the x coordinate matches over here so in such case we matches over here so in such case we will give precedence to a higher will give precedence to a higher y-coordinate as a result of it one comma y-coordinate as a result of it one comma four comes four comes at first then one comma two at first then one comma two let's proceed ahead the next would be let's proceed ahead the next would be sorting on the basis of x coordinate so sorting on the basis of x coordinate so we will get two comma eight followed by we will get two comma eight followed by three comma six three comma six now if you carefully observe this now if you carefully observe this updated array you can simply assume that updated array you can simply assume that all the elements in this array would be all the elements in this array would be in the increasing order of x coordinate in the increasing order of x coordinate so we have increasing x here one in or so we have increasing x here one in or increasing or similar it can't be increasing or similar it can't be decreasing so 1 1 then we have 2 then we decreasing so 1 1 then we have 2 then we have 3 so we can simply eliminate have 3 so we can simply eliminate x coordinate here and we don't need to x coordinate here and we don't need to do any manipulation over it the area of do any manipulation over it the area of interest would remain in the y interest would remain in the y coordinate how let's walk through an coordinate how let's walk through an example so what i'm going to do i'll example so what i'm going to do i'll create a variable and let me just change create a variable and let me just change the color of pen for better the color of pen for better understanding i'll create a variable understanding i'll create a variable range of y-coordinate and by default it range of y-coordinate and by default it will be mean slice to minus 1. will be mean slice to minus 1. what do we see we see the first element what do we see we see the first element now which happens to be 1 comma 4 now which happens to be 1 comma 4 now is this range overpowering this 4 now is this range overpowering this 4 value no it's not that means this value no it's not that means this element will be part of your answer element will be part of your answer since we have included this range that since we have included this range that is 4 to be part of our answer set we is 4 to be part of our answer set we will increment this variable to the will increment this variable to the maximum of value that is set here versus maximum of value that is set here versus this so what is that minus 1 and 4 you this so what is that minus 1 and 4 you get 4 so the range gets updated to 4. get 4 so the range gets updated to 4. now let's look at the next entry the now let's look at the next entry the next entry happens to be 1 comma 2 and next entry happens to be 1 comma 2 and we will not look out for the x we will not look out for the x coordinate because we know it's already coordinate because we know it's already increasing in nature we are only increasing in nature we are only interested in looking out for the y interested in looking out for the y coordinate range so what is the value coordinate range so what is the value here the value is 2 and the current max here the value is 2 and the current max range that we have reached happens to be range that we have reached happens to be 4 that means we can simply eliminate 4 that means we can simply eliminate this variable this is not needed it is this variable this is not needed it is already covered by some other entry in already covered by some other entry in the past the past and we can get this information from the and we can get this information from the range variable that we have created and range variable that we have created and the value that is here is 4 here it is 2 the value that is here is 4 here it is 2 we can simply delete this element since we can simply delete this element since we are deleting this element we will we are deleting this element we will increment the counter variable to 1 increment the counter variable to 1 which is because we are also also which is because we are also also counting how many intervals have we counting how many intervals have we removed removed let's proceed ahead next what do we see let's proceed ahead next what do we see we see that the next entry is 2 comma 8 we see that the next entry is 2 comma 8 we are not interested about x coordinate we are not interested about x coordinate we only look out for the y coordinate we only look out for the y coordinate the y coordinate happens to be 8 is is the y coordinate happens to be 8 is is the range overpowering 8 no it's not as the range overpowering 8 no it's not as a result of which we have to include a result of which we have to include this as part of our answer this as part of our answer along with this we will update the range along with this we will update the range since we have included this as part of since we have included this as part of the answer to eight so the range gets the answer to eight so the range gets updated to eight updated to eight let's proceed ahead next we see is three let's proceed ahead next we see is three comma six comma six again we will not look out for the x again we will not look out for the x coordinate we are only interested in the coordinate we are only interested in the y coordinate what is the value at the y coordinate what is the value at the y-coordinate it is 6 y-coordinate it is 6 is is 8 over powering 6 yes this range that we 8 over powering 6 yes this range that we have already reached is overpowering 6 have already reached is overpowering 6 because it's a lower value as a result because it's a lower value as a result of which we can simply eliminate this of which we can simply eliminate this and delete this element because this and delete this element because this rain has already been covered in the rain has already been covered in the past as a result of it the count past as a result of it the count variable gets updated to 2. variable gets updated to 2. that simply signifies in totality we that simply signifies in totality we have removed two intervals so what is have removed two intervals so what is the length of the initial input data set the length of the initial input data set that was given to us how many intervals that was given to us how many intervals were there they were in totality four were there they were in totality four intervals how many have been removed we intervals how many have been removed we have removed two intervals what is the have removed two intervals what is the remaining count the remaining amount remaining count the remaining amount happens to be two happens to be two and this is what we need to write on and this is what we need to write on pretty simple and straightforward no pretty simple and straightforward no rocket science involved in it the crux rocket science involved in it the crux of the problem lies in this sorting of the problem lies in this sorting approach that we have followed because approach that we have followed because we are eliminating one coordinate and we are eliminating one coordinate and then operating on the other coordinate then operating on the other coordinate along the y axis in this case along the y axis in this case without further ado let's quickly walk without further ado let's quickly walk through the through the coding section where i'll conclude the coding section where i'll conclude the approach so as talked in the ppt first thing that i'm going to do is to sort the intervals first on the basis of x coordinate if it happens to be equal then i'll sort them in decreasing contour on the basis of y coordinate otherwise we'll go for the increasing x coordinate i have created an answer variable for storing the answer and i have created a previous range variable for the y-coordinate so this only signifies for the y coordinate then i start the operation over the then i start the operation over the intervals uh using a for loop if my intervals uh using a for loop if my previous range happens to be greater previous range happens to be greater than equal to the current element of the than equal to the current element of the at the at the index index that means the previous range is already that means the previous range is already cover covering this interval as a result cover covering this interval as a result of which i increment my answer variables of which i increment my answer variables so this answer variable is not actually so this answer variable is not actually storing the answer rather it's storing storing the answer rather it's storing how many removal count let's rename it how many removal count let's rename it to removable count to removable count how many intervals have we removed how many intervals have we removed moving ahead i update my previous range moving ahead i update my previous range to mat dot max the current y coordinate to mat dot max the current y coordinate and the previous one we always look out and the previous one we always look out for the maximum out of these two in the for the maximum out of these two in the end i simply return intervals.length end i simply return intervals.length minus removable count so let's summit minus removable count so let's summit this up accepted it returns faster which is pretty good and fine in terms of time complexity here it would be equal to order of n log n when n signifies the number of elements that are part of the intervals data set with respect to the phase complexity i think it would be constant space because we are not using anything extra here this brings me to the end of today's session i hope you enjoyed it if you did please don't forget to like share and subscribe to the channel thanks for being here have a great day ahead and stay tuned for more updates from coding decoded i'll see you tomorrow with another fresh question but | 2024-03-20 10:37:36 | 1,288 | Remove Covered Intervals | Leetcode 1288 | Live coding session 🔥🔥🔥| Greedy | Sorting TC O(nlogn) |
|
URoy1fFmGIw | hello guys welcome to deep codes and in today's video we will discuss liquid today's video we will discuss liquid question 956 that says tallest billboard question 956 that says tallest billboard so guys although this question is easy so guys although this question is easy to understand as well as code but the to understand as well as code but the complexity arises when you have to solve complexity arises when you have to solve this question in a memory bound this question in a memory bound so yeah guys uh in today's video we will so yeah guys uh in today's video we will learn how we can solve this question uh learn how we can solve this question uh by using some smart moves right so yeah by using some smart moves right so yeah guys stick to the end and watch the guys stick to the end and watch the complete video complete video now here what you have to do is you have now here what you have to do is you have to to um you know make two support of equal um you know make two support of equal height and on which on the support you height and on which on the support you have to place the billboard so you need have to place the billboard so you need to find what is the maximum height of to find what is the maximum height of support you can achieve and yeah both support you can achieve and yeah both the support one that is the left support the support one that is the left support as well as the right support must be of as well as the right support must be of equal length equal length ok so here ok so here to still supports that you need and they to still supports that you need and they must they must be of equal height and must they must be of equal height and they are a build of rods so there are they are a build of rods so there are lots of different lengths like length lots of different lengths like length one length two length three and length one length two length three and length six and so on so you need to use these six and so on so you need to use these rods in order to make left support as rods in order to make left support as well as right support well as right support okay and yeah this uh you we need to try okay and yeah this uh you we need to try to achieve the largest or the maximum to achieve the largest or the maximum height possible to install the billboard height possible to install the billboard so as the question says tallest so as the question says tallest billboard so we need to achieve the billboard so we need to achieve the maximum height maximum height and yeah if you cannot support the and yeah if you cannot support the billboard that means it is not possible billboard that means it is not possible to make a lab support and write support to make a lab support and write support equal then in that case return 0. equal then in that case return 0. so let's try to go through a few so let's try to go through a few examples here examples here now here in the first example you are now here in the first example you are given this uh four rods first Rod is of given this uh four rods first Rod is of a length one second of length two third a length one second of length two third of length 3 and 4th of length 6. so guys of length 3 and 4th of length 6. so guys if you want to achieve tallest billboard if you want to achieve tallest billboard with this road then what you can do is with this road then what you can do is you can create the left support you can create the left support combining Rod uh of a length one two and combining Rod uh of a length one two and three so this would be of a total length three so this would be of a total length six and the right support would be of six and the right support would be of Line 6 by taking this road so now both Line 6 by taking this road so now both the left support as well as right the left support as well as right support out of equal length as well as support out of equal length as well as they are the maximum possible height they are the maximum possible height that can you can achieve using these that can you can achieve using these rods so yeah the maximum height you can rods so yeah the maximum height you can achieve is six and that is the height achieve is six and that is the height that or the answer that we need to that or the answer that we need to return now if you take a look at the return now if you take a look at the second example second example so here we have used three rods to make so here we have used three rods to make the left support and one and two rods to the left support and one and two rods to make the right support and here we make the right support and here we haven't used the rod with the length one haven't used the rod with the length one in any of them so yeah guys you can see in any of them so yeah guys you can see here that a rod can be either a part of here that a rod can be either a part of a left support or a particular Rod can a left support or a particular Rod can either be a part of right support and it either be a part of right support and it can be possible the dot is not a part of can be possible the dot is not a part of any of them right so yeah by do uh by any of them right so yeah by do uh by solving this equation this way this is solving this equation this way this is the left support this is the right the left support this is the right support you can get a maximum height of support you can get a maximum height of 10 okay correct 10 okay correct so yeah guys as I told you the rod can so yeah guys as I told you the rod can be a part of left support or can be a be a part of left support or can be a part of right support or none none of part of right support or none none of them and the question asks us to find them and the question asks us to find the maximum height or most for optimal the maximum height or most for optimal answer so guys whenever you have answer so guys whenever you have something like this that there are some something like this that there are some choices for each given index so here A choices for each given index so here A Rod of index for each Rod of index there Rod of index for each Rod of index there are some choices these are nothing but are some choices these are nothing but your choices So based on these choices your choices So based on these choices you can easily write the recursive you can easily write the recursive solution okay and yeah you need to get solution okay and yeah you need to get the most optimal optimal answer that is the most optimal optimal answer that is you need to return the maximum height so you need to return the maximum height so yeah you will take uh the maximum of all yeah you will take uh the maximum of all the choices correct simple it is so yeah the choices correct simple it is so yeah it is easy to write the recursive it is easy to write the recursive solution and if you want to uh see how solution and if you want to uh see how the recursion tree can be built for this the recursion tree can be built for this question then we can do it in this way question then we can do it in this way so here you are given in this example of so here you are given in this example of six Rod indexing from 0 to 5. so for the six Rod indexing from 0 to 5. so for the first index you have three choices that first index you have three choices that it would be a part of support one it it would be a part of support one it would be a part of support two or none would be a part of support two or none so if this would be a part let's say so if this would be a part let's say index 0 that is Rod of length 1 is a index 0 that is Rod of length 1 is a part of support one then you have a part of support one then you have a height one on the this is the left a height one on the this is the left a support type and 0 that is the right support type and 0 that is the right support height So currently this is your support height So currently this is your situation if it would be a part of situation if it would be a part of support then this would be a situation support then this would be a situation where the left support is of height zero where the left support is of height zero and the right support is of height one and the right support is of height one okay so you have three you have you okay so you have three you have you created three states now then uh take created three states now then uh take for index one so for index one for index one so for index one either you can take it in the lab either you can take it in the lab support so then the height of the left support so then the height of the left support would be 1 plus current that is support would be 1 plus current that is 2 so overall it would be three 2 so overall it would be three as you can take this index one as a as you can take this index one as a right support then our the height of the right support then our the height of the support would be one comma two that is support would be one comma two that is uh on the left and on right uh on the left and on right and it would be a part of none then the and it would be a part of none then the height would be one comma zero so height would be one comma zero so similarly you can take uh similarly you can take uh I equal to 3 4 5 from each Stitch so I equal to 3 4 5 from each Stitch so yeah now you can try to build up this yeah now you can try to build up this recursion Tree on yourself and yeah you recursion Tree on yourself and yeah you can get more idea of how this recursion can get more idea of how this recursion works now moving on to the coding part works now moving on to the coding part for this recursion so here we have build for this recursion so here we have build one solve function and call this all one solve function and call this all function from here this all function function from here this all function takes parameter of rods index sum 1 and takes parameter of rods index sum 1 and sum two so someone is nothing but height sum two so someone is nothing but height of a support one and this is I have of a support one and this is I have taken as a height of the support too taken as a height of the support too now our base condition is when there are now our base condition is when there are no rods remaining in that case we no rods remaining in that case we checked if someone equals to sum 2 that checked if someone equals to sum 2 that means height of raw uh support to an means height of raw uh support to an equals to height of support two then equals to height of support two then simply return the height height of any simply return the height height of any one of the support and indirect one of the support and indirect condition returns zero because yeah it condition returns zero because yeah it is it was not possible to make both the is it was not possible to make both the height equal then in that case we simply height equal then in that case we simply return 0. and these are the three return 0. and these are the three options that we discuss that either a options that we discuss that either a rod can be a part of support one or it rod can be a part of support one or it can be a part of support or it won't be can be a part of support or it won't be a part of any then in that case we a part of any then in that case we haven't added in any simply we take the haven't added in any simply we take the max max okay now as you all know that this is okay now as you all know that this is the recursive solution and it is not the recursive solution and it is not optimal solution uh and yeah if you see optimal solution uh and yeah if you see here that there are three changing here that there are three changing variables some uh index number and some variables some uh index number and some two so total States would be 3 to the two so total States would be 3 to the power and yeah and this will result in power and yeah and this will result in time limit accelerated as well as memory time limit accelerated as well as memory limit accident limit accident so yeah we have to think of some better so yeah we have to think of some better solution in order to optimize our solution in order to optimize our approach and it there is no doubt that approach and it there is no doubt that we can memorize it so whenever we have we can memorize it so whenever we have recursive solution we can easily recursive solution we can easily memorize the recursive solution memorize the recursive solution so our memorization does what it simply so our memorization does what it simply stores the changing variables or the stores the changing variables or the answer at different states so this answer at different states so this States so this is a state so States so this is a state so this is one state this is one state and this is one state this is one state and answer of this state is determined by answer of this state is determined by the index as well as sum 1 and sum two the index as well as sum 1 and sum two right this this will create someone and right this this will create someone and this will create some too so each state this will create some too so each state is determined by the changing variables is determined by the changing variables that is index someone and something now that is index someone and something now if you take a look that there can be 20 if you take a look that there can be 20 different possible possible value of different possible possible value of index 5000 different possible value of index 5000 different possible value of somewhere and five thousand different somewhere and five thousand different possible valuesome two this is already possible valuesome two this is already mentioned in the constraint so if you mentioned in the constraint so if you look at the constraint the index maximum look at the constraint the index maximum limit is up to 20 and some of all the limit is up to 20 and some of all the rod length would be up to five thousand rod length would be up to five thousand so this is the maximum limit uh for our so this is the maximum limit uh for our three changing variables so total States three changing variables so total States would be 20 multiplied by 5000 multiply would be 20 multiplied by 5000 multiply by five thousand so that is five five by five thousand so that is five five multiple ten to The Power 8 and this is multiple ten to The Power 8 and this is very large number so this will surely very large number so this will surely give you memory limit exceeded right if give you memory limit exceeded right if you have to store this many different of you have to store this many different of states states then it will give Emily then it will give Emily so now but if you take a step back and so now but if you take a step back and think what was about gold or what was think what was about gold or what was our base condition instead of a base our base condition instead of a base condition we were simply checking what condition we were simply checking what is the height of left sub left support is the height of left sub left support and what is the height of right support and what is the height of right support that means uh if you look at the that means uh if you look at the recursion code that we already discussed recursion code that we already discussed that we were checking somewhere equals that we were checking somewhere equals to sum to or not right so this is to sum to or not right so this is nothing but if someone minus sum 2 nothing but if someone minus sum 2 equals to zero that is the difference is equals to zero that is the difference is zero then we can say their height is zero then we can say their height is same okay got it this is the theme right same okay got it this is the theme right if the difference is zero then the if the difference is zero then the height is same height is same right so yeah instead of using three right so yeah instead of using three changing variables we will reduce to two changing variables we will reduce to two changing variables there is no way changing variables there is no way possible to not to take index as a possible to not to take index as a changing variables but we can reduce changing variables but we can reduce from this two to any one and that one from this two to any one and that one would be nothing but the difference of would be nothing but the difference of these two and whenever the difference is these two and whenever the difference is zero that means that height is same zero that means that height is same so we will take the difference now if so we will take the difference now if you look that what will be the range of you look that what will be the range of your difference see the sum 1 ranges your difference see the sum 1 ranges from zero to five thousand some two from zero to five thousand some two ranges from zero to five thousand so the ranges from zero to five thousand so the difference would range from minus five difference would range from minus five thousand to plus five thousand right if thousand to plus five thousand right if let's say someone is zero and sum two is let's say someone is zero and sum two is five thousand so it lower limit would be five thousand so it lower limit would be minus five thousand this and it makes it minus five thousand this and it makes it would be five thousand right five would be five thousand right five thousand when one of his uh let's say thousand when one of his uh let's say some two is zero and someone is five some two is zero and someone is five thousand then in that case maximum limit thousand then in that case maximum limit would be five thousand so if you uh see would be five thousand so if you uh see that there are total of two times five that there are total of two times five thousand that means uh ten thousand thousand that means uh ten thousand different values possible for this div different values possible for this div this is the count of values for this this is the count of values for this diff uh total ten thousand values are diff uh total ten thousand values are possible here now if you try to find out possible here now if you try to find out that how many different states are that how many different states are possible then you can see that here possible then you can see that here there are two changing variables that is there are two changing variables that is index and the diff this index can have index and the diff this index can have 20 different values and this div can 20 different values and this div can have two multiplier five thousand have two multiplier five thousand different values so total two into ten different values so total two into ten to the power 5 would be the number of to the power 5 would be the number of states and this is the accepted solution states and this is the accepted solution here okay here okay now if you take a look at the coding now if you take a look at the coding part it is very much simple here we part it is very much simple here we initialize this DP 21 uh of size for initialize this DP 21 uh of size for this index and this is the size of this this index and this is the size of this right ah diff and we initialize the DP right ah diff and we initialize the DP with minus one and call this all with minus one and call this all function inside the solve function we function inside the solve function we have index and div as a input parameters have index and div as a input parameters we would check uh okay this is the base we would check uh okay this is the base condition where no rows are remaining in condition where no rows are remaining in that case we would check that if that case we would check that if difference is zero then return 0 else 10 difference is zero then return 0 else 10 as a minimum value as a minimum value now guys you might be thinking here that now guys you might be thinking here that y inside of a DP array we are adding y inside of a DP array we are adding difference plus five thousand one this difference plus five thousand one this is because difference can have value up is because difference can have value up till minus 5000. so uh but we cannot till minus 5000. so uh but we cannot have negative indexes so in the inside have negative indexes so in the inside this DP address we cannot have negative this DP address we cannot have negative index in order to convert the negative index in order to convert the negative index to positive we are simply adding index to positive we are simply adding five thousand one here okay five thousand one here okay this is the base condition that if this is the base condition that if already the value is calculated that already the value is calculated that means this value is not minus 1 then you means this value is not minus 1 then you simply written the answer as there are simply written the answer as there are three choices so now if we are taking three choices so now if we are taking that rod in the left support then what that rod in the left support then what we would do is we would simply add we would do is we would simply add difference plus a rod length if we are difference plus a rod length if we are taking in the right support we will add taking in the right support we will add difference minus Rod length right and difference minus Rod length right and and then here what we are checking if we and then here what we are checking if we are checking the only the difference are checking the only the difference okay now guys you might be thinking that okay now guys you might be thinking that why we are adding here Rod of index that why we are adding here Rod of index that is the length of this road here inside is the length of this road here inside the option one or the first choice this the option one or the first choice this is because we need to return what is the is because we need to return what is the length of the support So at the end length of the support So at the end whatever may be the difference if the whatever may be the difference if the difference is zero or not if the difference is zero or not if the difference is zero that means both the difference is zero that means both the rod are of same length then in that case rod are of same length then in that case we need to written what is the length of we need to written what is the length of the support right when both the supports the support right when both the supports are of same length then the difference are of same length then the difference is zero but in the answer we don't want is zero but in the answer we don't want that we want what is the length so in that we want what is the length so in order to keep track what is the length order to keep track what is the length of the support we would keep track of of the support we would keep track of length of one of the support only and we length of one of the support only and we would keep track of the difference so would keep track of the difference so this difference will tell whether both this difference will tell whether both the support are of same layer and if it the support are of same layer and if it is same less then what is the length so is same less then what is the length so yeah we only keep track of one of the yeah we only keep track of one of the length of one length of one of the length of one length of one of the support and simply add the rod that we support and simply add the rod that we included in the left support each time included in the left support each time inside our choice right and in the uh inside our choice right and in the uh and yeah when the difference is zero and yeah when the difference is zero nothing would be adding but if the nothing would be adding but if the difference is not zero we are adding difference is not zero we are adding some weak negative number same at some weak negative number same at maximum the height of the support can be maximum the height of the support can be 5000 so we can take any larger value 5000 so we can take any larger value than this 5000 and return it so yeah if than this 5000 and return it so yeah if the difference is not zero then we are the difference is not zero then we are returning some negative large negative returning some negative large negative value but if difference is zero we would value but if difference is zero we would have some positive value and that have some positive value and that positive value would be nothing but a positive value would be nothing but a height of both the support right so yeah height of both the support right so yeah this is how we uh are getting the answer this is how we uh are getting the answer by returning this see we are only by returning this see we are only returning this when we are uh taking the returning this when we are uh taking the rod in the lab support in the other case rod in the lab support in the other case that when we are taking the rod for the that when we are taking the rod for the right support we only subtract that that right support we only subtract that that length from the difference and we do not length from the difference and we do not do we do not return here right we don't do we do not return here right we don't add in the retail statement because we add in the retail statement because we simply need a high okay simply need a high okay and yeah the third option is pretty much and yeah the third option is pretty much the same that is not to take the drawer the same that is not to take the drawer in any one of the support so yeah guys in any one of the support so yeah guys that's how we solve this question that's how we solve this question um so I hope you guys have understood um so I hope you guys have understood that what we are trying to do here not that what we are trying to do here not talking about the time and space talking about the time and space complexity the time complexity here is complexity the time complexity here is very much obvious that it would be very much obvious that it would be nothing but 21 multiplied by two nothing but 21 multiplied by two multiple to 5001 uh because these are multiple to 5001 uh because these are the different possible states that we the different possible states that we are calculating okay and the calculation are calculating okay and the calculation of one state will take bigger of 1 only of one state will take bigger of 1 only because here here there is uh there is because here here there is uh there is no for Loop or nothing else so these all no for Loop or nothing else so these all statements we run we go one time so yeah statements we run we go one time so yeah overall this is the time complexity and overall this is the time complexity and space complexity is also the same but space complexity is also the same but there would be some recursive check he there would be some recursive check he would be used because this is a would be used because this is a recursive function called uh so yeah recursive function called uh so yeah guys that's all for this video if you guys that's all for this video if you guys have still any doubts then do let guys have still any doubts then do let me know in the comment section make sure me know in the comment section make sure to like this video And subscribe to our to like this video And subscribe to our Channel thank you | 2024-03-25 12:16:15 | 956 | 956. Tallest Billboard | LeetCode Daily Challenge |
|
qaOtdWO47b4 | hey everyone welcome to Tech wired in this video we are going to solve problem this video we are going to solve problem number 72 edit distance first we will number 72 edit distance first we will see the explanation of the problem see the explanation of the problem statement then the logic on the code now statement then the logic on the code now let's dive into the solution so here we are given word one and word two we need to convert word one to word two by using these three operations so I can delete 10 character I can insert a character or replace a character and by doing these operations I need to find the minimum required operations to convert word one to word two right which means there are many ways to remove insert or replace characters and I can convert this word horse to Ros but we need to find the minimum number of operations required for this conversion right so for example if I replace H with r and if I remove the center or and if I remove the end e so here I performed three operations right I performed three operations and there are other ways to to convert this particular word one to word two there are many other possible ways but that requires more operations for the conversion so we need to minimize those operations so that is what required here right now we will see how we are going to do this so here I'm going to solve this problem using dynamic programming approach so initially I will create a matrix of 0 and the rows will be the length of my word one plus one and the column will be the length of my word two plus one right so I'm going to have two Loops where I will be used to keep track of the rows and J will be the column Index right so first we will start and then we will see what we are going to do at each and every step right so initially my zeroth index the 0th row will be having the column index right so I'm going to be having 0 1 2 and 3. then the zeroth column so we saw Zero throw had the values of columns right so and this zeroth column will have the values of rows so we are going to just replace the row values corresponding row values right so this will be the starting Matrix for us so we will start from iterating from first row and First Column right so we will first update this particular value so when we are updating I will show you guys what we are doing here right now let's start so initially I'm going to check and J minus 1 index in my word 2 and I and J minus 1 index in my word 2 and I will check whether they are equal right so word I minus 1 is nothing but the H character and word two J minus 1 is nothing buddy our character and they are not equal then I will move to the next condition now I will take the I minus 1 and J minus 1 column value which is from I minus 1 rho and J minus 1 call I need to pick that value so here I am going to get 0 I minus 1 and 0 through and J minus 1 is the 0 and 0th column and I need to pick that value which is nothing but 0 then I will pick I throw and J minus 1 column so here I row is First Column here here I is 1. and the J minus 1 is nothing but the zeroth column that is one here so I will pick one here then I need to pick I minus 1 rho and jth column I need to pick three values so I minus 1 row is 0 0 and J is First Column J is equal to 1 so which is nothing but 1 here then I will take a minimum of these three values so in this case it's going to be 0 and I will add 1. so I'm going to get 1 year then I'm going to take this value and replace and I'm going to update that value in my Matrix in the corresponding I throw jth column that is 1 comma 1 here I will update in 1 comma 1 as 1. right I will show you guys in the next iteration what we are updating right next my J will be 2. so I need to check I minus 1 character and the J minus 1 character so here I minus 1 characters h j minus 1 characters o right now I need to check whether H and O character is equal no they are not equal since they are not equal I will pick the three values and I will take minimum of those three values so those three values nothing but I minus 1 and J minus 1 and I throw and J minus 1 column and I minus one column and J through I need to pick these three values from a DP Matrix then I will take minimum of that and I will add one to it and I will update that in my DP Matrix so here I've updated few values and I will show you guys when the characters are equal right when the characters are equal So currently I am in second row and second column here right now I need to check my I minus 1 character which is nothing but o and J minus 1 character that is nothing but o itself when both characters are equal I will update with I minus 1 rho and J minus 1 column from my DP Matrix so here I need to go to my first I minus 1 is 1 first row and J minus 1 is First Column so I will go to this value and I will update 2 comma 2 with this value one right so what we are trying to do here so we know our row represents the word one and the column represents verb right so we know we are at the I throw on jth column this is nothing but 2 comma 2 I is nothing but the second index in my first word and so if I try to slice word one from 0 to I what I will get I will not include ith index so we will be getting H and over here right then if I try to slice from 0 to jth index from 0 to jth index we know our column is represented by J we know our column is represented by J and the rho is represented by I so here and the rho is represented by I so here J is nothing but 2 if I try to slice J is nothing but 2 if I try to slice over to over to from 0 to 2 I will get from 0 to 2 I will get R and O so here we have one right R and O so here we have one right this one represents minimum operation I this one represents minimum operation I need to perform need to perform within this substring of characters within this substring of characters so if I try to convert word one two word so if I try to convert word one two word two what I need to do here within this two what I need to do here within this substring what I need to do I need to substring what I need to do I need to remove remove I need to perform a remove operation I need to perform a remove operation that's it I don't have to do anything that's it I don't have to do anything in this particular substring I don't in this particular substring I don't have to do anything I need to perform have to do anything I need to perform only one that one is nothing but only one that one is nothing but this value this value one operation I need to perform one operation I need to perform if I try to convert if I try to convert we are not converting perfectly because we are not converting perfectly because we are only checking its substring here we are only checking its substring here if at least I need to perform within if at least I need to perform within this substring this substring if I try to convert I need to remove H if I try to convert I need to remove H right then I will add R in front of v in right then I will add R in front of v in the upcoming stages the upcoming stages but within this substring I need to but within this substring I need to remove R that's all we need to do here remove R that's all we need to do here in this particular stage so as we in this particular stage so as we increase our characters we will be increase our characters we will be performing the minimum number of performing the minimum number of operations at that stage right so at the operations at that stage right so at the end so after performing all of the end so after performing all of the operations after checking all of my operations after checking all of my characters characters I will get 3 at the end of my Matrix I will get 3 at the end of my Matrix that's all we are doing here now let's that's all we are doing here now let's see the code see the code so before we call if you guys haven't so before we call if you guys haven't subscribed to my Channel please like And subscribed to my Channel please like And subscribe this will motivate me to subscribe this will motivate me to upload more videos in future and also upload more videos in future and also check out my previous videos and keep check out my previous videos and keep supporting guys supporting guys so initially I'm going to have M and N so initially I'm going to have M and N which is nothing but the length of my which is nothing but the length of my word one word one and the length of my word then I'm going to create my DP Matrix right which is nothing but n columns and M plus 1 right M plus 1 right then I'm going to update my DP Matrix then I'm going to update my DP Matrix and I will be iterating through the and I will be iterating through the row and columns row and columns right from M plus 1 row and N plus 1 columns then if I'm in the eighth row I will update with column numbers in my DP which is nothing but J itself then if I'm in the zeroth column I will values values right then I will check my characters in my word one if they are equal I'll update that if they are equal I'll update that particular I throw in jet column with particular I throw in jet column with the the I minus 1 I minus 1 . . 1 and J minus 1 value right else I will take and update my current I throw in J column with the my I my I minus 1 and J minus 1 value minus 1 and J minus 1 value then I and J minus 1 value then I will take the I minus 1 and jth column value then I will add One Pilot then finally my result will be at the end row and column that's all the chorus now let's run the so the time complexity is order of n m so the time complexity is order of n m into n and space is order of M into n as into n and space is order of M into n as well well thank you for watching this video please thank you for watching this video please like share and subscribe this will like share and subscribe this will motivate me to upload more videos in motivate me to upload more videos in future and also check out my previous future and also check out my previous videos keep supporting happy learning videos keep supporting happy learning cheers guys | 2024-03-20 11:30:01 | 72 | Edit Distance - Leetcode 72 - Python |
|
Q154Pdb_Mqw | Hey guys welcome back to my YouTube channel I am astrologer and in this video serial I am channel I am astrologer and in this video serial I am solving the problem of lead and solving the problem of lead and today we are going to see the problem which is the today we are going to see the problem which is the media so let's see media so let's see what is the problem what is the problem of scientists we can see that of scientists we can see that of scientists we can see that problem is given by the heart attack list in the problem statement that the attacks have 200 terraces with which you can see the sexual attacks returning to the medium of darkness. You can see the example. First example is the chief guest and if we have Let's march and Let's march and Let's march and what will be the element in it, so for example, if people what will be the element in it, so for example, if people do then put 1234 and do then put 1234 and divide by adding the media, you can see it on the gram divide by adding the media, you can see it on the gram which will be very much a problem which will be very much a problem but the problem here but the problem here is time complexity, that is Bigg Boss. is time complexity, that is Bigg Boss. is time complexity, that is Bigg Boss. neither, how can we find the correct one for this case, so we have seen the problem statement of this problem, seen the problem statement of this problem, so let us know how we can oppose it so let us know how we can oppose it as we have as we have seen that seen that merging both the legs which we give and find out merging both the legs which we give and find out what will be the media. If we have logo and number of what will be the media. If we have logo and number of elements then the media that will remain will be the elements then the media that will remain will be the middle element and if we have middle element and if we have middle element and if we have make even number of elementary, then the media which will be there will be the central two elements, by adding it and dividing it, we will get it, but we cannot use it because if we do not have to do the sum of Bigg Boss, then We will have to do the We will have to do the We will have to do the element, then we will have to use something element, then we will have to use something that we people should subscribe that we people should subscribe * element * element in which we have to search, then let us try to solve this in which we have to search, then let us try to solve this problem which is dead without washing, problem which is dead without washing, if we if we do this then people do this then people do this then people add this thing and this logical left side and a logical right side between share and subscribe if we decide that the war element here is to be taken on the left side element and on the right side which If we do the media then we If we do the media then we If we do the media then we can set the people, know that the total can set the people, know that the total element can be considered as 4.5 and refill, element can be considered as 4.5 and refill, then this element is on the left side then this element is on the left side like this people are present are you consider and like this people are present are you consider and apply binary search in it. apply binary search in it. apply binary search in it. know its left side is its lt lt lt 143 on its left side. Now because we know that in the logical life which is considered in law, there are four elements and already two elements have been considered. From this A B, the remaining element is that of which is the considered Is that is to which is to Is that is to which is to Is that is to which is to should be aspects should get RSSB to elements should be should be aspects should get RSSB to elements should be in zoological park in zoological park if we consider this then we have if we consider this then we have finalized the laptops given by these people but finalized the laptops given by these people but how will we determine that the how will we determine that the laptops which these people have given laptops which these people have given laptops which these people have given correct. To consider this as correct, we have to compare the remote element for the left leg and the right here right now its elements of the other one and it should be smaller than that like we have to compare these Must be smaller with, must be Must be smaller with, must be Must be smaller with, must be equal to, and must be compared to, must be equal to, and must be compared to, must be equal with, if equal with, if both of these start then we will know both of these start then we will know why this minimum husband of media has done this why this minimum husband of media has done this and here the element can and here the element can also do that. also do that. also do that. is confusion here then subscribe, it should be on the right and left side, if you consider it, then I want to say that the media has done it, I will be on the right side, whatever is right, we have Details will remain in between the Details will remain in between the Details will remain in between the left and right left and right portion because the left portion portion because the left portion has element 1234, the right portion has element 1234 and the has element 1234, the right portion has element 1234 and the other 57 will remain medium, it will remain the middle element only other 57 will remain medium, it will remain the middle element only because we do not know because we do not know in which area the President is either. in which area the President is either. sharing the minimum of right left and right left contenders, he will have to sharing the minimum of right left and right left contenders, he will have to select the minimum value of both the media, select the minimum value of both the media, which has become an example and let's which has become an example and let's take one in which people will take one in which people will implement the research, if 12345 157 were melted in it, implement the research, if 12345 157 were melted in it, then it has then it has validators. validators. validators. here we can divide the face into elements and then we can calculate its media. If we go into life, then there will be elements in it. Accordingly, if we look at this matter and calculate here. Do Subscribe Share And if we do that - then you will know that this element has been assigned to compare the two elements before and after, not subscriber, this means it In the left side, consider In the left side, consider In the left side, consider that the young man had to ride point. Quid minus one day test index Quid minus one day test index minus one of 25, this means that he will remove two one. minus one of 25, this means that he will remove two one. Now after the halwa, the Now after the halwa, the logical logical consideration in the smaller reduction on the left side is empty. consideration in the smaller reduction on the left side is empty. consideration in the smaller reduction on the left side is empty. which is one and this message which is logical left motor, three elements are coming in it is one two three and for this case we can see that 143 both the corresponding elements Now we got the logical left Now we got the logical left Now we got the logical left half and logical right half clear half and logical right half clear because in this case there because in this case there is another element president in both the logical houses. Here to is another element president in both the logical houses. Here to remind the sisters, we remind the sisters, we have to use one element from the left hand and have to use one element from the left hand and one element from the right hand. one element from the right hand. one element from the right hand. not know which element is Africa near attacks which is maximum and one element because the right week is near attacks which is minimum. To know this we have considered the logical address. That is, let's use it, we will That is, let's use it, we will calculate the maximum between being considered left calculate the maximum between being considered left part in these three in one part in these three in one and we will calculate the minimum considering part of these and we will calculate the minimum considering part of these latest point five, maximum will latest point five, maximum will come to 3013, minimum will come to 154 and by come to 3013, minimum will come to 154 and by adding that if we adding that if we adding that if we we will get 14.5 so we will understand this problem by subscribing to you, this is the one appointed by subscribing and running the conditioner statement in which keep the size of both at a minimum so that we Which one Which one Which one can do and after that people can do and after that people considered Anshuman as a small considered Anshuman as a small vector in the jam so we will use the taste function and vector in the jam so we will use the taste function and after that calculate the points in the index after that calculate the points in the index that this and this which will that this and this which will represent the friend, after adding both the persons the represent the friend, after adding both the persons the total total total do this and then set the accused then this loot has been conditioned to prevent index flu and what it is, it differentiates and represents the arrest which is different from the other is the first Life in a that the rest of the elements are witch that Saif will be in number two as the day has been noted after that we have done a condition check etc. this loosening x max and no - one is great to the number of side this People were checking whether the considered index is the same condition as other elements, whether it is a small or not, so that we can accurately guess what will be the left half. In these two conditioner statements, we have Which Which Which we, this number will be inside the number one vector left. we, this number will be inside the number one vector left. After gassing you, we ran a cab After gassing you, we ran a cab statement. In the angry statement, we statement. In the angry statement, we first calculated the max left and first calculated the max left and then calculated the mean of Friday. then calculated the mean of Friday. Maths of left means this is what will be left. Maths of left means this is what will be left. After merging Arya, After merging Arya, what will be its maximum volume and main right means what will be its maximum volume and main right means whatever will be written by us, whatever will be written by us, what will be the minimum value of that face? If we are what will be the minimum value of that face? If we are Arya Arya and there will be elements on the number then we will and there will be elements on the number then we will directly return directly return directly return in your next left some age text, initially we have kept the loop at zero, if you index it as 0, it means that the Western Amazon which we have considered is whatever, then the max life which will be that will be of number two. Jail - Details will be that it will be the last value of number two. In the same way if 30 then the max which will be left will be the last element of number 1. If both of these are close then it means that whatever is there is likes from zero. For that case in larger portions, we can calculate the meat loop today. Maximum of No. 9 - 110 No. - As we saw this in the example, now we do not know that we If If If its numbers are one and two, then we will maximize its numbers are one and two, then we will maximize both and if you turn on Totally Free Mode, both and if you turn on Totally Free Mode, then we will return the max left, which will be the result, if these are elements, then our add statement will continue further. Test Hello Main. Adams to define the right, after that we will check that I camp is equal to that SI, our considered actors has reached the end of one, has Guru reached the end, you will have minimum right, he will be number two's Jai. Similarly, If it reaches , then the If it reaches , then the If it reaches , then the main right will be up to Nam Swan's I and main right will be up to Nam Swan's I and in this case also we have in this case also we have considered the minimum of Friday in the same way, S is the considered the minimum of Friday in the same way, S is the minimum of number to Z Adams's I, which minimum of number to Z Adams's I, which we don't even know yet. we don't even know yet. We must have heard that the minimum value will be We must have heard that the minimum value will be in number two because we have in number two because we have reached here only when reached here only when after doing the total calculation in our personality, there is an even number after doing the total calculation in our personality, there is an even number of elements, then we have to do the Max Loop and of elements, then we have to do the Max Loop and Main Ride in the evening. Main Ride in the evening. Main Ride in the evening. divide it by two and return it for any reason. If it doesn't work then we will return zero. So let's run it and see what output is coming. Its solution has been accepted, Tomorrow the college can see that it has been successfully Tomorrow the college can see that it has been successfully submitted and its runtime was only submitted and its runtime was only 1 millisecond and 98 per cent of the 1 millisecond and 98 per cent of the solution. I hope you solution. I hope you liked this video. liked this video. liked this video. like this video and subscribe to my channel. I will keep bringing interview videos in this manner for the people. Thank you for watching my video. Have a Nice Day [Music]. | 2024-03-18 10:49:30 | 4 | #4 Median of Two Sorted Arrays | Ultimate Leetcode Challenge |
|
6txNskrD9xU | hello everyone so today in this video we are going to solve a question of fleet are going to solve a question of fleet code that is remove duplicate letters it code that is remove duplicate letters it is 316 question on lead code and it is 316 question on lead code and it consider medium category all right so consider medium category all right so let's start with the problem statement let's start with the problem statement given as string as remove duplicate given as string as remove duplicate letters so that every letter appears letters so that every letter appears once and only once you must make sure once and only once you must make sure your result is a smallest in your result is a smallest in lexographical order among all possible lexographical order among all possible results so basically in this question we results so basically in this question we have given a string and in this string have given a string and in this string we need to remove all the duplicate we need to remove all the duplicate characters as well as we need to characters as well as we need to maintain the lexographically smallest maintain the lexographically smallest order so let's quickly understand with order so let's quickly understand with an example and how can we approach this an example and how can we approach this question so question so let me make a multi-line comment here let me make a multi-line comment here and let's take the first example in the and let's take the first example in the first example we have first example we have s is equal to s is equal to p c abc this is our first example p c abc this is our first example now now to approach this question let's make to approach this question let's make let's take a answer string let's let's take a answer string let's initially it is zero like it is empty initially it is zero like it is empty and and and let's take two and let's take two vectors like the integer vector so vectors like the integer vector so first one is the count which will be first one is the count which will be storing the count of each characters and storing the count of each characters and second one is visited which will be second one is visited which will be keeping the track whether the character keeping the track whether the character is visited or not so is visited or not so let's count the number of characters so let's count the number of characters so for b we have for b we have two occurrence so two occurrence so let's let's make it two and then we have for c make it two and then we have for c we have we have two occurrence two occurrence for c we have two occurrence then for b for c we have two occurrence then for b we have already we have already counted here so for a we have only one counted here so for a we have only one occurrence so initially we have not occurrence so initially we have not visited anything so let's visited anything so let's make make visited to zero visited to zero initially it is zero and initially it is zero and this is also zero and k is also 0 this is also zero and k is also 0 now let's sit right through our string now let's sit right through our string so so first we get b first we get b so whenever we get b and nothing is in so whenever we get b and nothing is in our answer so let's try to push it in our answer so let's try to push it in our answer and let's make it visited and our answer and let's make it visited and decrement the count as we have already decrement the count as we have already tried through one character of b now tried through one character of b now let's see for c for c let's see for c for c b is less than c so we can push it into b is less than c so we can push it into our answer because it is lexographically our answer because it is lexographically correct so let's push c into our answer correct so let's push c into our answer and let's decrement the count by one and and let's decrement the count by one and make it visit it make it visit it now we have c now we have a so for a now we have c now we have a so for a a is less than c so a is less than c so it's not lexographically correct if we it's not lexographically correct if we directly push it into our answer so directly push it into our answer so let's check for b and c so let's check for b and c so for c for c c c this count is 1 this count is 1 it means c is available in this it means c is available in this remaining string as well so let's pop it remaining string as well so let's pop it out from here and out from here and let's make it unvisited so let's let's make it unvisited so let's initialize c with zero like update c initialize c with zero like update c with zero and with zero and the count is same because that is the count is same because that is popping up so popping up so let's check for b let's check for b b is also present since count is greater b is also present since count is greater than zero and let's make it unvisited than zero and let's make it unvisited now let's see for a so let us keep now let's see for a so let us keep pushing over pushing over answer and answer and let's decrement the count let's decrement the count and make it and make it visited now we have b visited now we have b so we can push b to our answer because so we can push b to our answer because it is lexographically correct it is lexographically correct so so let's push it to our answer and let's push it to our answer and make it visit it and just decrement the make it visit it and just decrement the count count now we have seen let's push c into our now we have seen let's push c into our answer because it is lexographically answer because it is lexographically correct because c is greater than b and correct because c is greater than b and let's decrement the count and make it let's decrement the count and make it visited visited now we have completed the iteration of now we have completed the iteration of our given string so our given string so as an answer we get abc so we will as an answer we get abc so we will directly written abc from here as this directly written abc from here as this is our desired answer is our desired answer so i hope the project is clear to you so i hope the project is clear to you let's quickly fold it up let's quickly fold it up all right so let's make a string all right so let's make a string initially it is empty now let's take a vector vector of integer let's take count 26 comma 0 we are taking 26 characters because like we are given we have only lowercase english character so let's make 26 and also make a visited vector this will be stored in 26 characters so yeah let's run a for loop to count the number of occurrence of a particular character so let's run our for loop x yes and just increment the count for each index plus plus plus plus now let's run a for loop to create now let's run a for loop to create through our string and through our string and write the logic for it so write the logic for it so auto x yes and auto x yes and let's decrement the count whenever we let's decrement the count whenever we get a character so x minus a get a character so x minus a minus minus minus minus now let's check if it is unvisited like now let's check if it is unvisited like this this is unvisited then we will check is unvisited then we will check the the remaining like the our current answer so remaining like the our current answer so answer dot answer dot size is greater than zero size is greater than zero and answer dot back like the previous element like the like the current element which we just pushed in our answer should be greater than like it should be less than if it is greater than we will just pop it out so like if answer dot back is greater than x and the count of answer dot back and the count of answer dot back minus a is greater than zero like if it minus a is greater than zero like if it is present in the remaining string then is present in the remaining string then only we can just pop it out so let's only we can just pop it out so let's make it make it unvisited unvisited so answer or back so answer or back minus a is minus a is unvisited and let's pop it out from our unvisited and let's pop it out from our answer so answer answer so answer pop back all right now let's just add the current character into our answer so answer plus equal to x and let's make it visited so visited x minus e is equal to 1 and then just written answer from here i hope it should work fine let's just yeah it's working fine now let's just yeah it's working fine now let's just submit it yeah it's perfectly fine now let's calculate the time and space complexity of our solution so time complexity of our solution is speak off and because we are creating through all the n elements and space complexity is also big of n because we are storing all the n characters into our string as well in the vector so space and time complexities are because n so that's it for this video i hope you understood the solution if you still have an advantage in this question feel free to comment down please like this video and subscribe to our channel thank | 2024-03-24 10:23:11 | 316 | 316. Remove Duplicate Letters | O(n) 🔥🔥 | LeetCode | C++ |
|
aYqYMIqZx5s | everyone welcome back and let's write some more neat code today so today let's some more neat code today so today let's solve the problem minimum size subarray solve the problem minimum size subarray sum we're given an array of positive sum we're given an array of positive integers and that's actually going to be integers and that's actually going to be an important detail the fact that an important detail the fact that they're all positive and we're also they're all positive and we're also given a target value and all we want to given a target value and all we want to do is return the minimum length of a do is return the minimum length of a contiguous subarray uh basically think contiguous subarray uh basically think of a contiguous subarray as like a of a contiguous subarray as like a window within our array so for example window within our array so for example this is our array you know we want some this is our array you know we want some window in this array and we want the sum window in this array and we want the sum of all the values in that window to be of all the values in that window to be greater than or equal than the target greater than or equal than the target value now there could be multiple value now there could be multiple windows like this but remember we want windows like this but remember we want to return the one that has the minimum to return the one that has the minimum length and specifically we're going to length and specifically we're going to return the length of that window so in return the length of that window so in this case this case our target value is seven so is there our target value is seven so is there any window here that sums up to seven any window here that sums up to seven well there's many right like the whole well there's many right like the whole array itself could be but the shortest array itself could be but the shortest one in terms of length is this one four one in terms of length is this one four and three because they sum up to seven and three because they sum up to seven and the length of that window is two and the length of that window is two looking at the second example you know looking at the second example you know this could be considered a window but this could be considered a window but there's a shorter one you know the value there's a shorter one you know the value for itself it could be this one or it for itself it could be this one or it could be this one there's a multiple in could be this one there's a multiple in this case but the length of each of them this case but the length of each of them is one so we can return one as the is one so we can return one as the result so let's immediately jump into result so let's immediately jump into the brute force solution because it's the brute force solution because it's not too difficult to come up with i mean not too difficult to come up with i mean we could try every possible subarray or we could try every possible subarray or every possible window in other words every possible window in other words right and we could do that with nested right and we could do that with nested for loops what i mean is for loops what i mean is we look at every single window starting we look at every single window starting at two right this is the first window at two right this is the first window then the the next window is the first then the the next window is the first two values then this then this and then two values then this then this and then basically keep going right and basically keep going right and technically we don't have to actually go technically we don't have to actually go through the entire array because we're through the entire array because we're going to stop the first time that we going to stop the first time that we find a window that sums up to the target find a window that sums up to the target value in this case i think it's this one value in this case i think it's this one because this sums up to i think these because this sums up to i think these three are six plus two that's going to three are six plus two that's going to be eight so this is one window the size be eight so this is one window the size of it is four so that's the shortest of it is four so that's the shortest window starting at 2 that will sum up to window starting at 2 that will sum up to the target but there could be even the target but there could be even shorter windows that maybe start at 3 so shorter windows that maybe start at 3 so then we try every window starting at 3 then we try every window starting at 3 etc etc we do that for every value in etc etc we do that for every value in this entire array that's how we're going this entire array that's how we're going to use the nested for loops now the time to use the nested for loops now the time complexity of that is going to be big o complexity of that is going to be big o of n squared where n is the size of the of n squared where n is the size of the input array so the question is can we do input array so the question is can we do better yes we can do better and we can better yes we can do better and we can actually use this brute force solution actually use this brute force solution to figure out how we can do better to figure out how we can do better because there is some repeated work that because there is some repeated work that we're doing here which might not be we're doing here which might not be immediately obvious let's uh first you immediately obvious let's uh first you know go through starting at two right know go through starting at two right now our sum is two uh now we include the now our sum is two uh now we include the three now our sum is five now our sum is three now our sum is five now our sum is six we're still under the target we six we're still under the target we include one last value uh two now our include one last value uh two now our sum is a so by doing this we found out sum is a so by doing this we found out that the shortest window that can sum up that the shortest window that can sum up to the target starting at the two is of to the target starting at the two is of length four right four values and of length four right four values and of course we could add more values to the course we could add more values to the window now but those are just gonna make window now but those are just gonna make the window longer so there's no point in the window longer so there's no point in doing that so then next what we're gonna doing that so then next what we're gonna do is then start at the three and then do is then start at the three and then you know do the work that we were just you know do the work that we were just doing right in other words we're gonna doing right in other words we're gonna then include the one then include the then include the one then include the two but didn't we kind of already do two but didn't we kind of already do that work with the first pass so why that work with the first pass so why should we repeat it now and this is should we repeat it now and this is where it comes into play the values in where it comes into play the values in the array are going to be positive what the array are going to be positive what does that mean for us because if there does that mean for us because if there were negatives that would complicate were negatives that would complicate things but since it's positive we know things but since it's positive we know for sure one important thing and that for sure one important thing and that important thing is it wasn't until we important thing is it wasn't until we included this value that our first included this value that our first window window was greater than or equal to the target was greater than or equal to the target right that's pretty obvious so then my right that's pretty obvious so then my question to you is is it ever going to question to you is is it ever going to be possible that starting from this 3 we be possible that starting from this 3 we find a window before the last value of find a window before the last value of the previous window right that green the previous window right that green window window is it going to be possible that we find is it going to be possible that we find a window like this that's also going to a window like this that's also going to be greater than or equal to the target be greater than or equal to the target no way because we know all these values no way because we know all these values are positive this value is positive now are positive this value is positive now that we're starting at 3 we're not that we're starting at 3 we're not including this value anymore and we know including this value anymore and we know for sure that until we reach this 2 when for sure that until we reach this 2 when we just had these three values we we just had these three values we definitely were not greater than or definitely were not greater than or equal to the target so how is it going equal to the target so how is it going to be possible that with just these to be possible that with just these values we're going to be greater than or values we're going to be greater than or equal to the target it's not possible so equal to the target it's not possible so what i'm saying is we don't have to uh what i'm saying is we don't have to uh even we don't have to consider this even we don't have to consider this window we're never going to find a window we're never going to find a window this short starting at three we window this short starting at three we can just include the entire window can just include the entire window except for that first value that we were except for that first value that we were doing and if you're starting to see what doing and if you're starting to see what we're doing here this is a very common we're doing here this is a very common technique called the sliding window technique called the sliding window we're gonna maintain two pointers and we're gonna maintain two pointers and shift those pointers accordingly as we shift those pointers accordingly as we find a valid window so let's run through find a valid window so let's run through this algorithm it's going to actually be this algorithm it's going to actually be pretty simple it's very standard sliding pretty simple it's very standard sliding window okay i'll run through it quickly window okay i'll run through it quickly we started at the two uh we're going to we started at the two uh we're going to take uh this is our left pointer by the take uh this is our left pointer by the way so let's actually call it left and way so let's actually call it left and then our right pointer is initially then our right pointer is initially going to be here too we're going to going to be here too we're going to maintain what the total is so far so maintain what the total is so far so right now we're at two and we're going right now we're at two and we're going to keep uh increasing our window so now to keep uh increasing our window so now our total is actually going to be five our total is actually going to be five but five is still less than seven so but five is still less than seven so we're going to shift our right pointer we're going to shift our right pointer again so now our total is going to be again so now our total is going to be six that's also less than the target six that's also less than the target we're going to shift again now our total we're going to shift again now our total is going to be eight now the question is is going to be eight now the question is this might be our result well what's the this might be our result well what's the size of the window right now it's four size of the window right now it's four so i'm not going to write it down but so i'm not going to write it down but let's just keep track mentally of what let's just keep track mentally of what the shortest window that we find and the shortest window that we find and once we find a valid window like this once we find a valid window like this one we know that we can just chop off one we know that we can just chop off the left value there's no point in the left value there's no point in repeating the work or just because now repeating the work or just because now we're going to start at 3 we don't have we're going to start at 3 we don't have to recompute all this let's just shift to recompute all this let's just shift our left pointer so i'm going to do that our left pointer so i'm going to do that like this and since we got rid of this 2 like this and since we got rid of this 2 our total is actually going to be our total is actually going to be decremented by 2 so instead of 8 we're decremented by 2 so instead of 8 we're going to be now at a 6. our right going to be now at a 6. our right pointer is going to be here but now pointer is going to be here but now we're going to start shifting our right we're going to start shifting our right pointer because our total is less than pointer because our total is less than the target so uh we're going to shift the target so uh we're going to shift the right pointer one more time to here the right pointer one more time to here so now our total is going to be 10 we're so now our total is going to be 10 we're going to add this four that we just got going to add this four that we just got so now our total is 10 it's greater than so now our total is 10 it's greater than or equal to the target but this window or equal to the target but this window is also of size four so it's not any is also of size four so it's not any shorter than the previous one but now shorter than the previous one but now we're going to uh shift our left pointer we're going to uh shift our left pointer it was over here now we're going to it was over here now we're going to shift it to this position so left is shift it to this position so left is here our right pointer is still here but here our right pointer is still here but we have to decrement the three from our we have to decrement the three from our total total our total was 10 now it's going to be 7. our total was 10 now it's going to be 7. but our window this time is a valid but our window this time is a valid right 7 is greater than or equal to the right 7 is greater than or equal to the target target and our window is a little bit shorter and our window is a little bit shorter this time it's of size 3. since our this time it's of size 3. since our window is valid we're going to take the window is valid we're going to take the left pointer and then shift it so it's left pointer and then shift it so it's now going to be over here our window now now going to be over here our window now our target was seven now we're going to our target was seven now we're going to decrement it by one so our our total is decrement it by one so our our total is going to be six now that's less than the going to be six now that's less than the target so let's start uh incrementing target so let's start uh incrementing our right pointer so now our right our right pointer so now our right pointer is going to be over here and our pointer is going to be over here and our window is once again uh now it's we're window is once again uh now it's we're adding the three so now our total is adding the three so now our total is nine so it's valid the size of it is nine so it's valid the size of it is three of course that's greater than the three of course that's greater than the target three is what we already target three is what we already previously had uh but now we're going to previously had uh but now we're going to shift our left pointer because the shift our left pointer because the window is valid and now the left pointer window is valid and now the left pointer is going to be over here is the window is going to be over here is the window still valid yes it is right because we still valid yes it is right because we decremented the total by two so now it decremented the total by two so now it went from being nine to now being seven went from being nine to now being seven seven is still uh greater than or equal seven is still uh greater than or equal to the target so now our window is of to the target so now our window is of size two and one thing i didn't actually size two and one thing i didn't actually mention in any of the previous cases is mention in any of the previous cases is while our window is still valid we're while our window is still valid we're going to be incrementing the left going to be incrementing the left pointer because there's no need to shift pointer because there's no need to shift the right pointer and add elements if the right pointer and add elements if our window is currently valid right our window is currently valid right that's when we want to be shrinking the that's when we want to be shrinking the windows it could be possible that windows it could be possible that multiple consecutive times we end up multiple consecutive times we end up shifting the left pointer in this case shifting the left pointer in this case we are going to shift the left pointer we are going to shift the left pointer it's going to it's going to be here now left and right are at three be here now left and right are at three but now our window is no longer valid of but now our window is no longer valid of course we're going to take the right course we're going to take the right pointer and then shift it but now it's pointer and then shift it but now it's going to be out of bounds so that's how going to be out of bounds so that's how you know we can stop and you know we can stop and you know we basically found all of the you know we basically found all of the windows that we possibly could and the windows that we possibly could and the shortest one was this one of size two so shortest one was this one of size two so two is going to be what we return that's two is going to be what we return that's exactly what was expected in this exactly what was expected in this example problem if you noticed well we example problem if you noticed well we do have two pointers so in a sense we're do have two pointers so in a sense we're going to be scanning through the array going to be scanning through the array two times uh but that's still big o of n two times uh but that's still big o of n time complexity there's really no extra time complexity there's really no extra memory complexity we don't have any data memory complexity we don't have any data structures just a couple of pointers so structures just a couple of pointers so the memory complexity is big o of one the memory complexity is big o of one with that said we can jump into the code with that said we can jump into the code now so now let's code it up we have our now so now let's code it up we have our left pointer and our total which are two left pointer and our total which are two variables we're going to be keeping variables we're going to be keeping track of so our left pointer of course track of so our left pointer of course initially is going to be at the initially is going to be at the beginning our total uh sum beginning our total uh sum is what the total represents is also is what the total represents is also initially going to be zero the reason we initially going to be zero the reason we don't have a right pointer is because don't have a right pointer is because that we're actually just going to that we're actually just going to be incrementing our right pointer each be incrementing our right pointer each time time using a for loop we could have done it using a for loop we could have done it differently but i feel like it's a differently but i feel like it's a little bit easier to do it this way so little bit easier to do it this way so our right pointer is just going to our right pointer is just going to iterate through every position in the iterate through every position in the input array now our result is what's input array now our result is what's going to be that minimum length that going to be that minimum length that we're trying to return initially we can we're trying to return initially we can set it to you know multi we could set it set it to you know multi we could set it to a default value of infinity which is to a default value of infinity which is what i'm going to do in this case what i'm going to do in this case because one detail that they mention is because one detail that they mention is if we don't find an array that sums up if we don't find an array that sums up to the target then we can return a to the target then we can return a default value of zero so what i'm going default value of zero so what i'm going to say is return zero if a result is to say is return zero if a result is equal to equal to the initial infinity value and if it's the initial infinity value and if it's not equal to infinity then we can not equal to infinity then we can actually return the real result which we actually return the real result which we calculated in that variable if you don't calculated in that variable if you don't have an infinity in your language or have an infinity in your language or whatever you could also set it to the whatever you could also set it to the length of the input array plus 1 because length of the input array plus 1 because that's also technically an invalid value that's also technically an invalid value and that's also a large value you could and that's also a large value you could set it to negative 1 as well if you want set it to negative 1 as well if you want but but the reason i'm setting it to a big value the reason i'm setting it to a big value is because remember we're trying to is because remember we're trying to minimize it so we're going to be using minimize it so we're going to be using like the min function like the min function within this for loop okay but now for within this for loop okay but now for the actual sliding window portion the actual sliding window portion remember each time we add a new value at remember each time we add a new value at the right pointer we're going to be the right pointer we're going to be taking that value and adding it to our taking that value and adding it to our total right that's the first and very total right that's the first and very basic step so let's add that value at basic step so let's add that value at index right to our total but also index right to our total but also remember that if the total becomes remember that if the total becomes greater than or equal to the target well greater than or equal to the target well one the first thing uh to do then is one the first thing uh to do then is potentially we have found our result but potentially we have found our result but our result is going to be the size of our result is going to be the size of the window how do we get the size of the the window how do we get the size of the window we can take the right pointer window we can take the right pointer minus the left pointer a plus minus the left pointer a plus one which is going to give us the size one which is going to give us the size of the window and remember we're trying of the window and remember we're trying to minimize the result so we're going to to minimize the result so we're going to set the result equal to the minimum of set the result equal to the minimum of that computation right the size of the that computation right the size of the current window as well as the minimum of current window as well as the minimum of the result itself so of course if the the result itself so of course if the result is infinity then you know this result is infinity then you know this will become the new result but if the will become the new result but if the result is already a smaller value than result is already a smaller value than this window then the result is going to this window then the result is going to stay the same okay that's the first step stay the same okay that's the first step but also remember we want to increment but also remember we want to increment our left pointer by one now because if our left pointer by one now because if the window is already greater than or the window is already greater than or equal to the target let's try to find a equal to the target let's try to find a smaller window but remember if this smaller window but remember if this condition holds multiple times multiple condition holds multiple times multiple consecutive times then we want to consecutive times then we want to continue incrementing the left pointer continue incrementing the left pointer as well as potentially you know figuring as well as potentially you know figuring out if we found the result so instead of out if we found the result so instead of having this be an if statement let's having this be an if statement let's make it a while loop now just because we make it a while loop now just because we have a while loop inside of a for loop have a while loop inside of a for loop does not mean the time complexity is n does not mean the time complexity is n squared think about how many times this squared think about how many times this loop is going to execute in total in the loop is going to execute in total in the worst case the left pointer will be worst case the left pointer will be incremented until it's out of bounds of incremented until it's out of bounds of the nums array now we don't need to you the nums array now we don't need to you know confirm that because if that was know confirm that because if that was the case then of course our total would the case then of course our total would be zero and we know that the target is be zero and we know that the target is always going to be a positive number so always going to be a positive number so then the loop would exit by itself then the loop would exit by itself anyway there's one thing that i actually anyway there's one thing that i actually forgot with this loop before we actually forgot with this loop before we actually increment the left pointer we also want increment the left pointer we also want to subtract the value at the left to subtract the value at the left pointer from our total right because our pointer from our total right because our total represents the values in our total represents the values in our current window if we're updating our current window if we're updating our window then we also have to update the window then we also have to update the total value and that is actually the total value and that is actually the entire code as long as i didn't make any entire code as long as i didn't make any mistakes so let's run it to make sure mistakes so let's run it to make sure that it works and as you can see on the that it works and as you can see on the left yes it does and it's pretty left yes it does and it's pretty efficient so i really hope that this was efficient so i really hope that this was helpful if it was please like and helpful if it was please like and subscribe it really supports the channel subscribe it really supports the channel a lot consider checking out my patreon a lot consider checking out my patreon where you can further support the where you can further support the channel and hopefully i'll see you channel and hopefully i'll see you pretty soon thanks for watching | 2024-03-22 10:14:28 | 209 | Minimum Size Subarray Sum - Leetcode 209 - Python |
|
RYSkjEIovsw | [Music] hey guys welcome back to another video hey guys welcome back to another video and today we're going to be solving the and today we're going to be solving the leaka question h leaka question h index so in this question we're given an index so in this question we're given an array array of citations and we need to write of citations and we need to write a function to compute the researchers h a function to compute the researchers h index so what exactly is the h index index so what exactly is the h index so over here we have the definition a so over here we have the definition a scientist has scientist has index h if h of his or her end papers index h if h of his or her end papers have at least n site h citations each have at least n site h citations each and the other n minus h papers have no and the other n minus h papers have no more than eight more than eight citations each so as it is i think the citations each so as it is i think the definition is pretty confusing definition is pretty confusing so what i'm going to do is i'm going to so what i'm going to do is i'm going to break it down step by step break it down step by step and we're going to be following this uh and we're going to be following this uh question over here so question over here so we're going to take this as our input so we're going to take this as our input so let's just go let's just go line by line so a scientist has index h line by line so a scientist has index h so this is what we're looking for so this is what we're looking for we're looking for the index h if h of we're looking for the index h if h of his or her his or her n papers so over here let's initialize a n papers so over here let's initialize a variable called variable called n and n over here is going to be the n and n over here is going to be the number of papers they have number of papers they have and in other words this is going to be and in other words this is going to be the length of our citations area the length of our citations area so in this case we have a length of five so in this case we have a length of five so our so our n value is going to be five okay so a n value is going to be five okay so a scientist has index scientist has index h so if each of his or her paper so h so if each of his or her paper so we have h papers over here so out of we have h papers over here so out of these h papers these h papers all of these papers have at least eight all of these papers have at least eight citations each citations each so the number of citations are equal to so the number of citations are equal to or greater than h so we don't know what or greater than h so we don't know what the number the number value h is yet but h papers have a value value h is yet but h papers have a value greater than or equal to the value h greater than or equal to the value h okay so the second part is and the other okay so the second part is and the other n minus age paper so it's saying the n minus age paper so it's saying the rest of the papers rest of the papers so in this case it's going to be the so in this case it's going to be the rest of the papers are nothing else rest of the papers are nothing else but n minus h so the rest of the n minus but n minus h so the rest of the n minus h papers have no more than eight h papers have no more than eight citations each so citations each so have no more is equal to or less than have no more is equal to or less than the value the value h so this is what defines the h index h so this is what defines the h index so let's just take the example so over so let's just take the example so over here here our output is the number three so let's our output is the number three so let's just rewrite it just rewrite it so we have three papers so for papers so we have three papers so for papers i'm just gonna write p i'm just gonna write p which are equal to or greater than the which are equal to or greater than the number three so what that means is number three so what that means is three papers have at least three three papers have at least three citations each so let's just take a look citations each so let's just take a look at that at that so we have the value three so that's one so we have the value three so that's one we have six we have six so that's two and we have five that's so that's two and we have five that's three so as you can see we have three three so as you can see we have three papers papers which meet that criteria now let's look which meet that criteria now let's look at the remaining papers at the remaining papers so the remaining papers in this case are so the remaining papers in this case are the values 0 the values 0 and the value 1. and what this is saying and the value 1. and what this is saying is is both of these papers no matter what have both of these papers no matter what have a value which is equal to or less than a value which is equal to or less than the h value so if you look at zero it's the h value so if you look at zero it's less than less than h and h is three so zero is less than h and h is three so zero is less than three and one is also less than three three and one is also less than three and this is why the answer for this is and this is why the answer for this is three so now what we're going to do is three so now what we're going to do is let's see at how we can let's see at how we can solve this question so this wikipedia solve this question so this wikipedia link has link has a lot of the information we need and a lot of the information we need and over here you can clearly see that over here you can clearly see that so first we order the values of f from so first we order the values of f from largest to lowest value largest to lowest value then we look at the last position in then we look at the last position in which f which f is greater than or equal to the position is greater than or equal to the position so i think that's pretty simple and so i think that's pretty simple and let's just write that in code so let's just write that in code so our first step over here is going to be our first step over here is going to be to sort our to sort our citations so citations citations so citations dot sort and we want to sort it in dot sort and we want to sort it in descending order descending order so to do that we just need to do reverse so to do that we just need to do reverse equals to true equals to true so now we sorted it in descending order so now we sorted it in descending order so now what we're going to do is we're so now what we're going to do is we're going to iterate going to iterate through our citations but what we're through our citations but what we're gonna do is we need to gonna do is we need to compare the citation value to compare the citation value to the value of our index and the easiest the value of our index and the easiest way to do this way to do this is by enumerating the list and what that is by enumerating the list and what that does is we get a tuple value does is we get a tuple value of our index and then the citation so to of our index and then the citation so to do that do that for index comma citation for index comma citation in enumerate in enumerate and we're going to call our citations and we're going to call our citations over your citations over your citations okay over here we're going to return the okay over here we're going to return the index index when the index has a greater value than when the index has a greater value than our citation our citation so in this case if index is greater than so in this case if index is greater than or equal to our citation value and in or equal to our citation value and in that case we're just going to return that case we're just going to return our index and that's going to be the h our index and that's going to be the h value value but if this is not the case then we're but if this is not the case then we're just going to return just going to return but if that is not the case we're just but if that is not the case we're just going to return going to return the length of our citations the length of our citations and the purpose of this is because if and the purpose of this is because if you go up to our definition over here you go up to our definition over here so if we did not find any answer and our so if we did not find any answer and our h index is the length of our citations h index is the length of our citations that means that each of his or her end that means that each of his or her end papers papers have at least eight citations each so have at least eight citations each so obviously obviously all the papers have more citations than all the papers have more citations than that that h value which is going to be the length h value which is going to be the length of our citations of our citations so if none of these uh are true so if none of these uh are true if we do not return anything inside of if we do not return anything inside of our for loop we're going to end up our for loop we're going to end up returning the length of our citations returning the length of our citations so let's submit to our answer and so let's submit to our answer and as you can see our submission to get as you can see our submission to get accepted and finally do let me know what accepted and finally do let me know what you thought about the video you thought about the video and don't forget to like and subscribe and don't forget to like and subscribe if this video helped you if this video helped you thank you thank you bye | 2024-03-22 12:32:38 | 274 | H-Index | Leet code 274 | Theory explained + Python code |
|
OoGswqFU-zs | hey what's up guys it's Nick white here I do tech inchoate hey what's up guys I do tech inchoate hey what's up guys think white here I did technically stuff think white here I did technically stuff on Twitch on youtube check the on Twitch on youtube check the description I got all my stuff there I description I got all my stuff there I do these premium problems on leak code do these premium problems on leak code there on my patreon if you want to check there on my patreon if you want to check that out and join the discord that out and join the discord this is min-cost climbing stairs a this is min-cost climbing stairs a pretty cool problem gives you kind of an pretty cool problem gives you kind of an intro to dynamic programming if you intro to dynamic programming if you don't know what dynamic programming is don't know what dynamic programming is maybe look it up but I guess I can maybe look it up but I guess I can explain it it's basically if your jet if explain it it's basically if your jet if you're answering problems more than once you're answering problems more than once then that's usually bad and you don't then that's usually bad and you don't want to do that so sometimes you might want to do that so sometimes you might want to use space or you might want to want to use space or you might want to save an answer or a previous answer that save an answer or a previous answer that you calculated and use it later to speed you calculated and use it later to speed up your run time that's generally what up your run time that's generally what it is on a staircase the ID step has it is on a staircase the ID step has some non-negative cost cost of AI so we some non-negative cost cost of AI so we have a staircase and it's represented as have a staircase and it's represented as an array of integers cost each in each an array of integers cost each in each value in the array is the cost of value in the array is the cost of climbing a stair once you pay the cost climbing a stair once you pay the cost you can either climb one or two steps so you can either climb one or two steps so if I pay the cost 10 I can climb to 15 if I pay the cost 10 I can climb to 15 or I can go to 20 if I pay 15 I can go or I can go to 20 if I pay 15 I can go to 20 or I can just go to the end I'm to 20 or I can just go to the end I'm done with the array I climb to finish done with the array I climb to finish the staircase you need to find the the staircase you need to find the minimum cost to reach the top floor and minimum cost to reach the top floor and you can either start from the step with you can either start from the step with index 0 or this step with index 1 so index 0 or this step with index 1 so these are not sorted arrays by any means these are not sorted arrays by any means some values can be really large some can some values can be really large some can be really small we want to find the be really small we want to find the minimum cost to get to the top the end minimum cost to get to the top the end of the array we could start at either of the array we could start at either index so this is a little bit it's index so this is a little bit it's almost like a mix of like a greedy almost like a mix of like a greedy algorithm and dynamic programming I algorithm and dynamic programming I would say because it might be greedy in would say because it might be greedy in the sense that like you're making the the sense that like you're making the current choice now of I think the current choice now of I think the obvious thing is like pick the smaller obvious thing is like pick the smaller number right so you're gonna look at the number right so you're gonna look at the two staircases you can go one or two two staircases you can go one or two steps and you could start at the first steps and you could start at the first or second position or second position so we're gonna look at these and which so we're gonna look at these and which one are we gonna start on guys I think one are we gonna start on guys I think we're obviously gonna start on the first we're obviously gonna start on the first one because it's smaller and when you one because it's smaller and when you jump what are you going to jump to the jump what are you going to jump to the larger of the smaller the smaller larger of the smaller the smaller obviously etc so you keep going cost us obviously etc so you keep going cost us six in this example on this one it's six in this example on this one it's just 15 and then you jump over 20 and just 15 and then you jump over 20 and then you're done so that one's that then you're done so that one's that that's obvious so it's really not a hard that's obvious so it's really not a hard problem problem you could there's a couple approaches you could there's a couple approaches they're basically this they're pretty they're basically this they're pretty similar but let's do let's do a if your similar but let's do let's do a if your I guess here's the two different I guess here's the two different differences of approach if you're able differences of approach if you're able to modify this array then we can do it to modify this array then we can do it probably this is the easier way you probably this is the easier way you would do a loop you would just do I would do a loop you would just do I equals two you'd start at I less than equals two you'd start at I less than cost out length in then I plus plus and cost out length in then I plus plus and then you would just do cost of I plus then you would just do cost of I plus equals the math dot min of cost of I equals the math dot min of cost of I minus one the previous two steps you minus one the previous two steps you know this is pretty obvious know this is pretty obvious it just is going to store or add to the it just is going to store or add to the value it's going to add to the current value it's going to add to the current value whatever the cheaper step was I value whatever the cheaper step was I mean like for example in when we're at a mean like for example in when we're at a hundred and we look at the minimum if we hundred and we look at the minimum if we start at two we start at one and then we start at two we start at one and then we would do you know what I mean you start would do you know what I mean you start at the second position and you check the at the second position and you check the previous two and whatever the minimum previous two and whatever the minimum was is the one you jumped from and then was is the one you jumped from and then you keep doing that the whole way you keep doing that the whole way through so that's that makes sense right through so that's that makes sense right that's pretty obvious and then when that's pretty obvious and then when you're at the end it will have added up you're at the end it will have added up the indices and have chosen the minimum the indices and have chosen the minimum of all the steps till you get to the end of all the steps till you get to the end so you're at the end and you're just at so you're at the end and you're just at the final two steps and you just the final two steps and you just returned math dot min of cost of cost returned math dot min of cost of cost length minus one in length minus one in most of cost up lane - - sorry so this most of cost up lane - - sorry so this is one solution I would say yeah see is one solution I would say yeah see this one works and I didn't even test this one works and I didn't even test these out before but that's a good one these out before but that's a good one and then you could use a little bit and then you could use a little bit that's kind of a greedy one more so cuz that's kind of a greedy one more so cuz you're kind of just picking the minimums you're kind of just picking the minimums until you get to the end putting them in until you get to the end putting them in the array but if you're not allowed to the array but if you're not allowed to modify this array it might be a little modify this array it might be a little bit harder so another way you could do bit harder so another way you could do it is more dynamic programming related it is more dynamic programming related so you could say you know you could call so you could say you know you could call these variables whatever you want like these variables whatever you want like step one in step 2 or f1 and f2 or step one in step 2 or f1 and f2 or whatever we could call step one we'll whatever we could call step one we'll call it step one and step two so we'll call it step one and step two so we'll say step one step two we will loop from say step one step two we will loop from the end of the array - one to the I the end of the array - one to the I greater than or equal to zero backwards greater than or equal to zero backwards and do it kind of the opposite way but and do it kind of the opposite way but we'll save these variables we'll use we'll save these variables we'll use these variables because if we can't these variables because if we can't modify the array we have to use some modify the array we have to use some kind of storage to get the final answer kind of storage to get the final answer so what we do is we just say we'll make so what we do is we just say we'll make a new variable and we'll say you know a new variable and we'll say you know whatever we want us to current step is whatever we want us to current step is equal to cost of I so the current cost equal to cost of I so the current cost plus sorry I have to blue I'm gonna plus sorry I have to blue I'm gonna sneeze plus math dot min have step one sneeze plus math dot min have step one and step two and this will be nothing at and step two and this will be nothing at first so you just start out with it's first so you just start out with it's the same concept as the one we just did the same concept as the one we just did before so you just add the value of the before so you just add the value of the last element to whatever the previous last element to whatever the previous steps are going to be and we're gonna steps are going to be and we're gonna calculate those later on by just doing calculate those later on by just doing okay okay step two now step 1 is equal to step to step two now step 1 is equal to step to remember the reference you don't want to remember the reference you don't want to lose reference and then step two is lose reference and then step two is equal to current step and then you just equal to current step and then you just return the return the math dot min of step 1 in step 2 math dot min of step 1 in step 2 at the end because these will get down at the end because these will get down to the first two things and you want the to the first two things and you want the minimums of those and it would have all minimums of those and it would have all added up by the end of it so I think added up by the end of it so I think this one works too I haven't tested this this one works too I haven't tested this out either right they're both good this out either right they're both good this one's more dynamic programming because one's more dynamic programming because you're kind of saving things but it's you're kind of saving things but it's not I don't know it's kind of a greedy not I don't know it's kind of a greedy algorithm let me know what you guys algorithm let me know what you guys think I'm kind of torn between greedy think I'm kind of torn between greedy and dynamic programming this this and dynamic programming this this solution says dynamic programming but it solution says dynamic programming but it seems more like greedy algorithm to me seems more like greedy algorithm to me if you want me to run through I think I if you want me to run through I think I have this yeah if you wanted me to run have this yeah if you wanted me to run through this this is from the solution through this this is from the solution that they had we could do step one step that they had we could do step one step two our step is it current step sorry two our step is it current step sorry I'll just print these out for you so you I'll just print these out for you so you can see what's happening step one step can see what's happening step one step two you know we could do one step two two you know we could do one step two current step and let's run test case for current step and let's run test case for you guys to see what's going on I cannot you guys to see what's going on I cannot find symbol oh this has to be in the find symbol oh this has to be in the loop sorry loop sorry you know you can turn this off if you you know you can turn this off if you don't want to watch this walkthrough but don't want to watch this walkthrough but I assume some people might get confused I assume some people might get confused so with dynamic programming it's so with dynamic programming it's probably the most confusing thing even probably the most confusing thing even though this is a pretty easy one so if though this is a pretty easy one so if we run test case on this one for example we run test case on this one for example 10 15 20 it starts at the end and then 10 15 20 it starts at the end and then it's 20 and then it adds you know 20 it's 20 and then it adds you know 20 plus the minimum of the previous to two plus the minimum of the previous to two steps which aren't set yet so it'd just steps which aren't set yet so it'd just be zeros but later on we get to the next be zeros but later on we get to the next one and there'll be 15 plus you know the one and there'll be 15 plus you know the minimum of those which would be you know minimum of those which would be you know zero and 20 and then it would be 10 plus zero and 20 and then it would be 10 plus you know what I mean like current step you know what I mean like current step is equal to the current element 20 plus is equal to the current element 20 plus the minimum of zeroes so it's 20 the minimum of zeroes so it's 20 step one is zero still and current step step one is zero still and current step step two get set to current step so get step two get set to current step so get set to 20 then current step is 15 plus set to 20 then current step is 15 plus minimum of zero and 20 so it becomes 15 minimum of zero and 20 so it becomes 15 step two becomes 15 after step one step two becomes 15 after step one becomes 20 so step two is fifteen step becomes 20 so step two is fifteen step one is twenty current step is 15 then one is twenty current step is 15 then it's ten plus the minimum of 20 and 15 it's ten plus the minimum of 20 and 15 so it is 10 plus 15 and then it's 25 and so it is 10 plus 15 and then it's 25 and then step two is set step one is set to then step two is set step one is set to 15 and step two is set to 25 and then 15 and step two is set to 25 and then you return the minimum of those which is you return the minimum of those which is 15 so it just chooses the best choice 15 so it just chooses the best choice that was a walk through sorry if it was that was a walk through sorry if it was kind of shaky and you can look through a kind of shaky and you can look through a walk through of this too if you want to walk through of this too if you want to just check it out sorry for making the just check it out sorry for making the video so long I just assume people want video so long I just assume people want to know how like this stuff works so to know how like this stuff works so your current step is one at the end then your current step is one at the end then it's zero step two get set to the it's zero step two get set to the current step which is one then it's 101 current step which is one then it's 101 yeah so I'm not gonna walk this one's yeah so I'm not gonna walk this one's too long but let me know what you guys too long but let me know what you guys think let me know what you guys think think let me know what you guys think about this let me know if you have any about this let me know if you have any questions pretty straightforward link to questions pretty straightforward link to the problems in the description thanks the problems in the description thanks for watching see you guys next time | 2024-03-21 12:19:33 | 746 | LeetCode Min Cost Climbing Stairs Solution Explained - Java |
|
t-_RGOYZ9lw | today we are going to solve a question called as binary tree tilt called as binary tree tilt we are given with the root of a binary we are given with the root of a binary tree and we need to return the sum of tree and we need to return the sum of every tree nodes tilt every tree nodes tilt and your question could naturally be and your question could naturally be what is a tilt yeah what is a tilt yeah so let us see the tilt of a tree node is the absolute difference between the sum of all left sub 3 node values and all right subtree node values if a node does not have a left child then the sum of all the left child of the left child left subtree node would be treated as zero the rule is similar if there are node if the node does not have right child so in this tree's case the tilt of this node is 0 tilt of this node is 0 delta of this node is 1 and then finally we add 1 0 and 0 to give 1 as the final answer let us understand this with help of another so the tree that we are given with is 4 so the tree that we are given with is 4 2 2 9 9 3 3 5 5 and 7. um this is your tree so tilt tree first and then once the treated tree tilt tree is built then we'll add all the elements of this tilt tree and that will be our answer so let us see how to go with that i am going to first start with the leaves and then we will go slightly uh one step further up right so what about three three stilt is going to be zero because it doesn't have left node it doesn't have right nodes so zero minus zero is going to be zero and once uh the tree tilt is decided it returns the total value of the subtree itself so what is the total value of this subtree it is 3 so it returns back 3 what about 5 5 doesn't have any left node or right node so this is also going to be 0 so it is 0 and then it also returns back 5. now we go to this particular node so for this note the return value was 3 and the return value was 5 from the right 3 minus 5 is going to be -2 and we take absolute value of this returned integer return term and minus 2 is going to be then what is the total value of then what is the total value of this segment 3 plus 2 plus 5 and that is this segment 3 plus 2 plus 5 and that is 10 10 so this returns 10. so this returns 10. and we reach root node and we reach root node now let's take care of the right subtree now let's take care of the right subtree so let's start with 7 so let's start with 7 7 7 doesn't have left side or right child so doesn't have left side or right child so it is also going to be 0 it is also going to be 0 and then it returns 7 that is the total and then it returns 7 that is the total of the subtree of the subtree we go to this node we go to this node and here as well and here as well uh uh there is no left side so that is going there is no left side so that is going to be 0 to be 0 and 0 minus the returned value so 0 and 0 minus the returned value so 0 minus 7 is minus 7 and we take the minus 7 is minus 7 and we take the absolute value so it becomes 7 here we absolute value so it becomes 7 here we write 7 write 7 then then it returns the total value it returns the total value so total will be calculated as 7 so total will be calculated as 7 7 from here 7 from here return value from here was 0 so 0 plus 7 return value from here was 0 so 0 plus 7 plus the value of the plus the value of the node itself that is 9 node itself that is 9 so 9 plus 7 so 9 plus 7 is going to be 16. so 16 is returned from here and then we finally reach root node 10 from left 16 from right so 10 minus 16 10 minus 16 is going to be minus 6 and we take absolute value so it becomes 6 here and then because we have already reached the root node we don't need to worry about 10 plus 16 plus 4 as the return so finally so finally this is the tilt tree that we have got this is the tilt tree that we have got and it is simple now we just need to and it is simple now we just need to add all the elements here so 6 plus 2 add all the elements here so 6 plus 2 plus 7 plus 0 plus 0 plus 0 plus 7 plus 0 plus 0 plus 0 and we get and we get 15 15 and that is our answer so so so i am going to do a dfs visit to i am going to do a dfs visit to calculate calculate calculate this total that we need to calculate this total that we need to return return so i will have a function with the name so i will have a function with the name dfs that will accept root dfs that will accept root and this will return this will return the total i'll take one variable our total which is a global variable here and this is the value that we'll finally be returning back so we call dfs with root and this function will internally calculate total update total in the end and then we'll return this is going to be recursive function this is going to be recursive function so let let us take care of the so let let us take care of the termination condition first termination condition first so if there is no root so if there is no root then just return 0 and we don't need to then just return 0 and we don't need to touch total because it is 0 by default touch total because it is 0 by default then what happens we go to then what happens we go to left side left side so left is going to be so left is going to be dfs of root dfs of root dot left dot left then we go to right side so that is then we go to right side so that is going to be dfs of root dot right going to be dfs of root dot right now now i'm reminding you i'm reminding you the the the return value was always the total of the return value was always the total of the tree the total of the subtree the tree the total of the subtree so total of the subtree is going to be so total of the subtree is going to be left plus right plus left plus right plus root dot value root dot value while the thing that we need to while the thing that we need to calculate and we need to return is the calculate and we need to return is the total of tilt total of tilt so let us see what is going to be the so let us see what is going to be the tilt of this node and the tilt of this tilt of this node and the tilt of this node is going to be left minus right and we take absolute value of it so math dot abs left minus right this is the tilt and then finally we return and then finally we return root dot value plus left plus right so total is done the return value is done that means everything is done let us see if it works it does for example cases yeah i think it is good and it is faster yeah i think it is good and it is faster than 100 than 100 so i think we are we are doing great | 2024-03-20 11:35:43 | 563 | Binary Tree Tilt LeetCode 563 Solution using Depth First Search |
|
TK_BRa0CI3Q | welcome to august leeco challenge today's problem is add and search word today's problem is add and search word data structure design data structure design design is data structure that supports design is data structure that supports the following operations the following operations add word and search word search word can add word and search word search word can search search for a literal word or a regular for a literal word or a regular expression string containing letters a expression string containing letters a through z through z or period period means it represents any or period period means it represents any one letter one letter that's basically a wild card you see in that's basically a wild card you see in this example we add this example we add the words bad dad mad and we can search the words bad dad mad and we can search for for period a d and that's going to return a period a d and that's going to return a true because true because we indeed see that word exists so we indeed see that word exists so this problem is an implementation of a this problem is an implementation of a tree we've seen this problem before tree we've seen this problem before there's many ways to implement one i'm there's many ways to implement one i'm going to use a nested dictionary going to use a nested dictionary but the big twist here is how do we get but the big twist here is how do we get this this wild card search to work notice that we wild card search to work notice that we can't add words with the wild card but can't add words with the wild card but we need to be able to search we need to be able to search for words with that so initially let's for words with that so initially let's start with start with initializing a dictionary we'll just initializing a dictionary we'll just call that d call that d and this is going to be our root and this is going to be our root dictionary for for our dictionary for for our tree like structure word dictionary tree like structure word dictionary now when we want to add a word we want now when we want to add a word we want to add basically each character of the to add basically each character of the word word into a nested dictionary right and into a nested dictionary right and basically one first first first see if basically one first first first see if this word exists this word exists if it does we're going to add each if it does we're going to add each character with the word character with the word into a nested dictionary and at the very into a nested dictionary and at the very end we have to mark it somehow to say end we have to mark it somehow to say this is the end of the word because this is the end of the word because otherwise we're not going to be able to otherwise we're not going to be able to know if know if this word is indeed inside of a this word is indeed inside of a dictionary or if it's just like the dictionary or if it's just like the starts with starts with part is working so first i'm going to part is working so first i'm going to initialize a initialize a current pointer pointing to the current pointer pointing to the dictionary that we're at and this starts dictionary that we're at and this starts with a root dictionary with a root dictionary now if the word now if the word does not exist inside of our word does not exist inside of our word dictionary dictionary then we want to add it and we'll write then we want to add it and we'll write this this search function later we'll say search function later we'll say for i in range of the length word for i in range of the length word we're going to um let's see add to we're going to um let's see add to our current pointer the character being the key of the dictionary and create a new dictionary that is we only want to do this if this word doesn't exist right so we should say if um not in cur not in cur then we'll set a new dictionary then we'll set a new dictionary otherwise we don't need to do that we otherwise we don't need to do that we just move on to the next pointer just move on to the next pointer we'll say current is going to be equal we'll say current is going to be equal to cur to cur word dot i now once we're at the end word dot i now once we're at the end here here we want to add some sort of key to we want to add some sort of key to indicate that this is the end indicate that this is the end right so what i'll do is just have right so what i'll do is just have this hashtag symbol be a marker it's this hashtag symbol be a marker it's going to be a key to mark the end of the going to be a key to mark the end of the word word so this will just point to an empty so this will just point to an empty dictionary but dictionary but that's going to be that's going to be that's going to be that's going to be what's going to help us know what's going to help us know if we are indeed at the end if we are indeed at the end all right so now the hard part now we all right so now the hard part now we want to write some sort of way to want to write some sort of way to search for the word and search for the word and the tricky part is getting that wild the tricky part is getting that wild card card part correct right and there's different part correct right and there's different ways you can do it ways you can do it um you could build a stack because once um you could build a stack because once we hit a wild card what we're going to we hit a wild card what we're going to have to do is search for have to do is search for every word that's inside that dictionary every word that's inside that dictionary so we could build a stack to do that or so we could build a stack to do that or we could do something recursively we could do something recursively i'm just going to go with a recursive i'm just going to go with a recursive approach approach start with initializing the current start with initializing the current pointer to our root dictionary pointer to our root dictionary and what we do we want to do well let's and what we do we want to do well let's write a write a helper method that's going to be our helper method that's going to be our recursive method recursive method and we want to pass in the starting and we want to pass in the starting index the index number where we're at index the index number where we're at as well as the current dictionary that as well as the current dictionary that we're pointing at so there's going to be some base condition that's going to return true we'll come back to that in a bit let's first think about what possible things could happen here well the first thing that might happen is that this is a period so if it's a period we have to search through every single um you know diction dictionary inside of our current dictionary okay so to do that we'll say if word start is equal to period let's do a for loop and say all right all the dictionaries we'll do key value all the dictionaries we'll do key value in current dot items we'll recursively call start plus one and pass in the dictionary which would be value now the trick is we want to return a billion right so what we'll do is say all right if at any point in this loop we return a true here then we return to true otherwise we get through this whole loop then we can just return false now there's other things that can happen might just be a regular character and so might just be a regular character and so all we'll do is check to see if that's all we'll do is check to see if that's inside of our inside of our current dictionary and if it is then current dictionary and if it is then we'll just do the same thing here we'll just do the same thing here we'll say uh if recursive method start plus one and pass in the um current word start [Applause] and if that's true then we turn a true otherwise we've found the point that it does not have anything there so we just return a false all right so now we have to go back to our base condition so what would reach the end of our search well basically since we're passing the start if the start is greater or equal to the length of the word then we've reached the end of the word right so that's the point that we know yeah this word exists but keep in mind we need to remember to check to see if this hashtag exists inside of our current pointer because otherwise say that we added the word dog and now we're searching for the word do it's going to return a true if we don't check for this end word symbol so to do that i'm just going to keep it simple and say all right if the start is greater or equal to the length of the word now check if hashtag in current then return true otherwise we've found that this word starts with inside of our dictionary but it doesn't reach the end of the word so we return false all right so finally we want to return our recursive function and just pass in the zero index as well as the current so let's submit that see if it works so let's submit that see if it works no no no false true true true no no no false true true true it looks like it works let's go and it looks like it works let's go and submit that and accept it so like i said before there's different approaches i saw that some people prefer to use a stack some people used a tree node object instead but the basic you know logic is still the same we're going to have to do a for loop for check every single item if it's a period otherwise we just go down the right the normal path like we would do for a normal tree all right so that's it thanks for watching my channel really appreciate it and remember do not | 2024-03-22 10:28:13 | 211 | Leetcode - Add and Search Word - Data structure design (Python) |
|
U4fIp3lTq10 | hello everyone welcome to coding chance in today's video we are going to be in today's video we are going to be solving the problem maximum ice bars solving the problem maximum ice bars let's start by reading the problem let's start by reading the problem statement it says sweltering summer day statement it says sweltering summer day and a boy wants to buy some ice cream and a boy wants to buy some ice cream bars at this store there are n ice cream bars at this store there are n ice cream bars you are given an array of cost of bars you are given an array of cost of length n where cost of I is price of the length n where cost of I is price of the ith ice cream bar the boy initially has ith ice cream bar the boy initially has coins to spend and he wants to buy as coins to spend and he wants to buy as many ice cream bars as possible return many ice cream bars as possible return the maximum number of ice cream bars the the maximum number of ice cream bars the boy can buy with the coins boy can buy with the coins so the bike and the boy can buy the ice so the bike and the boy can buy the ice cream bars in any order cream bars in any order okay so in the first glance this looks okay so in the first glance this looks like kind of a DP problem like coin like kind of a DP problem like coin change but it actually seems greedy change but it actually seems greedy because we because we we want the boy wants to buy as many ice we want the boy wants to buy as many ice cream cream ice cream bars as possible so what is the greedy strategy up we can apply here is a buying bars with least cost so we can buy ice cream bars with the least cost and um buy more of them so how to um get the least ice cream bars we can actually become smart we can apply sorting and we can sort the cost array then we will get the cost in ascending ascending order and then we can um take the ice cream bars until we are out of coins so let's see let's code it up so firstly we have to sort the ice cream bars for that we do array start sort cost now that we have sorted let's iterate over the ice creams costs of length we also have to keep track of how how many ice creams we have got how much cost how much cost we have spent so far yeah so we keep track of running cost and each time oh we check first if yarning Cost Less current cost of the ice cream bar is greater than the coins we have then we know we cannot buy the ice cream bar because we are out of coins so we return um Ace we um Ace we add the current ice cream bar add the current ice cream bar to the coins to the coins and finally if we are out of this Loop and finally if we are out of this Loop then how many ice cream bars we bought then how many ice cream bars we bought we bought all the ice cream bars so we we bought all the ice cream bars so we can length can length we can return cost dot length so this gets accepted for the sample test this gets accepted for the sample test cases let us submit it it got accepted so what will be the time complexity of this approach as we are using sorting this will be pause any log n time complexity and this Loop runs in a little slow transition of n time complexity so the maximum is off and login so the time complexity of the solution will be of n log n and the space complexity as we are not using any external space if we ignore the space in the Sorting then the space complexity will be was one so I hope you understood the solution to the problem for more daily videos to subscribe to the YouTube channel and like this video if you understood the | 2024-03-22 18:23:41 | 1,833 | 1833. Maximum Ice Cream Bars #leetcode #greedy |
|
XdgS7eqwF2M | hey hey everybody this is larry this is me going over me going over the lead code weekly contest 243 problem the lead code weekly contest 243 problem one one check if word equals summation of two check if word equals summation of two words words so this one is actually pretty okay so this one is actually pretty okay um probably the users of the bunch um probably the users of the bunch uh which is why it's q1 but uh hit the uh which is why it's q1 but uh hit the like button like button subscribe whatever hit the subscribe subscribe whatever hit the subscribe button join me on discord button join me on discord and yeah and basically this one is just and yeah and basically this one is just implementation and translation it's just implementation and translation it's just for you to work for you to work uh for each word the three words you uh for each word the three words you want want you know some translation function from you know some translation function from the first word the first word plus the translation function of the plus the translation function of the second word is you go to the translation second word is you go to the translation function of the third word function of the third word and once you break it down like that um and once you break it down like that um you you kind of you you kind of for each character you just translate it for each character you just translate it to the number which is to the number which is um you know for each digit you shift it um you know for each digit you shift it by 10 and then you by 10 and then you get it from the delta from the value of get it from the delta from the value of a a and that's pretty much it this is linear and that's pretty much it this is linear time because for each character you do time because for each character you do one operation or one one operation or one over one operation and during the over one operation and during the contest this was the contest this was the useless part for me i got in 114 uh useless part for me i got in 114 uh actually pretty fast compared to other actually pretty fast compared to other people and that's my only bright spot so people and that's my only bright spot so that's why i'm that's why i'm bragging about it because after that it went downhill but yeah so this is linear time uh constant space let me know what you think um yeah and you can watch me solve it live during the contest next i'm sorry i don't know but all i'm still allergies okay a2j do um uh yeah so this was a rough contest and day for me so yeah uh hit the like button and hit the subscribe and show me some love uh and hopefully it will bounce back uh as i explain more problems but i hope y'all have a good good night have a good long weekend and i will see y'all later | 2024-03-25 11:49:25 | 1,880 | 1880. Check if Word Equals Summation of Two Words (Leetcode Easy) |
|
XbFzOlfDUUc | hey hey everybody this is larry this is dave dave one of the june nico daddy challenge hit one of the june nico daddy challenge hit the like button hit the subscribe button the like button hit the subscribe button join me on discord let me know what you join me on discord let me know what you think about today's prom how you doing think about today's prom how you doing uh just to give a quick update i was at uh just to give a quick update i was at the yankee game day one so go yanks no the yankee game day one so go yanks no more sports for until a little bit so more sports for until a little bit so we'll see anyway um yeah if you're if we'll see anyway um yeah if you're if this is your first day here uh welcome this is your first day here uh welcome welcome i have a 791 day streak though welcome i have a 791 day streak though you can't really see it maybe after we you can't really see it maybe after we solved this you could see it but so that solved this you could see it but so that means that we're going to be doing this means that we're going to be doing this all month so hit the like button hit the all month so hit the like button hit the subscribe button come on my discord and subscribe button come on my discord and hang out and and uh show us your code uh hang out and and uh show us your code uh do code reviews and we we we've been do code reviews and we we we've been pretty good about it doing uh sharing pretty good about it doing uh sharing our code there and and just kind of get our code there and and just kind of get comments though maybe not for today's comments though maybe not for today's because it seems to be a yeezy one um because it seems to be a yeezy one um but yeah just so yeah so we'll i mean but yeah just so yeah so we'll i mean like i said we have 791 days streak like i said we have 791 days streak going so we'll probably keep going until going so we'll probably keep going until as long as we can we'll see what happens as long as we can we'll see what happens but let's get started today's problem is but let's get started today's problem is 1480 running some of one d array 1480 running some of one d array given in a way sums uh yeah i mean this given in a way sums uh yeah i mean this is yeah i mean i wonder if there's a good one liner to do it but either way i think well before i say that uh i would say so prefix sum definitely something that you should definitely something that you should look up i wonder if this is going to be look up i wonder if this is going to be the theme for this week and i hope so the theme for this week and i hope so because prefix sum is something that is because prefix sum is something that is interesting and also um comes up interesting and also um comes up often um often um but i mean it's not necessary for this but i mean it's not necessary for this problem but it is just maybe a pre-rule problem but it is just maybe a pre-rule and if that's the case for the rest of and if that's the case for the rest of the week we'll go over the week we'll go over some of the concepts and solving and and some of the concepts and solving and and explanations and so forth so definitely explanations and so forth so definitely uh hang out and uh hang out and yeah come hit the subscribe button i yeah come hit the subscribe button i guess that's what i'm trying to say and guess that's what i'm trying to say and uh and solve it every day together uh uh and solve it every day together uh it's always good to serve with people it's always good to serve with people and friends and buddies but yeah baby and friends and buddies but yeah baby you know a core part of this is pretty you know a core part of this is pretty straightforward though so straightforward though so we can just we can just do it right um and do it right um and there's a couple ways to it all right uh there's a couple ways to it all right uh i would say i was gonna do something i would say i was gonna do something fancy with doing it in place but fancy with doing it in place but i think that's just you know it's fine i think that's just you know it's fine we don't need it that way but we don't need it that way but the way that i write it is just the way that i write it is just for for i and i and and you can you can write this in a and you can you can write this in a couple of ways i'm actually this is not couple of ways i'm actually this is not the way that i normally would write it the way that i normally would write it to be honest but i'm trying to write it to be honest but i'm trying to write it in a way that is as least confusing as in a way that is as least confusing as possible maybe but not with some like possible maybe but not with some like wrinkle about it right wrinkle about it right um um i'm surprised i'm surprised um um so yeah so that's basically it uh and we so yeah so that's basically it uh and we have to get rid of the prefix of zero have to get rid of the prefix of zero but the idea here is and this is how i but the idea here is and this is how i usually write the prefix sum for the usually write the prefix sum for the most part maybe not the way that i most part maybe not the way that i actually write it is for say x and nums actually write it is for say x and nums uh just to be a little bit uh maybe this uh just to be a little bit uh maybe this is a free option is a free option yeah so and i would oops yeah so and i would oops and let's just call it prefix right and let's just call it prefix right and sometimes you need the first and sometimes you need the first uh zero and sometimes you don't but uh zero and sometimes you don't but that's basically the way i write it that's basically the way i write it right for each number i add it to the right for each number i add it to the last number and it's kind of similar to last number and it's kind of similar to fibonacci except for only one number i fibonacci except for only one number i guess uh so you know but that's guess uh so you know but that's basically what we do and it comes up in basically what we do and it comes up in a lot of competitive programming maybe a lot of competitive programming maybe not so much on interviews to be honest not so much on interviews to be honest but but it is something oh man i i but but it is something oh man i i didn't fix that that's the easy facts didn't fix that that's the easy facts anyway i mean this is a easy problem so anyway i mean this is a easy problem so you you probably already have an idea of you you probably already have an idea of how to do it so this is how i would do how to do it so this is how i would do it uh you could use also accumulate i it uh you could use also accumulate i think uh as a python thing but i think think uh as a python thing but i think that's a little bit yeah keep it stupid that's a little bit yeah keep it stupid keep it simple that's the way that i keep it simple that's the way that i like to think about these problems like to think about these problems especially even on competitive and especially even on competitive and and um and um and on interviews right because and on interviews right because sometimes you try to be too clever with sometimes you try to be too clever with one liners and then one you have a type one liners and then one you have a type one you don't have to debug it because one you don't have to debug it because there's one line so you can't add a there's one line so you can't add a debug thing debug thing easily easily and then two is that and then two is that uh for the most part uh for the most part if if you're cleverness means making the if if you're cleverness means making the code a little bit shorter and maybe a code a little bit shorter and maybe a little bit harder to read that's not little bit harder to read that's not actually a plus even though i think this actually a plus even though i think this is one of those newbie traps uh if you is one of those newbie traps uh if you ask me ask me where someone think like okay yeah as where someone think like okay yeah as few characters as possible makes it like few characters as possible makes it like really cool and smart and called clever really cool and smart and called clever but but and that's why i call it a newbie trap and that's why i call it a newbie trap is because as an experienced engineer is because as an experienced engineer part of your software engineer part of your software engineer description is working with other people description is working with other people and some of that working a lot of and some of that working a lot of you know writing code that is you know writing code that is understandable without much thought or understandable without much thought or as little done as possible right like i as little done as possible right like i don't have to figure out what someone's don't have to figure out what someone's doing i just look and go like oh yeah i doing i just look and go like oh yeah i would have win it more or less the same would have win it more or less the same way in any case so way in any case so don't fall into that trap that's one and don't fall into that trap that's one and also uh it's also uh it's so the upside is not that much you maybe so the upside is not that much you maybe look a little bit clever too look a little bit clever too some certain people who may find it some certain people who may find it clever but two is that when you do mess clever but two is that when you do mess up if you have a typo you're gonna look up if you have a typo you're gonna look like in yeah you're not you're gonna like in yeah you're not you're gonna look like like why did they try to do look like like why did they try to do something to silly and then and didn't something to silly and then and didn't even succeed right so even succeed right so anyway those are trade-offs i leave up anyway those are trade-offs i leave up to you um i'm only talking about that to you um i'm only talking about that because you know this is a pretty because you know this is a pretty uh did i weigh someone no that's uh yeah uh did i weigh someone no that's uh yeah 792 days yeah i only talk about that 792 days yeah i only talk about that because this is not um because this is not um this is pretty silly as a you know i this is pretty silly as a you know i mean this is just a full event they tell mean this is just a full event they tell you exactly what to do right um but that you exactly what to do right um but that way you know well um if it's prefix some way you know well um if it's prefix some week we'll talk about it more if not week we'll talk about it more if not that's fine anyway that's all i have for that's fine anyway that's all i have for today though uh we'll we'll keep doing today though uh we'll we'll keep doing it for the rest of the month so let's do it for the rest of the month so let's do it together let's hang out i'll see you it together let's hang out i'll see you later um stay good stay healthy to good later um stay good stay healthy to good mental health mental health uh see you later bye-bye | 2024-03-21 03:03:55 | 1,480 | 1480. Running Sum of 1d Array - Day 1/30 Leetcode June Challenge |
|
T5zYVDnC8oU | it could question 473 match sticks to square 473 match sticks to square uh first thing i have never seen this uh first thing i have never seen this question so question so it's gonna be like a real interview kind it's gonna be like a real interview kind of a of a video so let's see you are given an video so let's see you are given an integer array matchsticks where mastics integer array matchsticks where mastics of i is length of eighth matchstick of i is length of eighth matchstick you want to use all matchsticks to make you want to use all matchsticks to make a square a square you should not break any stick but you you should not break any stick but you can link can link them up them up and each mastic and each mastic must be used exactly one time must be used exactly one time return true return true if you can make this square written if you can make this square written false false otherwise uh otherwise uh from the description it's kind of a easy from the description it's kind of a easy to understand question so we have given a mastics and we have to make a square out of it so before going into an algorithm let's uh let let me write down few things so what is going to be the input uh it's going to be array right uh matchsticks uh okay and is there anything uh no so okay what's what's the output boolean true true if if square square if you can make a square out of it right if you can make a square out of it right okay so okay so uh uh inputs are easy and inputs are easy and i can work with that i can work with that that's fine that's fine uh let's uh let's let me understand few things so let me understand few things so um area of size um area of size what what i i believe it it's not going to be i i believe it it's not going to be empty right uh empty right uh no at least there will be no at least there will be one one mastic mastic okay so one and uh do you think okay so one and uh do you think there is a limit to matchsticks or there is a limit to matchsticks or anything or i don't have to worry about anything or i don't have to worry about it it uh uh okay uh okay uh [Music] [Music] let's see let's see you can you can have up to 15 you can you can have up to 15 matchsticks at max matchsticks at max so 1 to 15 okay fine fine so 1 to 15 okay fine fine and and the values in the mastics are right the values in the mastics are right as as it's a length it cannot be negative and it's a length it cannot be negative and it cannot be zero uh is that assumption it cannot be zero uh is that assumption fair yeah that's that's fair assumption okay uh it's can be one and it can go up to 10 raised to 8 but yeah this interval will not say this he will obviously say like you don't worry about the yes let's assume it's it's fine or something like that okay and uh one more thing i would like to ask it's not zero it cannot be negative it can have duplicates i'm assuming that as well interval yeah yeah it's fine fine assumption good um okay now i would like to have some basic um check checklist like so that i don't forget a few things is which is edge or test cases which is edge or test cases then then i'm gonna do and i'll go design i'm gonna do and i'll go design i i like to code it like to code it and i'll talk about time and space and i'll talk about time and space complexity yeah so coming let's go through one example uh this let's go through one example uh this give an example give an example matchsticks one one two two matchsticks one one two two two so there are five matchsticks two so there are five matchsticks i have to make a square so yeah from this example i can see that we have four sides right for the square and there are and there are two ones two ones so i can use that so i can use that and it becomes and it becomes these two as a one and these three so it these two as a one and these three so it can be made as square can be made as square you can form okay understand you can form okay understand uh let's say three three three three uh let's say three three three three and four okay so so so few things i'm noticing here is that to make it a square exactly divisible by 4 divisible by 4 is that is that right is that is that right so let's see in this example if the so let's see in this example if the total is 8 total is 8 divided by divided by 4 is 4 is is not fraction so it gives you is not fraction so it gives you two two in this example it's in this example it's three fours at 12 plus uh 9 12 okay so that will give you four but based on this you cannot make a square because you cannot break this into four because you cannot break this into four different different uh uh mastics mastics if if you had ability to break this if if you had ability to break this i am sure you can just i am sure you can just do this and sum this and divide by four do this and sum this and divide by four and and if it is zero then you can mod by four if it is zero then you can mod by four and zero you can return and zero you can return but not in this case so but not in this case so i think there is a similar kind of a i think there is a similar kind of a logic that can be used logic that can be used somewhere let's say let's say in this example we had in this example we had four right and and the maximum so so [Music] um [Music] no um yeah is there anything else that can be done whatever the sum is whatever the sum is of total of total divided by 4 divided by 4 this value has to be size this value has to be size it cannot be less than this it cannot be it cannot be less than this it cannot be more than this more than this that's one thing so i have to make sure that so i have to make sure that i can i can make all the equal to this size there there is a complicated solution in my mind like a brute force solution try to try to make make try to make a side equal to this this value so yeah uh let me think something else if i can come come up so so here here there is there is also also the input is given in sorted order the input is given in sorted order does that make any sense does that make any sense can it [Music] [Music] but i i came across an edge case but i i came across an edge case that is that is if there are less than four we can return we can return false false directly directly right because you cannot make a score if right because you cannot make a score if there are less than four matchsticks there are less than four matchsticks let's say each case is fine let's say each case is fine uh if some mod if some mod 4 is a 1 or something is is not 0 it unfolds the question is now now it's uh the question is now now it's uh divisible by four divisible by four and we got a value so can i make four buckets uh something like this buckets buckets okay and then i trade through each element and i add it to bucket and i'm making it sorted so and i'm making it sorted so i'm going to fill this i'm going to fill this bucket uh to make it two so i add right and uh right and uh again i add one now this is two again i add one now this is two now i go to second bucket and i'm here now i go to second bucket and i'm here so add that so add that add add another another another another and the and and that that i have scanned through array and all the i have scanned through array and all the buckets are full up to this value buckets are full up to this value so in that case it's it's true so in that case it's it's true [Music] [Music] let's try this for this example so it's let's try this for this example so it's three and now i cannot add another three here so i can directly return false or i can um add this to next but how is that possible because everything is going to be above about above about um greater than three right so i can um greater than three right so i can return in that case directly from here return in that case directly from here let's let's take another example so uh let's let's take another example so uh let's assume it's let's assume it's example one two one two three three four and four four four and four four so what i'm trying to make is these four so what i'm trying to make is these four four four these two makes four these two makes four and this one and three mix and this one and three mix makes four makes four so now in that case um so now in that case um [Music] [Music] so uh i have to make four buckets of so uh i have to make four buckets of size four size four right right the sum will be sixteen here so eight the sum will be sixteen here so eight plus ten plus ten plus five plus one sixteen yeah plus five plus one sixteen yeah and uh and uh now i have four buckets now i have four buckets okay okay and i am going to i have sorted this and i am going to i have sorted this array array in ascending order in ascending order so i put one here then i put two here so i put one here then i put two here now i cannot put another two here so in now i cannot put another two here so in that case the previous algorithm will that case the previous algorithm will return false so return false so that's not gonna work okay how how should i make sure two here to here two here to here i add one i add one here one here here one here i have 4 here and i add 4 here so how can i make i there is one one solution that is coming to my mind it's it's kind of a brute force so so i try to fill each two to this maximum value two to this maximum value and if i never and if i never if i can never do it then so so i i think i should go with this approach i i think i should go with this approach because this is simple uh like because this is simple uh like easy easy thing that create four buckets and make thing that create four buckets and make make them make them feel in in in a way that feel in in in a way that in a way that in a way that it matches this it matches this uh upper limit of that bucket uh upper limit of that bucket right it has to exactly match that upper right it has to exactly match that upper limit limit so uh one thing that i can i can so uh one thing that i can i can try is get like it's a brute force approach where i get the of elements of elements up to this value up to this value target value target value right right and i i will do it for four four times and i i will do it for four four times four buckets four buckets and i will i will add those indexes to to scene scene set or something so that i don't use that that value again and uh uh yeah and at the end of this end of this iteration recursive iteration if all the buckets are full um i can if all the buckets are full um i can assume assume if all the buckets are full and if all the buckets are full and all the elements are all the elements are used used then that means we can we can make a square out of it so what i'm talking here let me write it uh uh so so what i was going to write down what i was going to write down yeah i i wanted to illustrate this this yeah i i wanted to illustrate this this flow right flow right so let's say i so let's say i i i have set i i have set bucket value to one okay and bucket value to one okay and i want to do it for four buckets i want to do it for four buckets and then i pass an empty bucket and i and then i pass an empty bucket and i pass the value of four pass the value of four now i add first element now i add first element and and i make this value as 3 and this same i make this value as 3 and this same bucket now my algorithm goes to find value [Music] that can make this as a 4 so it can add 2 and it adds 2 and it goes further now it cannot add 2 because it's greater than that so it comes back it pops this value it adds another two or maybe not two because i have already taken care of two right so i had three and then this this is done so first bucket is done now as i have added one and three to the scene so for second bucket what happens is i i started to i started one but it's seen so i do do nothing then i i get two i added two and i go further now next person or next iteration will add one value from this which is 2 which makes sense then then there is third bucket i go i add 4 there is third bucket i go i add 4 it's already 4 so it's already 4 so add four to the same add four to the same and for fourth bucket there is and for fourth bucket there is obviously i start from here these are obviously i start from here these are all seen so all seen so nothing happens i add the fourth index nothing happens i add the fourth index value value and yeah so we should they should solve and yeah so we should they should solve the the solver problem solver problem and in at any case if i cannot do this and in at any case if i cannot do this at any state at any state right right let's see i start first bucket let's see i start first bucket um for this example i started three and i cannot add i i keep adding i add three and i add another three i entered i popped this i had another three i popped this i ended three of this i had four i i cannot do for first bucket so there is no point in finding another three buckets so if at any point even one bucket cannot be done that's it um on on a on on a time complexity level it's going to be time complexity level it's going to be some exponential in in in a way and you can see that um you only have 15 matchsticks so i think this assumption is right so off um okay i am not sure but maybe something like 2 raised to n time complexity not sure i i will come back to it after code maybe and space maybe o o of n but this is a rough maybe o o of n but this is a rough estimate once i write code i can estimate once i write code i can come back to time and come back to time and space okay space okay so let's try to so let's try to let me try to write code for this i let me try to write code for this i don't know don't know um um so so i'm gonna make i'm going to write these base cases first let's take let's take n is equal to n is equal to the length of the length of matchsticks right and or some is is mod 4 mod 4 is not equal to 0 yeah so base cases are taken care of let me also have this like um and okay yeah yeah so required so required is equal to m sum that is how much each bucket is required that is how much each bucket is required and i should have and i should have four buckets four buckets to fill to fill will be this value which takes an index and um what it should take uh i i think i'm going to use scenes as i said and and i am also going to so overall complexity is going to be in so overall complexity is going to be in exponential so this won't matter that exponential so this won't matter that much it will just much it will just it will just find easier um it will just find easier um because there is going to be a case because there is going to be a case where if where if the value is going above required just and just don't don't don't go further and just don't don't don't go further adding it adding it yeah so that's yeah so that's that's gonna be helpful let's see so what is the base case let's say i'm i'm going to pass required as whatever the required value and if it is 0 then i i am i'm good that means this case is okay okay so in that case what should i do now there can be a case if required is now there can be a case if required is less than zero less than zero then we cannot go further so return then we cannot go further so return false so what happens if i can i be at that index anyhow i'm i'm going to uh i'm going to try till 30 30 minutes i'm going to try till 30 30 minutes and then i will check out the solution and then i will check out the solution but i i think this will but i i think this will this is right algorithm this is the this is right algorithm this is the right approach but i don't think i am right approach but i don't think i am able to code it like in able to code it like in and i don't want this video to be like and i don't want this video to be like like a long video like a long video so let's so let's and i'm i'm also not that confident that and i'm i'm also not that confident that my code is going to work i i'm confident my code is going to work i i'm confident that algorithm is right but that algorithm is right but code it's kind of a tricky thing here yeah so let's see what happens if i have already seen this yeah so if i in scene um just call helper i plus 1 i'm required our i is greater than our i is greater than or equal to n if required is not zero written true if i ever go beyond the so i'm going to do this i'm going to do this if i in scene if i in scene go to the next go to the next value okay okay and and if it is not in scene else do what uh uh maybe i will try to finish this on my maybe i will try to finish this on my own own let's see how it goes let's see how it goes um i'm not going to stop now i think i'm um i'm not going to stop now i think i'm on the right track on the right track so let's see result helper still go to y plus one match of i add scene dot add add scene dot add i i have added this i have added this and i've gone and i've gone and i can get result as true or false and i can get result as true or false so if i get true that means this so if i get true that means this addition was good enough addition was good enough and and i don't want to i don't want to [Music] [Music] um um use this this index use this this index another time another time so i should not pop it so i should not pop it so if result so if result is equal to equal to is equal to equal to false or let's say not result uh uh sim dot remove sim dot remove the index right right and from here return and from here return result now i think i have to call this helper function with same with same request value request value so for i in range so for i in range for uh [Music] [Music] zero comma zero comma required right but there is a case right if i can return false directly otherwise right so let's uh let's try run this once for example fastly go through it fastly go through it uh uh this is not false this is not false so this is so this is like like five so that's fine five so that's fine uh this is eight uh this is eight so this is so this is this is not false or this is not false this is not false or this is not false no don't return no don't return so m sum is eight more divided by four so m sum is eight more divided by four that is required is two that is required is two and matchsticks sort and matchsticks sort actually i'm going to take this example um i'm sorting right so uh let's let's just okay the sum is 16 divided by four okay the sum is 16 divided by four required is four um i sorted it so this required is four um i sorted it so this isn't sorted after scene is empty um set isn't sorted after scene is empty um set so now so now i start here for i in range four i start here for i in range four i call helper function i call helper function with with with index 0 with index 0 and required 4 okay so required is not zero it's not less than and this is also not true and and i in scene i in scene is not true so i go here scene dot is not true so i go here scene dot add i add i so now all right let's see nobody is all right let's see nobody is anyway here anyway here um um yeah so i have added this yeah so i have added this and i have called this function and i have called this function with i plus one so now my pointer is with i plus one so now my pointer is here okay okay uh let's go uh let's go so i come here again so i come here again this is um i have i have removed that this is um i have i have removed that value uh so now required is three value uh so now required is three right it's still not zero right it's still not zero so so i get i get this this um i come here um i come here i plus 1 i have done i plus 1 so it is i plus 1 i have done i plus 1 so it is still not in seen i add i plus 1 still not in seen i add i plus 1 which is 1. okay to check okay to check if all elements used used okay let's let's go um i have added what scene okay um then i i call this function again i plus okay okay i go here i go here now the pointer is pointing to this now the pointer is pointing to this value value i come here it's not in scene here it was three minus two here it was three minus two and now it's minus one and now it's minus one right right because i'm here i already minus three because i'm here i already minus three from it and i'm now minusing from it and i'm now minusing 2 so required is less than so i come 2 so required is less than so i come here yeah so this is not not a right yeah so this is not not a right right right way to code so what happen what is happening here is i came back from this this value it has given me false result so now this is false i remove this i have added two here as well so i remove this so so [Music] but where i am going how i am going so i think here i have to do like for i j in range i hd and this is j if not result uh uh if result is true let's see these are solutions i wanted to add two these are solutions i wanted to add two two three four two three four four let's work for this but it's not working let's work for this but it's not working for this okay uh if okay uh if length of scene i'm still not sure it's right solution but yeah it's not gonna work let's see the solution directly is the intuition dfs uh written false perimeter of square [Music] [Music] yeah this is like mod base case yeah this is like mod base case reverse sort okay this is something i reverse sort okay this is something i didn't do didn't do for this array represent the four sides for this array represent the four sides and their current lengths okay some so these are this is making buckets like what i'm doing zero okay and then for dfs uh okay sum sub zero one two is equal to equal the possible side yeah it's to rest when not tourist and yeah it's to rest when not tourist and it's four is doing ok there is a dynamic programming solution uh should i post this i i think i should post this at least um i i think i should post this at least um at least uh you you might anyone might at least uh you you might anyone might get some idea about get some idea about solving solving how to go about such questions so maybe maybe um the interviewer interview is like for 45 to one hour right minutes so i will make this video as a at max1r and and then let's see um i tried i will try to understand the solution if i can in that time i will post it uh in dynamic program what's important uh in dynamic program what's important is that our problem must be breakable is that our problem must be breakable into smaller sub problems and also these into smaller sub problems and also these sub problems show some sort of overlap sub problems show some sort of overlap which we can solve which we can solve we can save upon by caching we can save upon by caching memorization memorization suppose we have three four four five i suppose we have three four four five i adds our matchsticks that have been used adds our matchsticks that have been used already to construct some of the sides already to construct some of the sides of our square of our square but all the sides may be completely but all the sides may be completely constructed at all times constructed at all times if the square side is 8 then there if the square side is 8 then there are are many possibilities many possibilities for how the sides can be constructed for how the sides can be constructed using the mastic support using the mastic support we can have four four three five three we can have four four three five three five three sides fully constructed or three four three five four five zero or one side completely reconstructed or one side completely reconstructed as we can see above there are multiple as we can see above there are multiple ways to use same set of matchsticks and ways to use same set of matchsticks and land up completely different recursion land up completely different recursion states states this means that if we keep the track of this means that if we keep the track of what all matchsticks have been used and what all matchsticks have been used and which are remaining which are remaining it won't properly define the state of it won't properly define the state of recursion recursion okay okay a single set of use mastics can a single set of use mastics can represent multiple different unliterate represent multiple different unliterate sub problems and that is not right sub problems and that is not right we also need to keep track of number of we also need to keep track of number of sides of the square that have been sides of the square that have been completely formed till now completely formed till now also an important thing to note is in also an important thing to note is in this example we just considered was this example we just considered was with the mastic begin used with the mastic begin used r r and the side of square is eight then we will always consider that agreement from forms number of complete sides over the arrangement that leads to incomplete site since optimal with three complete sides of square with three complete sides of square uh let's uh let's take a look at the following recursion take a look at the following recursion tree to see if in fact we can tree to see if in fact we can get over lapping sub problem i'm still not understanding the solution not all sub problems have shown in the figure the thing we wanted to point out was all of lapping sub problem okay we know that the overall sum of these matchsticks can be split equal into four halves the only thing we don't know is if four equal halves can be carved out of given set of mastics for that also we need to keep track of number of sides completely formed at any point in time if we end up forming four equal sides successfully then naturally we would have used up all the matchsticks each being used exactly once and we could let us first look at the pseudo code for let us first look at the pseudo code for the problem before looking at the exact the problem before looking at the exact implementation in details implementation in details here this is something i found recurse here this is something i found recurse this is something i this is something i found slide formed is equal to equal to found slide formed is equal to equal to 4 then 4 then square form that's fine square form that's fine for match in matchsticks available do for match in matchsticks available do add matrix to the mastic used add matrix to the mastic used let let result uh request matrix formed if result uh request matrix formed if result is true then return true result is true then return true otherwise remove match from mastic used otherwise remove match from mastic used and return false and return false so basically they are doing it for true so basically they are doing it for true case i was doing it for false case okay case i was doing it for false case okay this is overall structure of our dynamic this is overall structure of our dynamic programming solution of course a lot of programming solution of course a lot of implementation details are missing here implementation details are missing here and and that we will address now oh come on man this big question if if value is less than 4 value is less than 4 value mod 4 is not equal to 0 value mod 4 is not equal to 0 edge is four okay edge is four okay i didn't do this what is l1 l12 reveal for if l2 is equal to equal l if l2 is equal to equal l to l1 l2 l3 equal equal to h return true to l1 l2 l3 equal equal to h return true otherwise if i is greater than lane so index is above so index is above the sorted array the sorted array written false written false if if any of this bucket is above otherwise this is kind of cool cool so what what i was doing is i was doing so what what i was doing is i was doing similar thing but i was add matchsticks one by one add matchsticks one by one bucket but what he's doing is bucket but what he's doing is he has all all four buckets he has all all four buckets and and um he's doing like caching uh sorry i don't know what how is this caching working his calling helper function his calling helper function by adding this matrix by adding this matrix to to to any of these to any of these values values so let's say it goes on this direction so let's say it goes on this direction if it return false it goes in this if it return false it goes in this direction it written false direction it written false it goes in this direction it falls and it goes in this direction it falls and if it goes in this direction it returns if it goes in this direction it returns false so yeah kind of a kind of trick here can i can i improve this solution [Music] can i code my solution in this way i don't think i have time i will add it here and okay sorry could not solve this question i failed this interview | 2024-03-22 15:21:50 | 473 | 473. Matchsticks to Square | Did not solve but came up with algo | Dont watch | Leetcode medium |
|
kbcucihgO_I | is lead code number 3 28 but pay attention to this thing, I will make it very easy, I will explain it so well, it is simple, there is not much to do, okay then look, I have asked the company Amazon and Microsoftness, If you have kept it then look at the input and If you have kept it then look at the input and If you have kept it then look at the input and output and understand what is the question, it will be fine, you have to rearrange it will be fine, you have to rearrange it and see how to rearrange it, this is the and see how to rearrange it, this is the first note, this is the second, this is the third, fourth S is set and the rest. fine but look at the ordering. fine but look at the ordering. First A came, B then came BN, so it should be from ordering. But first see what we did here, we aggregated all these ODs at one place If you have done cricket, then If you have done cricket, then If you have done cricket, then you have to rearrange it, it you have to rearrange it, it is okay, it is not too much, when you is okay, it is not too much, when you explain it, you will understand it very well, you explain it, you will understand it very well, you just have to listen carefully to how it is just have to listen carefully to how it is approached, you should know that approached, you should know that such questions should be solved from the beginning. such questions should be solved from the beginning. such questions should be solved from the beginning. we make it, that is, we will not come to a direct solution, we will have to think a little, after that we have to move ahead. Okay, so see, this was our example. Look, pay attention. In the example, ABC will not be given, numbers will be given. I have deliberately Don't you get confused? Don't you get confused? Don't you get confused? This is the first, this is the second, this is the third, this is the fourth, This is the first, this is the second, this is the third, this is the fourth, this is the fifth. Okay, let's this is the fifth. Okay, let's reduce one more. Whenever I have to draw, reduce one more. Whenever I have to draw, I make a box diagram of it. I make a box diagram of it. Remember, what is the link? Remember, what is the link? Remember, what is the link? is here and it is easier for me to make the next point. By the way, if you always make a box diagram like C, then is ABCD and every note has an address, so see it in the next section. so see it in the next section. so see it in the next section. right, this is CX, open it, then look, its next point is C, it is opening DX, its next point is DX, it is null, right, because it is pointing to null, okay, it is clear till now, so generally I I I always make a box diagram to prepare the queries of linked list. always make a box diagram to prepare the queries of linked list. Okay, and you must know Okay, and you must know that there is a head, this is our head which has the address of the first note, so the first Which one is it, what is its address? note. I am Which one is it, what is its address? smoking river for that and kept the and pointer and kept the and pointer okay so you see what we have done here is we have made OD equal to head na what is the value of head x is na so see Is and and look, pay attention to Is and and look, pay attention to Is and and look, pay attention to whom is And is whom is And is pointing to the next of Head, isn't Head Head say, That's That's why I make a drawing, it is very why I make a drawing, it is very easy for me to make it like this, it's ok, easy for me to make it like this, it's ok, order and so we have written it, now what we have to order and so we have written it, now what we have to do is that it should have been connected to it, but it is connected to it here, so we have to We will not break it like this, stop We will not break it like this, stop here, what did I say that this is an OD, this is an order, then let's point to it, okay, it has been done, then let's point to it, okay, it has been done, but how will it be done in the court, many more. many more. many more. made it by drawing that Han should point to this and K is equal to Next, so it is okay and K is equal to Next, so it is okay here, let's go into the code, okay, so let's here, let's go into the code, okay, so let's reduce it by one, I reduce it by one, I cut it and make it English. cut it and make it English. No, it will be clear, okay, let's I have to do DX, okay, so what will I do next [ I have to do DX, okay, so what will I do next [ Music] Music] Music] Whatever is next, its next, Whatever is next, its next, okay, so pay attention to what's next, okay, so pay attention to what's next, CX, and what will be next, CX, and what will be next, DX, so important. After that we have converted it into code. Okay, what I had to do was to point to the fourth one, that is, let's make it from this. Then again I have to connect this to this. I first connected it, okay, it's done, okay, it's done, now pay attention that this is shorted out, it has to be changed, okay, so I changed, okay, so I go to CX and DX, right? I C write C No, and we should have changed this DX, at the same time, this happened, you are looking at the DX, it is reducing the correctness, as we are writing the code, it is reducing the correctness, now look and here we go to the Hey, the fourth one is Hey, the fourth one is Hey, the fourth one is absolutely correct, the third one is mine and the absolutely correct, the third one is mine and the note is mine, the fourth one is mine and the note is here. Now let's tell the story again. Okay, let's tell the story again. See what Should have been Should have been Should have been pointed, let's get the point done, pointed, let's get the point done, then we will write in the code that it was done then we will write in the code that it was done and Ka is next to, and if the connection is X, then A should have been adopted to What will happen and is the connection ok? I got help from the line. What did I do It It is here later, it is okay, what is it, after making the drawing, after writing the code, the drawing, after writing the code, the next connection of and is, what is the next connection of this, what is the next of this, it is the tap, that is, the tap is here, it is okay The one that was there, I have cut it, so let's The one that was there, I have cut it, so let's The one that was there, I have cut it, so let's remove it here, okay, till now it is clear, the drawing okay, till now it is clear, the drawing made, converted it into code, okay, made, converted it into code, okay, now what was the next line, brother, let now what was the next line, brother, let Ode move forward and Ode move forward and Ode move forward and Okay, so look, pay attention where OD will go and here A will go here, here is the next order, so the order had changed, we had made changed, we had made changed, we had made and A will go out here and A will go out Okay so our loop will end Okay we have to run the loop until and is null So we will go out now So now notice we have done See, should See, should See, should I limit Green to Green, I limit Green to Green, not to Blue, or do something else? not to Blue, or do something else? connected to C? When it comes out of the loop, it is pointing to the tap right Okay, let's go, Okay, let's go, Okay, let's go, no problem, let's pay attention to this now, let's no problem, let's pay attention to this now, let's see, the di is pointing to the tap, okay, so if we see, what have we done ACI and see, the di is pointing to the tap, okay, so if we see, what have we done ACI and B went to the di and B and And DI has been collected And DI has been collected And DI has been collected and DI is pointing to my tap, is and DI is pointing to my tap, is n't it? And IB is pointing to my tap, n't it? And IB is pointing to my tap, so now so now we have played cricket separately for both of them, the odd ones have become hard and the odd ones have become tough. we have played cricket separately for both of them, the odd ones have become hard and the odd ones have become tough. we have played cricket separately for both of them, the odd ones have become hard and the odd ones have become tough. pits, but we have to connect, we have to connect, so look, what is the name of I, look, now OD is pointing to OD, which is I, it is fine, that is, what will happen in the last, The OD pointer, which is obvious, will be pointing to the The OD pointer, which is obvious, will be pointing to the The OD pointer, which is obvious, will be pointing to the last note pointer of the OD link list. Okay, here, so I will not do anything, what will I do and what do I have to do, so what will what will we do and so what will we do and so just don't do anything here, let's just don't do anything here, let's sign the and start here, our [ __ ] is done, okay, our [ __ ] is already done, everything is a perfect match [Music] How long is it going to run How long is it going to run How long is it going to run until whatever is there comes out, just convert what I will say now, from what I have just said, I will say the same thing while writing the code, okay, it will convert the story, okay, so let's If we take it, then the If we take it, then the If we take it, then the question is the same simple, you have to question is the same simple, you have to cricket the order and the number separately, cricket the order and the number separately, okay, you have to connect it later and send it, like if okay, you have to connect it later and send it, like if you were three four five, then look, give 135, it you were three four five, then look, give 135, it is 24, then the order and number have been completed. is 24, then the order and number have been completed. Okay, let Okay, let me tell you the story again that we have to me tell you the story again that we have to order and smoke cigarettes, this is what we have to do, neither will we order and smoke cigarettes, this is what we have to do, neither will we take anything, and it take anything, and it is okay to point to and, after that we will cricket them separately and connect the ODs separately. connect the ODs separately. connect the ODs separately. last we will connect more and and. so let's do as you say. Okay, we will What was said in the last that What was said in the last that we will store the next part of the head. we will store the next part of the head. Because in the last we have to connect, Because in the last we have to connect, right, the order of and, so the and will be its own right, the order of and, so the and will be its own separate cricket, the odd will be its own separate cricket, separate cricket, the odd will be its own separate cricket, but the odd but the odd point, point, which will be the segregated part, will be the last k which will be the segregated part, will be the last k point of it, okay. point of it, okay. point of it, okay. what we will do is to connect the next of OD to and that is ok so look at the starting point of and ka what is the head dot next then store it here connect the starting of and ka to it and starts is connect the starting of and ka to it and starts is ok. ok. ok. go on till the and is not equal, you become null, what did I say that OD's what did I say that OD's next, what did I say, that and next, what did I say, that and connection will happen, that and's next will be next, okay, [Music] [Music] Hum Maximum Hum Maximum Hum Maximum running but look here, this means that we do not want the next tap of the event, even if by mistake the next tap of the event is done, then this code will neither be fat nor can it be fat, if the airport is there, then the next video of the answer key van. Right, that null should not be there, so that I can see that no in the loop of the link list, maximum that I can see that no in the loop of the link list, maximum to what extent, if I to what extent, if I want to make it disappear, then the next of and want to make it disappear, then the next of and should be at least North null, only then only. should be at least North null, only then only. should be at least North null, only then only. in the next one, okay, then I set the condition here accordingly, okay, it is not that you already know the condition, okay if it is so good, okay, many people are able to do it, but I generally do this I write this, I write this, I write this, I write the condition according to that, okay, this is done, I write the condition according to that, okay, this is done, then what did I say then what did I say that the OD guy is doing like the oven music] is here, so what I will do this and I will I will do this and I will I will do this and I will connect three to and then I am doing the same in the last kiss which I have connected to E1 means and which I have connected to E1 means and next starting [ run it and see and the connection is where have we made the corner? where have we made the corner? where have we made the corner? grade is BF question, I try you help and I will repeat again, always make the questions of the link list in the diagram, in the boxed diagram, after that, nothing else, you have to write the story, code the story. ok optical in next video thank | 2024-03-24 10:34:38 | 328 | Odd Even Linked List - (Microsoft, Amazon) : Explanation ➕ Live Coding |
|
hUzF240K7y4 | hello and welcome to another video in this video we're going to be working on this video we're going to be working on our move duplicate letters our move duplicate letters so in this problem you're given a string so in this problem you're given a string s and you want to remove duplicate s and you want to remove duplicate letters such that every letter appears letters such that every letter appears once and only once and you want to make once and only once and you want to make sure your result is the smallest and sure your result is the smallest and lexicographical Order among all possible lexicographical Order among all possible results meaning it's just the smallest results meaning it's just the smallest and like alphabetical order so if you and like alphabetical order so if you have a bunch of outputs and you rank have a bunch of outputs and you rank them in terms of which one comes first them in terms of which one comes first in alphabetical order that's the one you in alphabetical order that's the one you would want would want so for b c a b c any time we have two so for b c a b c any time we have two letters we have a choice do we want the letters we have a choice do we want the first or the second letter so the best first or the second letter so the best possible result with all your letters is possible result with all your letters is a strictly increasing string so if you a strictly increasing string so if you can whatever letters you have this would can whatever letters you have this would be the best result with ABC it's be the best result with ABC it's strictly increasing right strictly increasing right it's essentially it's kind of like it's essentially it's kind of like numbers like let's say a bunch of numbers like let's say a bunch of combinations of one two three and you combinations of one two three and you have to use each one of these numbers have to use each one of these numbers once and they ask like what's the once and they ask like what's the smallest number well it's gonna be one smallest number well it's gonna be one two three right you want the leftmost two three right you want the leftmost number to be the smallest possible number to be the smallest possible because that's the most important number because that's the most important number it's similar for a string when you do it's similar for a string when you do string comparison the leftmost letter is string comparison the leftmost letter is the most important and that needs to be the most important and that needs to be the smallest possible so then we have c the smallest possible so then we have c b a c d c b c b a c d c b c uh and similarly here you would want the uh and similarly here you would want the leftmost letter to be as small as leftmost letter to be as small as possible so we're going to want to use possible so we're going to want to use this a and then what comes after well we this a and then what comes after well we can use a c wherever we want right but can use a c wherever we want right but do we have to use this D because it's do we have to use this D because it's the only D we have so this the this is the only D we have so this the this is the best thing here you can use some the best thing here you can use some other D's but essentially if you had other D's but essentially if you had instead of this if you had a d b c or instead of this if you had a d b c or any other one of those that would be any other one of those that would be worse right so because you have to use worse right so because you have to use this D this D you will either have ACD or ADC and then you will either have ACD or ADC and then a b and ACD is better a b and ACD is better okay so the first thing to recognize is okay so the first thing to recognize is the smallest lexicographical string is the smallest lexicographical string is actually you know the leftmost character actually you know the leftmost character needs to be the smallest and then it needs to be the smallest and then it needs to be like strictly increasing so needs to be like strictly increasing so ideally if you ideally if you have ABCD ideally if you ideally if you have ABCD you could do this this would be the best you could do this this would be the best possible case but this can't happen possible case but this can't happen because there's only one d right and the because there's only one d right and the a needs to come first so if they need to a needs to come first so if they need to come first you have to use like this come first you have to use like this part of the string somehow and so it part of the string somehow and so it would have to be a d uh CB so or actually would have to be sorry it would have to be acdb because there's only one D and you have to use it and you want the C to come first so now that you recognize in order to have the best possible string our characters need to be strictly increasing when you see that kind of thing it typically tells you you want to use a stack right either strictly increasing or strictly decreasing but the problem is for every character we have to know like can we delete it and is there a character later on and so there is a way to do that and so what we're going to do here let's just take this string as an example so we have CBA here it is here it is so what we really want is to know like so what we really want is to know like the last there's a couple ways to do the last there's a couple ways to do this you can either know the last this you can either know the last possible index of a character or how possible index of a character or how many you have left either one's fine so many you have left either one's fine so you can record how many you have left you can record how many you have left and then go care and then go letter by and then go care and then go letter by letter or you can just record the last letter or you can just record the last possible index of a character and it's possible index of a character and it's very easy to record the last possible very easy to record the last possible index of a character essentially all you index of a character essentially all you do is you should make a hash map and do is you should make a hash map and then you just so if we give these things then you just so if we give these things indices three four five six seven the way to know the last possible index is you can simply make a hash map and then you just override the value so you just go left to right and you store the letter and its value and for example for the cable store like c0 and then C3 and then C5 and then C7 so the last value would be C7 so for a there's only one location which is two for B there are two so first you would store the one then you would store the six it would overwrite it then for C there would be a seven right you would store the zero you'd sort of three the five and the seven so you just override it and then for D there's only one location which is force now that we have this hash map we and we need a stack we also need one more thing we need to be able to check if the letter is in our stack in oh one time now technically you don't really need a visited set because uh you can't actually just manually Loop through the stack if you wanted to because the stack can only be 26 letters so it's like constant time but we're just going to make a visited set because that's going to be a little bit faster so essentially we're gonna have a visited set and we are going to have a stack and I'm going to kind of show you the process behind this so let's just use another character so let's say we start the C we just go character by character so for the C our stack is empty so we're just going to put in the C right and we're going to add it to our visited set now we go to the B and basically we want a strictly increasing uh stack so for every character in here already we're trying to add a b but B is less than C so ideally we want to have B and then a c afterwards right like B and then a c is always going to be better than CB in increasing order so we need to track before we remove the C does the C actually exist somewhere down the road so we're over here so we're at index one so we need to check like where where's the last occurrence of c and it's at seven so we can see there is a c down the road so we can actually get rid of this C and just add the B and we add it to the visited set then we try to add a and we do the same thing we check for every letter before is the letter smaller well B is not smaller than a so ideally you'd want to have a then D but is there a b down the road yes there is there's a b index six so we can get rid of that as well now we add the a now we are at C and so here we can just add the C straight away because the letter before the C is a right so AC is totally fine that's strictly increasing totally fine okay now for D is the letter before uh D strictly increasing yes totally fine and we only have to check one letter because there's going to be two cases there's either going to be the whole thing is strictly increasing or you just can't get rid of the letter as I'll show you later on so once there's a letter you find that breaks the rule you don't have to check down like the rest of the stack you just have to check until you get rid of the letter okay and so now we are at the C then we check is the C in our stack already well C is already in our stack so if it's already in there we don't want to put it in again right we already have like the optimized stack here and so we're never going to want to add a c later on like you're always going to want to keep the one you had before so we can skip that one okay now for B so B is smaller than D so ideally we would want to get rid of D but can we we have to check what's the last index of D well last index of D is four and we're at six so there are no more D's so we can't get rid of the D we can have adbc because this would work right but essentially if you can't get rid of D you never want to get rid of C because this is already strictly increasing so if you got rid of the C then it would be a d b and this is better right so a d b c is worse than the solution right this is this is greater so essentially kind of you get to a letter that you either can't remove or that is uh smaller you would just want to stop there pretty much yeah so anytime you can't pop the last character you're never going to want to do anything again because we already have like the current optimized spring without this letter so we're never going to want to like change that so now what we're going to want to do is we're going to want to add the B and so I forgot we actually had this D in here already we're going to want to add the B and so now this is our answer now for the C we already have it so we don't want to put it in again so as you can see it's already here and so this would be our answer acdb so let's write down our cases for removing from a stack right and both of these have to happen has to be greater has to be greater than the letter we are adding than the letter we are adding and and another instance another instance of that letter of that letter at the end of the stack at the end of the stack has to exist further down right we can't has to exist further down right we can't get rid of a letter unless it exists get rid of a letter unless it exists further down because we have to have at further down because we have to have at least one of every letter but that's least one of every letter but that's pretty much it so to remind us of the pretty much it so to remind us of the steps we make a steps we make a hash map that is going to give us the hash map that is going to give us the last index of everything we keep a last index of everything we keep a visited set or you could like I said you visited set or you could like I said you could actually technically go through could actually technically go through your stack because your stack is going your stack because your stack is going to be maxed 26 letters to be maxed 26 letters and for every letter you're trying to and for every letter you're trying to put in you just make sure like hey if put in you just make sure like hey if the letters before it are worse can I the letters before it are worse can I get rid of them and can I add them later get rid of them and can I add them later on and if you can then do that and if on and if you can then do that and if one of them if the very last letter one of them if the very last letter can't you can't get rid of it then you can't you can't get rid of it then you just stop right there just stop right there and that's pretty much the code so like and that's pretty much the code so like the tricky part is figuring out this the tricky part is figuring out this like lexicographical order how to get it like lexicographical order how to get it but other than that it's it's pretty but other than that it's it's pretty straightforward to code so let's just straightforward to code so let's just code it code it so we're gonna have a stack so we're gonna have a stack and we are going to have a visited set and we are going to have a visited set so we'll call it uniques and we're going so we'll call it uniques and we're going to have this last index hash map or like to have this last index hash map or like I said you could have a count instead I said you could have a count instead and we're going to use a dictionary and we're going to use a dictionary comprehension here so we're going to say comprehension here so we're going to say it's going to be letter index it's going to be letter index oh yeah four uh index letter and oh yeah four uh index letter and enumerate enumerate s and essentially a numerate will give s and essentially a numerate will give you the index and the letter right so you the index and the letter right so that's what we want that's what we want now we are going to Loop through the now we are going to Loop through the string so for index sweater in enumerate string so for index sweater in enumerate s s if the character is already in there we if the character is already in there we can just skip it uh for some reason we have this there we go and now we just have to Loop through our stack so while stack and the character has to be less than the last item in the stack and the last item in the stack actually has to exist right well there has to be another index so I has to be less than the last index of Stack minus one so essentially this part is just saying like if we remove this character is it somewhere down the road or is this the last one so if that's the case then we can remove from the stack so we want to we want to pop and then we want to actually remove that from the visited set right so we pop and then we remove that letter from our uniques and then once we're done with that once we're done with cleaning up the stack then we want to add the current character we're on and we also want to add it to the stack and so finally now we have a stack of our entire word but it's going to be letter by letter in increasing order so now all we need to do is we need to just join the stack on a space right so it's going to be this dot join stack because essentially you know if our word is ABCD we're storing it like this for now so we need to actually return a string so let's see how that goes oh let's actually get rid of this so you can see the errors and there we go and there we go and you can see it's really efficient and you can see it's really efficient so let's talk about the time in space so let's talk about the time in space and like I said for a lot of these and like I said for a lot of these technically like if you didn't have this technically like if you didn't have this unique set it would still be fine unique set it would still be fine because our stack is only 26 characters because our stack is only 26 characters so you can really use the fact that you so you can really use the fact that you only have 26 characters to really add a only have 26 characters to really add a lot of like things because it's lot of like things because it's basically basically of one space of one space so let's think about what would happen so let's think about what would happen here so we are going through every here so we are going through every character here so that's o of n character here so that's o of n then we're going through every character then we're going through every character here again here again and now if you think about it the worst and now if you think about it the worst case scenario is we add everything to case scenario is we add everything to the stack once and then we remove it the stack once and then we remove it from the stack once right so we can only from the stack once right so we can only add things to the stack one time and we add things to the stack one time and we can only remove from stack one time so can only remove from stack one time so worst case this is like you know we add worst case this is like you know we add and remove from the stack which is 2 and remove from the stack which is 2 times n and so this is pretty much going times n and so this is pretty much going to run worst case 2 times n this is n so to run worst case 2 times n this is n so this is O of n time and for the space Oh like I said a lot of these things are very convenient because there are only 26 characters so this last index only 26 characters that's o of one um uniques only 26 characters of one so you can really abuse this like 26 character thing and make a lot of data structures that just use characters A through Z and that costs you nothing so uh yeah then for our actual stack also only 26 characters so 26 characters 26 characters 26 characters because they all have to be unique and then our result is maximum obviously 26 characters but we don't count the result so we're going to say this is o1 space because all of these are content space they are just 26 characters no matter how long their word is it could be a billion characters this will only be 26. and yeah so I think that's it for this problem hopefully you liked it and if you did please like the video and subscribe to the channel and I will see | 2024-03-24 10:21:41 | 316 | Remove Duplicate Letters - LeetCode 316 - Python |
|
0HN7tYz_Abc | hey what's up guys this is chung here so let's let's talk about this week's so let's let's talk about this week's weekly contest weekly contest number 1648 number 1648 self diminishing valued colored boss self diminishing valued colored boss all right so i this is a interesting all right so i this is a interesting i would say it's a math more like a math i would say it's a math more like a math problem problem okay so you have an inventory of okay so you have an inventory of different colored balls and there is different colored balls and there is like a customer that wants other boss of like a customer that wants other boss of any color any color okay and this customer they're like a okay and this customer they're like a bunch of descriptions here right bunch of descriptions here right basically you know basically you know the customer will really values the the customer will really values the colored balls each color both values the colored balls each color both values the number of balls that number of balls that that color you currently have in your that color you currently have in your inventory so which means that inventory so which means that if you currently have six six yellow if you currently have six six yellow balls balls okay and then okay and then and then the first time you sell you and then the first time you sell you sell the sell the the first yellow ball you you get six the first yellow ball you you get six you get six values and then the second you get six values and then the second time you get five time you get five and then four five three four three four and then four five three four three four five three two one and two five three two one and two until you sell everything okay and then until you sell everything okay and then you're given like an integer of arrays you're given like an integer of arrays and this inventory which where the and this inventory which where the inventory i represents the number of the inventory i represents the number of the boss boss okay of this color of the ice color okay of this color of the ice color and you're also given like an integer and you're also given like an integer order so the others is basically the order so the others is basically the total total the total number of bots the customer the total number of bots the customer wants to order wants to order and you can sell the box in any other and you can sell the box in any other and it asks you to return the maximum and it asks you to return the maximum total value total value that you can obtain after selling the that you can obtain after selling the others others since the the color the answer may be since the the color the answer may be too large return it too large return it return the modular of this one return the modular of this one so a few examples here right so for so a few examples here right so for first one first one let's say you you have two you have let's say you you have two you have two color one bars and you have you have two color one bars and you have you have five color two bars five color two bars and in total you need to sell in total and in total you need to sell in total you need to uh you need to sell four you need to uh you need to sell four balls in total balls in total so as you guys can see here so the first so as you guys can see here so the first time you you sell time you you sell five right you sell five four and three five right you sell five four and three until you reach until you reach so after selling five four three right so after selling five four three right after setting three balls after setting three balls now the two the two colors are now the two the two colors are have are having the same same number have are having the same same number same number of same number of of balls right which are both two that's of balls right which are both two that's why why the last thing you sell you can either the last thing you sell you can either sell uh sell uh the the color one or color to color two the the color one or color to color two so that's why in total you have 14 so that's why in total you have 14 14 balls okay and then here 14 balls okay and then here here's like a tricky example here here's like a tricky example here as you guys can see here you have a huge as you guys can see here you have a huge number of the number of the others and only one numbers others and only one numbers only one color box here only one color box here that's why you you i mean you still have that's why you you i mean you still have the answer here the answer here right so cool so and here you have like this uh constraints here right so for this problem you know so what's going to be the the the naive or brutal force uh brutal force uh approach right of course is by using the priority queue right basically every time basically we push it push all the the number of the box into the priority queue and every time when we are like decreasing the others here right we also we pick the the highest the highest number of the of the current colors right and then we decrease the number by by one and then we push it back to the priority queue and then we we just collect that value the cut that highest value to the final answer right that'll be the the not even brutal force way and as you as you guys can see that will definitely tle because the uh because the the inventory where the order with others is has the limits can be uh out up to 10 to the power of nine so if you are just simply using the priority queue and try to decrease the others one at a time you will definitely tle okay so we need to find out like a more efficient way of of decreasing or of selling the boss so what's going to be the the highest the i mean the more efficient way so basically you know i'll give you guys a few examples say we have a 10 say we have a 10 and then we have a of eight and then we have a of eight we have six and blah blah blah we have six and blah blah blah okay so in total let's see that in total okay so in total let's see that in total we have the boss of we have the boss of we want to sell 20s 20 in total so the way it works is that first we sort the the number of the inventories from from the biggest to the smallest and every time we're comparing we're comparing the current one with the next one if the current one is greater than the next one then we know okay we can sell we basically we can make uh nine sorry we can make two sales nine sorry we can make two sales basically from basically from 10 uh the first time we 10 uh the first time we we can sell uh we can sell uh we can sell uh we can sell uh sell the numbers of 10 right we can sell sell the numbers of 10 right we can sell we can make the cell from 10 to nine and we can make the cell from 10 to nine and then from nine to eight then from nine to eight so why we only we can only make two two so why we only we can only make two two cells because after the two sales cells because after the two sales right we'll have two colors right we'll have two colors which uh who is having the the same which uh who is having the the same numbers which means we have eight here numbers which means we have eight here eight eight right so i mean eight eight right so i mean after two sales if we want to continue after two sales if we want to continue to make the sales to make the sales we have to do the factor of two right so we have to do the factor out of factors is not equal to two because at factors is not equal to two because at the next time the next time when we sell the make another cell right when we sell the make another cell right let's say let's say we have 20 right so after two cells the we have 20 right so after two cells the others here right we have others here right we have others here uh we'll talk about how can others here uh we'll talk about how can we collect the uh we collect the uh how can we collect the the values uh by how can we collect the the values uh by setting the balls i'm i'm only talking setting the balls i'm i'm only talking about the about the the others here so the first time we the others here so the first time we have a have a we make two two sales right and then the we make two two sales right and then the others will become to others will become to 18 right 18 right so now the factors becomes two because so now the factors becomes two because like as you guys can see we have we have like as you guys can see we have we have two eight here two eight here so now from eight to six we we can so now from eight to six we we can we can again make two sales but this we can again make two sales but this time we have to do a two times two time we have to do a two times two two times this is this factor here which two times this is this factor here which means after two sales again means after two sales again uh basically we'll be selling four bars uh basically we'll be selling four bars in in total in in total right that's two plus two so that's why right that's two plus two so that's why after this two here after this two here we have like 18 will be comes to 14 we have like 18 will be comes to 14 right so let's say we have a two we have right so let's say we have a two we have four here four here okay so after after another okay so after after another uh two times two sales now both of this uh two times two sales now both of this 8 becomes 2 to 6 right so which means we 8 becomes 2 to 6 right so which means we have have we have 3 6 here right we have 3 6 here right which means every time we have like a which means every time we have like a different one we we see the different different one we we see the different numbers numbers we now factor equals to three we now factor equals to three right so when the factor is three it right so when the factor is three it means that from six to four means that from six to four again we can make two sales and every again we can make two sales and every time we can sell time we can sell we we can sell two times two times we we can sell two times two times three bars right which means uh three bars right which means uh it's gonna be uh gonna be it's gonna be uh gonna be become to eight right so we keep saying that until we have reached the uh uh basically you know as long as we can we can make the like you can think of oh as a wholesale as long as we can say we can sell everything that the current factor represents we we can just use the same logic right and then in the end when we reach a point that we cannot uh sell everything we have to do a little bit different for example here let's say we have a let's see we have 20 let's say we have 20 and all we have is what let's see we and all we have is what let's see we only only now the only boss we have is it's three now the only boss we have is it's three eight eight let's see we have 3 8 here it means that let's see we have 3 8 here it means that we have three colors we have three colors uh that which every each one has uh that which every each one has like eight balls left right so at this point how can we and there's nothing else left so how can we make the cell this uh this three box here as you guys can see so what we do we do a 12 divided by three so what does this mean it means that we can we can sell three balls all together right so six times and then right so six times and then after six times we cannot sell three all after six times we cannot sell three all three bots here three bots here which means we have like how many bars which means we have like how many bars left we have left we have 20 uh do a modular by three we have two 20 uh do a modular by three we have two so which means that the remaining two we so which means that the remaining two we can only sell can only sell two right so what does it means that you two right so what does it means that you know know from eight from eight uh from eight from eight uh to make three uh to make six wholesales to make three uh to make six wholesales what what does it mean it means that what what does it mean it means that we'll we'll sell eight plus seven plus six sell eight plus seven plus six plus five plus four plus plus five plus four plus three you know what actually i'll write three you know what actually i'll write everything here you know plus zero everything here you know plus zero so after making uh six wholesales so after making uh six wholesales where are we now we're at we are three where are we now we're at we are three here here that's the one two three four five six that's the one two three four five six right basically that's the uh right basically that's the uh that's the that's the values we can that's the that's the values we can collect by collect by making uh six three six wholesales making uh six three six wholesales so basically we collect this eight to so basically we collect this eight to three and we of course will three and we of course will we multiply by three in the end and how we multiply by three in the end and how about this two here about this two here right after three after six uh six right after three after six uh six wholesales wholesales this this eight will becomes two to two this this eight will becomes two to two and now we just need to make another two and now we just need to make another two uh two out the the last remaining two uh two out the the last remaining two others which means others which means that we'll have like this two that we'll have like this two times two because we will be uh out of times two because we will be uh out of these three these three twos here we'll make another twos here we'll make another we will make the last two sales that's we will make the last two sales that's why why we have this two times two in the end all right so that's the basic idea of how can we uh approach to the final answers and as you guys can see the another crucial uh part for this algorithm is how can we calculate from eight the the sum from eight to three right and so how can we calculate that because you know it's obviously no i think everyone knows how can we calculate from from eight to one right so so what's the what's the the formula for that right that's the n times n plus one divided by two right and how but but how can we calculate it from eight to three right it's pretty straightforward right and if we have the if if we have and if we have the if if we have everything from eight everything from eight to one and then all we need to do is we to one and then all we need to do is we just uh subtract just uh subtract that two to one and then we have eight that two to one and then we have eight to three to three right so which means that you know from right so which means that you know from n times n n times n plus one here right what do we we can plus one here right what do we we can simply do this we simply do this we we sorry we we subtract we sorry we we subtract the what the the k let's say this is k k times k k plus one let's say the k is k times k k plus one let's say the k is equal to two equal to two right so that's the basically the right so that's the basically the formula we will be needing to calculate formula we will be needing to calculate eight to three right yeah that's it okay so with that being said i think we can all right cool you know since we'll be all right cool you know since we'll be using that using that that get summary get some formula that get summary get some formula multiple times multiple times i'm going to uh extract it into a into a i'm going to uh extract it into a into a separate functions here you know separate functions here you know that's which will make this code much that's which will make this code much more readable more readable so i will have a start and end okay so so i will have a start and end okay so here here you know i simply return the start you know i simply return the start times uh start times uh start plus 1 and then divided by 2 minus plus 1 and then divided by 2 minus n times uh n times uh end and plus one end and plus one divided by by two okay so by starting by divided by by two okay so by starting by starting n i mean this right so we have starting n i mean this right so we have a eight eight seven six five four to one i mean by starting n i mean i'm trying to get the sum from let's say from eight to six so from eight to six then the at the start is eight and the end is five so n n is five this is the end this is start so keep in mind i'm the end is not six okay it's five all right so okay now we have to get some functions here that so let's try to sort this uh this inventory first you know since this this uh variable is kind of long i'll rename it to inventory to inv here so i'll do a inv dot sort okay and since i'm going to sort it from the uh from the a decent in the descending order i'll do a reverse equals to true okay and then the factor right the factor at the beginning is one so the factor means that you know how many uh colors right how many colors right and since we're sorting from the right and since we're sorting from the the biggest the biggest to the smallest and the factor will to the smallest and the factor will always be increasing right always be increasing right and okay we have n equals the length of and okay we have n equals the length of i and v i and v and then we have uh what uh we have i and then we have uh what uh we have i here here so the i will be the the so the i will be the the i will be the inventory where we are i will be the inventory where we are currently uh currently uh at right now and then we have our answer at right now and then we have our answer the final answer will be equal to zero the final answer will be equal to zero so the way i'm i'm doing the loop here so the way i'm i'm doing the loop here is is uh i'm doing this others here right so uh i'm doing this others here right so while the others is greater than zero while the others is greater than zero okay so when the order is equal to zero okay so when the order is equal to zero then we know that's when we need to then we know that's when we need to return return our our answer okay so the answer will our our answer okay so the answer will be uh be uh i'll finish the answer here you know so i'll finish the answer here you know so when you guys like when you guys like at the interview or like any uh or any at the interview or like any uh or any type type testing or any exam you know i think testing or any exam you know i think it's always a good habit it's always a good habit to uh to finish the to uh to finish the the main logic part like like this mod the main logic part like like this mod equals to the 10 to the power of nine equals to the 10 to the power of nine plus seven and then in the end you do plus seven and then in the end you do this you know this you know and then you implement the details and then you implement the details because otherwise you know what because otherwise you know what if the if you're in the detail if the if you're in the detail implementation it is pretty implementation it is pretty complicated and then you'll be forget complicated and then you'll be forget you'll be forgetting what you want you you'll be forgetting what you want you want to do in the end want to do in the end right so okay so now we have these right so okay so now we have these things here things here and okay like i said right so first and okay like i said right so first thing first thing first the the most the easiest the easiest the the most the easiest the easiest scenario is that we can make the scenario is that we can make the the whole cell with the current factor the whole cell with the current factor which means that we can simply which means that we can simply subtract that that that subtract that that that the difference from the others the difference from the others and if the i is smaller than n minus 1. so i do this check because i will be checking this one because i'm like i said i'm checking if the current one is is greater than the inventory of the i plus one i only do this uh decrease when when the uh when the current one is greater than the the the next one because if they are the same i'll just keep increase i'll keep moving the eyes forward uh most while increasing the factors here okay so here like the if we can make sale for all factor boss for our right so i'll i'll try to finish this right so i'll i'll try to finish this one later so else if one later so else if right else if what else if if we can not make sale for our fac factor right here we have al we have if the right if that's the case right what do we do we simply do that we simply do i i uh plus one and then we do a factor plot plus one that's the that's the last step right because you know if the current one and the next one is the same we don't do anything we simply uh we'll simply just uh increase the the the pointer and then we also increase the factor right because we are we have we're accumulating one more uh colors who is having the same amount so now the first one right if we if we so now the first one right if we if we can make the whole sale for all the can make the whole sale for all the other for other for all the factors right so it means that all the factors right so it means that first thing is that it's always the if first thing is that it's always the if the current one is greater the current one is greater than the then the net the next one and what and this right and what the others right is greater and what the others right is greater equal greater than what equal greater than what then the factor times what then the factor times what the inventory i the inventory i minus inventory i plus one minus inventory i plus one right so here i mean right so here i mean of course since we're going to check the of course since we're going to check the i plus one that's how that's why do i i plus one that's how that's why do i i i do this track here and the second i i do this track here and the second one is the uh if the time one is the uh if the time the the the con is different the the the con is different and we can make the whole sale we can and we can make the whole sale we can sell sell we can make the wholesale for for the we can make the wholesale for for the difference for all this factor difference for all this factor right and then we do what we do we right and then we do what we do we simply do answer right we simply simply do answer right we simply accumulate this answer with the the accumulate this answer with the the current factor current factor times times this times times this times the let's say from eight to six times the let's say from eight to six right so right so now so now now so now the inventory i is eight the inventory i is eight and even to i plus one is five in this and even to i plus one is five in this case so what's going to be the the values we can collect right so from eight to five we have what right so from eight to five we have what we have get some inventory i and then inventory i plus one okay all right so that's how we calculate the the values we can collect from selling this box from eight to five by selling the number of these factors right so that's why we have eight seven six okay and after this say after this sales the others becomes to what becomes a factor times times the difference right times all right cool so that's the this is the all right cool so that's the this is the the easy case which means we can sell the easy case which means we can sell we can make the sale for the for the for we can make the sale for the for the for a difference a difference for all the factors and the second one for all the factors and the second one is a little bit is a little bit uh complicated one which means that we uh complicated one which means that we can make the sale can make the sale but we cannot sell everything just but we cannot sell everything just remember remember when i said we have 20 20 balls 20 when i said we have 20 20 balls 20 others others left and then we have a 3 8 left left and then we have a 3 8 left so in this case we can only make six so in this case we can only make six whole sales whole sales and the remaining two will be and the remaining two will be calculated later so in this case we have calculated later so in this case we have and what do we have here again right again it's has to be like this we also but you know we also need to check okay but you know we also need to check okay so we can do this if i is so we can do this if i is in the n minus 1 or this in the n minus 1 or this okay so just for this case right let's say we have a 3 8 left here so whenever i is the same as um has re has reached the end of this array here we also need to do the calculation or again or the uh what is the inventory i is greater than inventory i plus one okay same thing so but at this time we cannot make the the sale for the for the whole factor here right so that's why we have to use what we have to uh i'm going to calculate sale all times here so how how can we calculate that we use this remaining others and then we do a we do division by by the uh by the factor right that's the numbers we we can sell first okay we do this vector do uh like the the double slash divide divide division here so we can get like an integer here and so for this one that's the how that's that's the the number of times we can sell right for for the for the whole factor here so and now let's calculate collect the values we can we'll get by doing that so again we have a factor right and then what we have a get sum right again we start from this inventory i right and what's going to be the the end the ending point for this for this time it's going to be inventor i divided i'm sorry miners sell all times so why is that right for example here so we have six here right so we can sell so now sell our six so which means that we can six five four three six five four three two one we sell two one we sell six times that's why the end six times that's why the end the ending point is two in this case the ending point is two in this case which is the which is the the in the inventory i eight minus the in the inventory i eight minus six is two okay six is two okay so that's that okay so how about so the so that's that okay so how about so the next thing is going to be the remaining next thing is going to be the remaining the remaining others right so what's the remaining others right so what's gonna what's the remaining others gonna what's the remaining others uh it's just the others uh do a modular uh it's just the others uh do a modular by the uh by the uh by by the factor which in this case is by by the factor which in this case is is two right so 20 divided uh dual is two right so 20 divided uh dual modeler by six is two which means we modeler by six is two which means we have have we still have two others we need to we we still have two others we need to we need to sell need to sell so now with those two orders right it's so now with those two orders right it's pretty pretty obvious that the it's going to be the obvious that the it's going to be the remaining others remaining others times what times the uh times this right times what times the uh times this right times this one because that's the uh times this one because that's the uh the numbers we'll be having here what the numbers we'll be having here what will be left here so will be left here so we have a three we have three twos left we have a three we have three twos left that's why we're gonna be uh that's why we're gonna be uh uh multiply by two here okay so uh multiply by two here okay so once this is done don't don't forget to once this is done don't don't forget to set these orders to zero set these orders to zero because uh by by this time you know because uh by by this time you know everything is zero or we can simply do a everything is zero or we can simply do a break you know break you know let's do it let's do break because we let's do it let's do break because we have cell we have sold everything cool so let's try to run the code here i cool so let's try to run the code here i think that think that should be everything didn't make any mistake here let's say didn't make any mistake here let's say let's see uh oh here i think i'm missing out like miners sign here okay run code all right cool so it's accepted all right cool so it's accepted so that's the uh that's the uh so that's the uh that's the uh basically the logic here and basically the logic here and for the time space and time complexity for the time space and time complexity right as you guys can see here we have right as you guys can see here we have we have stored here that's why we have we have stored here that's why we have unlocked in here right unlocked in here right and here here will be uh will it this one is bounded it's bounded with the number of the i here because every time we'll be increasing the eyes here and by the time we we have it reached the end the others will be zero or uh by the by that time so that's why here we have n here you know and in total the the time complexity here here yeah okay i think i'll stop here i think yeah okay i think i'll stop here i think that's that's that's it for this problem you know it's that's it for this problem you know it's this one is i think for me it's more this one is i think for me it's more like a math problem because like a math problem because math plus greedy you know math plus greedy you know as long as you guys can um to figure out as long as you guys can um to figure out how to calculate the range sum how to calculate the range sum you know and also the uh how can you how you know and also the uh how can you how can you like can you like use this factor to to d to determine use this factor to to d to determine like the uh like the uh how to uh do a a full a wholesale or how how to uh do a a full a wholesale or how can you can you do a partial sale and then do the do a partial sale and then do the remaining remaining you know this one is more like a you know this one is more like a implementation implementation heavy implementation implementation heavy problem plus problem plus some a little bit of math okay i hope some a little bit of math okay i hope you guys like this video you guys like this video alright thank you so much for for alright thank you so much for for watching this video guys stay tuned watching this video guys stay tuned uh see you guys soon bye | 2024-03-19 18:09:07 | 1,648 | LeetCode 1648. Sell Diminishing-Valued Colored Balls |
|
RJfqIYG5yXs | hey guys welcome back to our channel so this channel every data science is all this channel every data science is all about trying to learn the different about trying to learn the different concepts involved data science we're concepts involved data science we're practicing a lot of questions in this practicing a lot of questions in this video I am going to solve this question video I am going to solve this question on lead code regarding reformat on lead code regarding reformat Department triple and try to walk you Department triple and try to walk you through how we can develop solutions to through how we can develop solutions to such problems the difficulty level of such problems the difficulty level of this question is easy and this question this question is easy and this question has been asked in Amazon interviews over has been asked in Amazon interviews over the past six months a couple of times the past six months a couple of times right okay let's Jump Right In we are right okay let's Jump Right In we are given a table called Department with given a table called Department with three different columns ID Revenue month three different columns ID Revenue month and these are the data types the and these are the data types the combined columns ID month is the primary combined columns ID month is the primary key of this table the table has key of this table the table has information about revenue of each information about revenue of each department per month okay department per month okay the month has values Jan Feb March up the month has values Jan Feb March up till December okay we are asked to write till December okay we are asked to write a SQL query to reformat the table such a SQL query to reformat the table such that there is the department ID column that there is the department ID column and a revenue column for each month okay and a revenue column for each month okay order of the result does not matter so order of the result does not matter so here if you look at this example right here if you look at this example right so we have so we have different IDs different revenues and the different IDs different revenues and the months so basically what we need to do months so basically what we need to do is for one column should be for ID right is for one column should be for ID right so let's say ID is equal to 1 then so let's say ID is equal to 1 then January revenue February Revenue March January revenue February Revenue March Revenue up till December Revenue right Revenue up till December Revenue right and then for Department 81 for different and then for Department 81 for different months what is the revenue and if the months what is the revenue and if the revenue is not there so you return revenue is not there so you return similarly for all the Departments right similarly for all the Departments right so that is what we need to do so for so that is what we need to do so for example if you look at it right the example if you look at it right the department ID one department ID one right so Department id1 uh in January right so Department id1 uh in January 8000 Feb 7000 and March 6000 right so it 8000 Feb 7000 and March 6000 right so it should be one then eight thousand seven should be one then eight thousand seven thousand six thousand and the remaining thousand six thousand and the remaining columns like April to December it should columns like April to December it should be null similarly for department id2 so be null similarly for department id2 so there's only for January so everything there's only for January so everything else should be null so if you look at else should be null so if you look at this like this is what we are having this like this is what we are having right uh so let me just so yeah ID Jan right uh so let me just so yeah ID Jan Feb mod so eight thousand seven thousand Feb mod so eight thousand seven thousand six thousand and everything else is null six thousand and everything else is null here right so this is what we need to so here right so this is what we need to so if you watch the previous video the if you watch the previous video the number 149 right so it is basically number 149 right so it is basically exactly the same question right just the exactly the same question right just the table is different that you know all you table is different that you know all you need to do is Group by different IDs need to do is Group by different IDs right and then return the IDS and you right and then return the IDS and you need to use case when statements and need to use case when statements and some Automax some Automax Etc to basically return the revenue Etc to basically return the revenue right and in case and since we are using right and in case and since we are using case when statement so case when case when statement so case when something is true then return Revenue something is true then return Revenue else you return null right and you else you return null right and you perform that aggregate sum or aggregate perform that aggregate sum or aggregate Max right and that is going to do it so Max right and that is going to do it so what we need to do is from what we need to do is from this table called Department right we this table called Department right we are grouping by right so Group by the ID are grouping by right so Group by the ID then return then return ID and then what we need to do is so ID and then what we need to do is so basically case when and why we are using basically case when and why we are using case when statement so basically if you case when statement so basically if you look at it this is basically just a look at it this is basically just a pivoting of this table right so you are pivoting of this table right so you are simply you know making the rules in this simply you know making the rules in this month column into different months right month column into different months right since we are using MySQL we cannot use since we are using MySQL we cannot use the pivot function because there is no the pivot function because there is no pivot function in MySQL if you are using pivot function in MySQL if you are using Ms SQL server or any other database so Ms SQL server or any other database so probably there is a direct pivot probably there is a direct pivot function so you don't need to use case function so you don't need to use case win statements just like I am doing here win statements just like I am doing here right so case when month is equal to Jan right so case when month is equal to Jan right so you return the revenue right right so you return the revenue right return Revenue else return null since return Revenue else return null since you started the casement statements you you started the casement statements you need to end this as well and and then need to end this as well and and then once you have that so you either use sum once you have that so you either use sum or you can use use max right or you can use use max right so let's use max again in the last video so let's use max again in the last video also we use max we can use sum as well also we use max we can use sum as well does not matter so and does not matter so and as right so as what is the Alias so Jan as right so as what is the Alias so Jan Revenue right so Jan Revenue Revenue right so Jan Revenue and why is this working so as I told in and why is this working so as I told in the previous video as well right so here the previous video as well right so here one let's say for Department id1 right one let's say for Department id1 right so this these three three rows first one so this these three three rows first one and the last two rows are basically one and the last two rows are basically one group because we are grouping by ID group because we are grouping by ID right so it will say Okay case in month right so it will say Okay case in month is equal to Zen so it is Jan so it will is equal to Zen so it is Jan so it will return 8000 then for this and this it is return 8000 then for this and this it is Feb and March obviously it is going to Feb and March obviously it is going to return null right so else null now it is return null right so else null now it is say it is going to uh say Okay maximum say it is going to uh say Okay maximum of 8000 null and null right so if you of 8000 null and null right so if you know about this aggregate function since know about this aggregate function since my my sequel so what it basically does my my sequel so what it basically does is it ignores the null value right if is it ignores the null value right if you are using sum and Max but if you are you are using sum and Max but if you are doing count then it is not going to doing count then it is not going to ignore the null values right so here ignore the null values right so here when we write Max 8000 commas null and when we write Max 8000 commas null and null so Basics basically it is ignoring null so Basics basically it is ignoring the null values and returning you the the null values and returning you the 8000 and that is why you have eight 8000 and that is why you have eight thousand here seven thousand here six thousand here seven thousand here six thousand here Etc right so basically you thousand here Etc right so basically you you get that right so you need to repeat you get that right so you need to repeat the same thing the same thing from January till December right so let from January till December right so let me just you know copy paste this and me just you know copy paste this and make that so that you know we can save make that so that you know we can save our time okay so I went ahead and copy pasted this and made the adjustments right so if March up till all the way up till December right so uh I think we have it right so let me go ahead and run this to see what happens except this is accepted our output is same as expected output right so let me go ahead and submit it to see if it passes all the test cases so if this passes all the test cases and this is how I do it again not a very difficult question but it is lengthy in the sense that you need to write every for every column you need to write this case when statements obviously here you only have 12 so since there are 12 months you only have 12 columns but remember like since it can be multiple so you need to follow some Loop to do this unfortunately in MySQL there is no pivot table let me know in the comment section if there is a way to do this using Loop in MySQL can you do that if you think there is a better way or a more efficient way to solve this problem let the solution be in the comment section below and until then I will see you guys in the next | 2024-03-25 18:26:49 | 1,179 | LeetCode 1179 Amazon "Reformat Department Table" Interview SQL Question Detailed Explanation |
|
tVTSth0zFms | Everyone is welcome and welcome back to my channel, so today's our daily need code challenge so today's our daily need code challenge is from you on 14th March 2022 and I have is from you on 14th March 2022 and I have solved it so please go and check it, you solved it so please go and check it, you can search it on YouTube Simply Baat can search it on YouTube Simply Baat By Tech By Tech By Tech attach a link with this video. Okay, so I made this butter when I had around 300 subscribers, so please go and watch it and give me feedback on how it was made. If it was good then I will not make it. Again another vice I will make it again ok | 2024-03-20 11:26:52 | 71 | Simplify Path || Daily Leetcode Challenege |
|
au-CLY0mE3Q | hello everyone welcome back to harlot called Channel today I'm going to talk called Channel today I'm going to talk about a new problem about a new problem Richard number the this problem has Richard number the this problem has medium complicity and first let's look medium complicity and first let's look at the problem the problem is that you at the problem the problem is that you are standing at position 0 on an are standing at position 0 on an infinite number line infinite number line there's a go at position target and on there's a go at position target and on it you move you can either go left or it you move you can either go left or right right during the end smooth studying from 1 during the end smooth studying from 1 you take you take n steps and it asks you take you take n steps and it asks you to retain the minimum number of you to retain the minimum number of steps required to reach the destination steps required to reach the destination and here are two examples let's use the and here are two examples let's use the example to understand the problem better example to understand the problem better the first example is the target is 3 and the first example is the target is 3 and you are standing at 0 right now how many you are standing at 0 right now how many moves do we need to go from 0 to 3 so on moves do we need to go from 0 to 3 so on the ends move you can move n steps so the ends move you can move n steps so like in this example on that we on the like in this example on that we on the first move we move one step on the first move we move one step on the second move we move to step so you can second move we move to step so you can use to move to reach your target rate so use to move to reach your target rate so the output is 2 and another example is the target value is 2 and you will start studying from 0 and that's the how many moves Joey needs to reach 2 so the answer here is that you this is the first move second move and the studs move you will be able to reach 2 so the outputs value is 3 and so let's see how can we solve a very general problem such that you the target value is here and we are here so the way we solve this problem is that at each move you can move either you can either move left or moves right if you move let's let's then that means to minus some value if you move right then that is to add some value so then the girl can be expressed using these expressions such that for each value you can either for each move you can either go right or left so when you sum up the left and right together eventually you reach target and we want to find the minimum value and here as the solution to this problem and an naive approach is to enumerate all the possible combinations of the positive and negative sign I mean either go left or right so for each one we will try each combination so the time complexity will be 2 2 n so this is an exponential complicity now let's consider other approach that first let's take a very greedy approach so say you want to reach target how can you reach it as fast as you can and very into intuitive approaches to always go to the right side so that means you adapt move one move 2 to the move and together the value you want to find them first value that can expect target which means if you go always go right after and move you already somewhere here but you are not exactly at the target you may be like K steps right beyond the target so that means for some value here we cannot put the plus sign is that we need the minus sign to make the expression here exactly equal to the target so let's discuss some cases here of how the value of K can be depending on whether it's even or odd so if the K is even then we can find the sum value all right such that two times I equals K which means we can just - I here then the left expression will be exactly equal to target but if case odd then we can not find a value art which satisfy this function so that means we need to move some steps for the right so like for example if we move one actress that one action moves with n plus 1 steps then the here's the expression on the left side the expression on the right side and so our target is to find this sum value such that the right side here the combination here can be an even value so we further discuss the case here if Empress is odd then k plus n plus 1 is even so we can similarly we can use this approach to find an I which is equal which such that two times I equals to this value this value is even but if n plus one is even then this side here it will be an old value so we need to move an extra move that is Empress 2 steps such that this very will be even so we can find I hear to find an I hear such that two times I equals this expression so summarize the results if we find an expression we find first we find an end such that 1 plus 2 plus n is at least larger than target and then depending on different value of K we different value of K whether it's even or odd we have different solution and if if K is even we can find an eye directly if K is odd then we just go need to do actual moves depending on the value of M minus 1 when n minus 1 is odd that way it only needs to do this move when n minus 1 is even then we need 2 action moves ok so this is the solution of the problem and the time compress there is a constant time which is all 1 because we just enumerate underneath let's look at the code to see underneath let's look at the code to see how we solve this problem so first I've how we solve this problem so first I've got to mentioned if target is a negative got to mentioned if target is a negative value first for simplicity we can value first for simplicity we can directly make it as positive value directly make it as positive value because the result will be exactly the because the result will be exactly the same and the first that finds the first same and the first that finds the first n such that 1 plus 2 plus and equal R is n such that 1 plus 2 plus and equal R is is equal or larger than target so this is equal or larger than target so this is the N value this is the position so is the N value this is the position so when petitioner is less than target we when petitioner is less than target we keep it up there and value by one and keep it up there and value by one and I kept moving right and so that's here I kept moving right and so that's here we got that one press M press to present we got that one press M press to present equals target plus K depending on equals target plus K depending on different value of K the results will be different value of K the results will be different so um we discussed the edge different so um we discussed the edge cases here one position we will current cases here one position we will current they're already at target the record they're already at target the record returned end and otherwise we can play returned end and otherwise we can play decay like how many actual steps have we decay like how many actual steps have we moved which is equals to position - moved which is equals to position - target and then if the K is an older target and then if the K is an older value is an even value that we can find value is an even value that we can find an eye as we discussed so we can an eye as we discussed so we can directly return n and otherwise if directly return n and otherwise if impressed one is an it's an alt value impressed one is an it's an alt value we've written we return and press one we've written we return and press one otherwise we'll return and press 2 and otherwise we'll return and press 2 and this solution is accepted and this is a this solution is accepted and this is a constant compressed a solution that constant compressed a solution that compressed is all one yeah okay so that compressed is all one yeah okay so that is this problem this problem Manik is is this problem this problem Manik is purpose of testing like the mathematic purpose of testing like the mathematic and logic thinking of problem rather and logic thinking of problem rather than other techniques so this is quite than other techniques so this is quite an interesting problem hope you guys can an interesting problem hope you guys can enjoy it and thank you for watching this enjoy it and thank you for watching this video I will see you guys next time video I will see you guys next time thank you | 2024-03-21 15:50:49 | 754 | LeetCode Tutorial 754: Reach a Number |
|
u_2kOwmJQW4 | solving the greatest sum divisible by 3 problem from lead code using dynamic problem from lead code using dynamic programming is what we are going to do programming is what we are going to do in this video of joey's tech welcome my in this video of joey's tech welcome my friends i am joey and yes i will be friends i am joey and yes i will be telling you how to think of the approach telling you how to think of the approach to the dp solution of this problem this to the dp solution of this problem this is one of the exciting problems i came is one of the exciting problems i came across and let me tell you solving this across and let me tell you solving this problem using dp will feel truly magical problem using dp will feel truly magical to you especially in the way we are to you especially in the way we are going to approach the solution so going to approach the solution so without further ado let's look into the without further ado let's look into the problem statement now problem statement now you are given an array of integers nums you are given an array of integers nums like this these are the elements inside like this these are the elements inside the anoms that we are going to consider the anoms that we are going to consider for our problem for our problem the ask is to find the maximum possible the ask is to find the maximum possible sum from this array nums that is sum from this array nums that is divisible by 3. so if we carefully take divisible by 3. so if we carefully take a look at it then a look at it then if we add 3 6 1 and 8 if we add 3 6 1 and 8 then we are going to get 18 and that then we are going to get 18 and that happens to be the maximum possible sum happens to be the maximum possible sum divisible by 3 from this array nups divisible by 3 from this array nups so we need to come up with a dynamic so we need to come up with a dynamic programming algorithm that produces this programming algorithm that produces this result 18. but before that a humble result 18. but before that a humble request to you to subscribe to my request to you to subscribe to my channel if you haven't done it already channel if you haven't done it already and hit the bell icon so that you do not and hit the bell icon so that you do not miss out on these videos especially miss out on these videos especially these dynamic programming videos i these dynamic programming videos i create for you all right you can see the create for you all right you can see the array over here now let me tell you that array over here now let me tell you that i tried a few approaches of tb to solve i tried a few approaches of tb to solve this problem like the two variables this problem like the two variables approach using which i have solved approach using which i have solved numerous problems using dynamic numerous problems using dynamic programming but especially in this programming but especially in this problem i found those approaches getting problem i found those approaches getting complicated so the basic idea or the complicated so the basic idea or the stepping stone to solve this problem stepping stone to solve this problem using dp lies in focusing on the phrase using dp lies in focusing on the phrase divisible by 3 when we divide any divisible by 3 when we divide any integer by 3 then what can happen the integer by 3 then what can happen the integer either will be completely integer either will be completely divisible by 3 or will give the divisible by 3 or will give the remainders 1 or 2 remainders 1 or 2 right just keep this in mind and now right just keep this in mind and now look at the problem in this manner what look at the problem in this manner what the first integer in this array is it is the first integer in this array is it is 3 and it is divisible by 3 3 and it is divisible by 3 so the greatest sum till here so the greatest sum till here is 3 okay now we move to the next is 3 okay now we move to the next integer which is 6. so 6 is also integer which is 6. so 6 is also divisible by 3. that's one candidate and divisible by 3. that's one candidate and we have a candidate already present we have a candidate already present which is 3 and since the problem is which is 3 and since the problem is about finding the sum the greatest sum about finding the sum the greatest sum the maximum possible sum the maximum possible sum hence we get our third candidate as well hence we get our third candidate as well which will be the summation of 6 and 3 which will be the summation of 6 and 3 which comes out as 9. look all these which comes out as 9. look all these candidates are divisible by 3. so we candidates are divisible by 3. so we pick the greatest one out of these 3 pick the greatest one out of these 3 which is going to be 9. so till here the which is going to be 9. so till here the greatest sum that is going to be greatest sum that is going to be divisible by 3 will be 9. all right we divisible by 3 will be 9. all right we move to the next integer of the array move to the next integer of the array now which is 5. we are going to expand now which is 5. we are going to expand the horizon of our understanding so make the horizon of our understanding so make sure you watch this part very carefully sure you watch this part very carefully the candidate which is the greatest sum the candidate which is the greatest sum divisible by 3 till here is 9 right now divisible by 3 till here is 9 right now we add 5 to it when we add 5 to 9 we are we add 5 to it when we add 5 to 9 we are going to get 14. when we divide 14 by 3 going to get 14. when we divide 14 by 3 we get 2 as the remainder so no way 14 we get 2 as the remainder so no way 14 is the greatest sum that is divisible by is the greatest sum that is divisible by 3 3 but we need to keep track of it because but we need to keep track of it because it will help us in the future to find it will help us in the future to find the greatest sum divisible by three the greatest sum divisible by three because there are more elements because there are more elements remaining so we open three slots the remaining so we open three slots the first one is going to store the largest first one is going to store the largest sum for which the remainder comes out as sum for which the remainder comes out as zero when it is divided by three the zero when it is divided by three the second one will store the largest sum second one will store the largest sum for which the remainder comes out as 1 for which the remainder comes out as 1 when it is divided by 3 and the third when it is divided by 3 and the third one is going to store the largest sum one is going to store the largest sum for which the remainder comes out as 2 for which the remainder comes out as 2 when it is divided by 3 so 14 goes in when it is divided by 3 so 14 goes in this slot of remainder 2 but let's start this slot of remainder 2 but let's start over let's start from the first over let's start from the first iteration so that you understand in a iteration so that you understand in a much proper way in the first titration much proper way in the first titration the integer is 3 when it is divided by 3 the integer is 3 when it is divided by 3 the remainder comes out as 0 so the the remainder comes out as 0 so the greatest sum till here greatest sum till here will be 3 which we have already seen so will be 3 which we have already seen so we are going to put 3 in this slot of we are going to put 3 in this slot of remainder 0. note why we have put it in remainder 0. note why we have put it in this slot of remainder 0 because the this slot of remainder 0 because the remainder came out as 0 when we divided remainder came out as 0 when we divided it by 3. now it by 3. now in the first titration the other slots in the first titration the other slots will be empty i am going to fill these will be empty i am going to fill these empty spaces with empty spaces with 0. now the algorithm is going to move to 0. now the algorithm is going to move to the second iteration here 3 will be the second iteration here 3 will be added to 6 the addition of 3 and 6 will added to 6 the addition of 3 and 6 will be 9 which is completely divisible by 3 be 9 which is completely divisible by 3 so 9 also goes in the slot of remainder so 9 also goes in the slot of remainder 0. all right and these slots of 0. all right and these slots of remainder 1 and remainder 2 will have a remainder 1 and remainder 2 will have a 0 as their values because there has been 0 as their values because there has been no greatest sum encountered till here no greatest sum encountered till here for which the remainder comes out as for which the remainder comes out as either 1 or 2 when they are divided by 3 either 1 or 2 when they are divided by 3 in the third iteration 9 will be added in the third iteration 9 will be added to 5 and that is going to give us the to 5 and that is going to give us the sum as 14. the remainder comes out as 2 sum as 14. the remainder comes out as 2 when 14 is divided by 3 hence we are when 14 is divided by 3 hence we are going to put 14 in this slot of going to put 14 in this slot of remainder 2 but wait a minute there is remainder 2 but wait a minute there is another slot that we are going to fill another slot that we are going to fill and that is the slot of remainder 0 and that is the slot of remainder 0 where the greatest possible sum so far where the greatest possible sum so far is 9 so we won't hesitate in bringing 9 is 9 so we won't hesitate in bringing 9 here in this slot of remainder 0. so for here in this slot of remainder 0. so for every iteration the dp algorithm is every iteration the dp algorithm is going to compare the values present in going to compare the values present in all these three slots against the values all these three slots against the values present in the same slots in the present in the same slots in the previous iteration and between the two previous iteration and between the two values the greater one will be populated values the greater one will be populated in the respective slots so for the in the respective slots so for the algorithm the default value present in algorithm the default value present in these slots will be 0 these slots will be 0 0 compared against a 9 will bring a 9 0 compared against a 9 will bring a 9 over here that's how algorithm is going over here that's how algorithm is going to work the same comparison will happen to work the same comparison will happen for these slots as well 0 will be for these slots as well 0 will be compared against 0 so no change 14 will compared against 0 so no change 14 will be compared against 0 14 is much greater be compared against 0 14 is much greater so 14 stays populated in this cell of so 14 stays populated in this cell of remainder 2 in the third column we move remainder 2 in the third column we move to the next integer now which is 1 to the next integer now which is 1 we add 1 to this 9 what do we get we get we add 1 to this 9 what do we get we get 10 the remainder comes out as 1 when 10 10 the remainder comes out as 1 when 10 is divided by 3 so what we are going to is divided by 3 so what we are going to do we are going to straight away put 10 do we are going to straight away put 10 in this slot of remainder 1 we are going in this slot of remainder 1 we are going in a much formal fee now the way the tp in a much formal fee now the way the tp algorithm is going to proceed this is algorithm is going to proceed this is how i shaped my own understanding guys how i shaped my own understanding guys now we are going to add 1 to this 0 as now we are going to add 1 to this 0 as well okay we are going to add this well okay we are going to add this integer to the values of every slot by integer to the values of every slot by adding 1 to this 0 we are going to get adding 1 to this 0 we are going to get 1 so when we are going to divide 1 by 3 1 so when we are going to divide 1 by 3 the remainder is going to automatically the remainder is going to automatically come out as come out as 1 1 so we try to populate this lot of so we try to populate this lot of remainder 1 with 1 but there is already remainder 1 with 1 but there is already a giant value sitting over here which is a giant value sitting over here which is 10 10 10 is greater than 1 so no way we are 10 is greater than 1 so no way we are going to put 1 over here going to put 1 over here we keep 10 and discard one you are now we keep 10 and discard one you are now going to ask me going to ask me why i didn't add five to these zeros of why i didn't add five to these zeros of slot one and two or why i didn't add the slot one and two or why i didn't add the six to these zeroes of slots one and two six to these zeroes of slots one and two the answer is i didn't want to create the answer is i didn't want to create any confusion earlier now if you go back any confusion earlier now if you go back and if you add 5 to this 0 then you are and if you add 5 to this 0 then you are going to get 5 you divide it by 3 the going to get 5 you divide it by 3 the remainder is going to come out as 2 remainder is going to come out as 2 hence you will try to populate this cell hence you will try to populate this cell with 5 with 5 14 is already present over here which is 14 is already present over here which is much greater than 5 so 5 gets discarded much greater than 5 so 5 gets discarded and 14 stays similarly if you add 6 to and 14 stays similarly if you add 6 to this 0 then you are going to get 6 only this 0 then you are going to get 6 only you divide it by 3 you get the remainder you divide it by 3 you get the remainder as 0 you try to populate 6 in this cell as 0 you try to populate 6 in this cell of slot 0 9 is already sitting over here of slot 0 9 is already sitting over here 6 compared against 9 9 is much greater 6 compared against 9 9 is much greater so 9 stays 6 gets discarded all right so 9 stays 6 gets discarded all right now coming back to this iteration only now coming back to this iteration only we add 1 to this 14 we are going to get we add 1 to this 14 we are going to get 15 when 15 is divided by 3 the remainder 15 when 15 is divided by 3 the remainder comes out as 0 comes out as 0 so we populate 15 in this cell all right so we populate 15 in this cell all right now after the values are populated in now after the values are populated in each of these slots the algorithm is each of these slots the algorithm is going to do one final thing for every going to do one final thing for every iteration iteration it's going to compare the values in each it's going to compare the values in each of these slots against the value in the of these slots against the value in the same slot of the previous iteration same slot of the previous iteration and the greater value is going to get and the greater value is going to get the priority so 15 will be compared the priority so 15 will be compared against 9 since 15 is greater hence 15 against 9 since 15 is greater hence 15 stays 10 will be compared against 0 stays 10 will be compared against 0 since 10 is greater hence 10 stays since 10 is greater hence 10 stays and 0 will be compared against 14 since and 0 will be compared against 14 since 14 is much greater hence 0 gets replaced 14 is much greater hence 0 gets replaced by 40. understand the basic idea guys we by 40. understand the basic idea guys we are capturing the greatest sums which are capturing the greatest sums which give remainders give remainders 0 1 and 2 for every iteration we now 0 1 and 2 for every iteration we now have 8 as the next integer we add 8 to have 8 as the next integer we add 8 to 15 we get 23 15 we get 23 that goes to slot with remainder 2 that goes to slot with remainder 2 all right now we add 8 to 10 that gives all right now we add 8 to 10 that gives us 18 us 18 it is divisible by 3 completely it is divisible by 3 completely divisible by 3 so 18 goes to the slot divisible by 3 so 18 goes to the slot of remainder 0 of remainder 0 now now we are going to add 8 to 14 that is we are going to add 8 to 14 that is going to give us 22 going to give us 22 we put it in the slot with a remainder we put it in the slot with a remainder 1 22 divided by 3 gives us the remainder 1 22 divided by 3 gives us the remainder 1 hence 22 goes in this slot 1 hence 22 goes in this slot of remainder 1. now these cells are of remainder 1. now these cells are populated the algorithm is going to populated the algorithm is going to compare this 18 against this 15 compare this 18 against this 15 18 is greater so 18 stays it's going to 18 is greater so 18 stays it's going to compare this value of slot 1 with the compare this value of slot 1 with the previous value in the same slot 1 22 is previous value in the same slot 1 22 is greater than 10 so 22 stays and finally greater than 10 so 22 stays and finally it is going to compare 23 against 14 23 it is going to compare 23 against 14 23 is also greater than 14 so 23 stays is also greater than 14 so 23 stays remember why we compare the value remember why we compare the value calculated in a particular slot with the calculated in a particular slot with the value in the same slot from the previous value in the same slot from the previous iteration because we are looking for the iteration because we are looking for the greatest sum for each of these slots if greatest sum for each of these slots if the algorithm hadn't done so we wouldn't the algorithm hadn't done so we wouldn't have got 9 over here or 14 over here oh have got 9 over here or 14 over here oh goodness me the matrix is full so this goodness me the matrix is full so this value value the value in the final column in the the value in the final column in the slot of remainder 0 is the answer so 18 slot of remainder 0 is the answer so 18 is the maximum possible sum from this is the maximum possible sum from this array of integers that is completely array of integers that is completely divisible by three if you want to check divisible by three if you want to check out the java code for this dynamic out the java code for this dynamic programming problem then you can find it programming problem then you can find it in my github repository you can find the in my github repository you can find the link to it in the description box link to it in the description box also check out my playlist of dynamic also check out my playlist of dynamic programming problems where i have programming problems where i have explained the approach to getting to the explained the approach to getting to the solution of hundreds of problems that solution of hundreds of problems that can be solved using dynamic programming can be solved using dynamic programming with this we have come to the end of with this we have come to the end of this video i hope you enjoyed learning this video i hope you enjoyed learning to solve this problem of greatest sum to solve this problem of greatest sum divisible by 3 using dynamic programming divisible by 3 using dynamic programming if you have any doubts related to this if you have any doubts related to this problem problem please let me know in the comment please let me know in the comment section i'll try my best to solve them i section i'll try my best to solve them i look forward to helping you with look forward to helping you with programming and algorithms programming and algorithms and only for this video goodbye and take and only for this video goodbye and take very good care of yourself | 2024-03-19 17:44:59 | 1,262 | Greatest sum divisible by 3 - Leetcode 1262 - Dynamic Programming |
|
gmuVRoWTT2k | welcome ladies and gentlemen for another exercise on leapcoat exercise on leapcoat today it's about the gold passer today it's about the gold passer interpretation interpretation so i guess it's coming from like a so i guess it's coming from like a football scenario football scenario so basically from this exercise if so basically from this exercise if you're given a command you're given a command and you see g in that command and you see g in that command you interpret it as g you interpret it as g if you see the open and closing if you see the open and closing parenthesis with nothing inside parenthesis with nothing inside interpret it as um oh interpret it as um oh and if you see the open and closing and if you see the open and closing parameter with a l parameter with a l inside we interpret as just a l inside we interpret as just a l this is an example here g this is an example here g is g up and closes is g up and closes o and uh up on close to a l o and uh up on close to a l is here it extrapolates here is here it extrapolates here like you can see go oh oh oh like you can see go oh oh oh otherwise so we have to look through this command and break it down by uh letter or parentheses symbols so um we're gonna draw the while loop you will see why so going to have my looping variable i as usual zero a variable that is going to a variable that is going to have the answer at the end have the answer at the end in the form of an array i'm going to construct um this as an array okay so let's start the loop so i is going to loop until [Music] the end of the command i to be equal to g i'm going to push the character g inside i'm going to push the character g inside so as i'm looping over i'm going to if i so as i'm looping over i'm going to if i detect detect g i'm going to put g inside my g i'm going to put g inside my array so i'll be going ahead and array so i'll be going ahead and constructing that way constructing that way and i is going to increment and i is going to increment to one because when i see g to one because when i see g i interpret it then i go to the next i interpret it then i go to the next character i'm going to meet this upon character i'm going to meet this upon braces braces for this example too for example for this example too for example and then we meet the character we meet the character open braces now we have two scenarios when we meet open brace it can either be the open close with nothing inside or with al inside so we evaluate so if the second character closer so if the second character closer i plus one is um parenthesis it means we parenthesis it means we add the el add the el so inside answer so inside answer are going to push here yes it means uh the closing uh yes it means uh the closing uh it means the next character is actually it means the next character is actually the closing the closing parentheses so we're going to parentheses so we're going to push um oh at the end we have our answer interpreted oops we have to debate we have some oops we have to debate we have some errors errors oh we're not done um oh we're not done um also let's run it again so that you can so you can see fatal error call and we so you can see fatal error call and we try last allocation for javascript heap try last allocation for javascript heap out of memory a part of memory usually out of memory a part of memory usually when you when you overload the memory like something overload the memory like something running running without stopping here because we haven't without stopping here because we haven't um um control the variable that permits to get control the variable that permits to get out of the while out of the while which is the eye at the second if which is the eye at the second if so let's come back here if we meet so let's come back here if we meet um the closing if we made the opening parenthesis let's start from that and the next and the next is not the closing it means we are at this particular open air and close if that's the case once we interpret the if that's the case once we interpret the whole of the string whole of the string which occupies four characters we have which occupies four characters we have to just keep and go to the next to just keep and go to the next [Music] [Music] the next possible letter for the goal the next possible letter for the goal so i is going to skip by four and for so i is going to skip by four and for this one this one is going to skip by two because we have is going to skip by two because we have uh uh open and closing parenthesis which is open and closing parenthesis which is two characters so when we're done two characters so when we're done interpreting we skip two interpreting we skip two i think that should be the reason since i think that should be the reason since this wasn't controlled we have that hip this wasn't controlled we have that hip error below error below so let's display again our answer we get something like this this is the array i was constructing so now we just have to join everything together as a string and return joint joint right good to go that's on me i'll be glad to have in the comments any i'll be glad to have in the comments any other procedures that can be other procedures that can be used to optimize this but for now this used to optimize this but for now this is what i have for you is what i have for you and see you on another | 2024-03-20 12:14:04 | 1,684 | Goal parser interpretation | Leetcode 1684 | Javascript |
|
DQbeqqyhGUU | recyclable and low fat products is a resql problem that involves finding all resql problem that involves finding all the products that are both low-fat and the products that are both low-fat and recyclable this question can be accessed recyclable this question can be accessed through leadcode.com problem slash through leadcode.com problem slash recyclable and low-fat products products recyclable and low-fat products products in a given database table name products in a given database table name products write an SQL query to find the IDS of write an SQL query to find the IDS of products that are both low fat and products that are both low fat and recyclable the products table has three recyclable the products table has three columns product underscore Aid low columns product underscore Aid low underscore fats and recyclable the underscore fats and recyclable the product underscore it column is the product underscore it column is the primary key of the table and is of type primary key of the table and is of type int the low underscore fats column is an int the low underscore fats column is an NM of type why n where y means the NM of type why n where y means the product is low fat and N means it is not product is low fat and N means it is not the recyclable column is also an NM of the recyclable column is also an NM of type Y and where y means the product is type Y and where y means the product is recyclable and N means it is not recyclable and N means it is not to solve this problem we need to write a to solve this problem we need to write a select statement that filters the select statement that filters the products table to only include rows products table to only include rows where the low underscore fats column is where the low underscore fats column is y and the recyclable column is y this y and the recyclable column is y this will return all the products that are will return all the products that are both low fat and recyclable both low fat and recyclable here is the basic Syntax for a select here is the basic Syntax for a select statement in SQL statement in SQL select column underscore names from select column underscore names from table underscore name where condition table underscore name where condition addition to filter the results of a addition to filter the results of a select statement based on multiple select statement based on multiple conditions we can use the and operator conditions we can use the and operator the and operator allows us to specify the and operator allows us to specify multiple conditions that must be met in multiple conditions that must be met in order for a row to be included in the order for a row to be included in the result set here is an example of how we result set here is an example of how we can use the end operator to filter the can use the end operator to filter the products table to only include rows products table to only include rows where the low underscore fats column is where the low underscore fats column is y and the recyclable column is y this y and the recyclable column is y this select statement will return the product select statement will return the product underscore Aid of all the products that underscore Aid of all the products that are both low fat and recyclable are both low fat and recyclable applicable select product underscore it applicable select product underscore it from products where low underscore fats from products where low underscore fats equals y and recyclable equals y alternatively we can also use the inoperator to simplify the query the inoperator allows us to specify a list of values that we want to include in the result set here is an example of how we can use the inoperator to filter the products table to only include rows where the low underscore fats column is y and the recyclable column is y this select statement will return the same result as the previous example select product underscore it from products where low underscore fats in y | 2024-03-22 12:07:24 | 1,757 | Leetcode SQL problem 1757 - Recyclable and Low Fat Products |
|
aLtW5ki6WWE | Scientist Hi Guys How Are You I Hope For Doing Good So This Is The New Yorker Face Which Has Been So This Is The New Yorker Face Which Has Been Created Athlete Code And Created Athlete Code And This Is The White Bun I Like It Record This Is The White Bun I Like It Record You Very Colorful And And Share Feedback Option You Very Colorful And And Share Feedback Option Dowry Want To The Receiver Want To Go Dowry Want To The Receiver Want To Go Dowry Want To The Receiver Want To Go attend the festival is the president where we are used to a guy but that's the question in the series so I hope you are in every I hope you are in every I hope you are in every sphere of these just like comment sphere of these just like comment and share and also tummy rest house farewell and share and also tummy rest house farewell improve my teaching skills that you can improve my teaching skills that you can learn a very well what I chair here learn a very well what I chair here let me first give the same let me first give the same question which we use to do Ho, on the first day of my husband, Ram match, a big mock that I don't know what is the problem, how do you have difficulty level status of the foreign country behaved, back to the question Some of the people are in the dark Are on sea I gave your show question which they have used to beach is bank intersection found so clearly is raw or betting suggestion it to festival solve remove is raw or betting suggestion it to festival solve remove time of these to will do minimum time time of these to will do minimum time distinguishing distinguishing distinguishing specific day every day time electricity bill question and win you to give more time on difficult strict military day for something important question of vegetable soup of but today we are so glad to have too many B Happy Calculator So B Happy Calculator So B Happy Calculator So Minimum Time Incident Withdrawal Point Okay Minimum Time Incident Withdrawal Point Okay Researcher Possible Direction Where They Can Do We Can Move Vertically Upward Researcher Possible Direction Where They Can Do We Can Move Vertically Upward Vikram We Khali Vikram We Khali Urgently We Can Move Vikram That Urgently We Can Move Vikram That Recent And Vinegar Diagnosis For Recent And Vinegar Diagnosis For Ki Bihar To Visit Wala Point Se Motor Show Ki Bihar To Visit Wala Point Se Motor Show Edison So It's Clear Edison So It's Clear Edison So It's Clear not have heart this browser that from which modal sudhijano setting show sweeties dhawan weight 600 this study from off to kanpur distance from three list reward for this is to do not welcome to take medicine - Ramoji Disputed Area Hall Disputed Area Hall Disputed Area Hall Problem This Android F1 Price 122 Problem This Android F1 Price 122 Bank Video Pizza Very Very Very Easy Bank Video Pizza Very Very Very Easy Fashion Ishq Very Easy To Send But You Have Fashion Ishq Very Easy To Send But You Have Analyzed This Totke Best Hot And Digression Analyzed This Totke Best Hot And Digression The First Analyst Phance 1000 Like It Is - The First Analyst Phance 1000 Like It Is - Repair Zero And His Team For It Give Repair Zero And His Team For It Give Information Information Information is the distance and what is the time quite to start from here and tourist here it is the difference between the spot and the college and pithadheeshwar coordinator and security convention from the strong list to the straight line a that and Can Also Find This Eminem The Can Also Find This Eminem The Can Also Find This Eminem The Distance Between Is The Time You Can See A Distance Between Is The Time You Can See A Time When E To Take Off Baroda Sugar Two Time When E To Take Off Baroda Sugar Two Table Spoon Profile Skin Disease And Table Spoon Profile Skin Disease And Like This Is The Third Reich Only And Only Like This Is The Third Reich Only And Only ₹100 Distance And Thee - Off - 150 416 ₹100 Distance And Thee - Off - 150 416 We can find a distance We can find a distance that apes loot of My Son Overload Straight Line Sona You Can Find It In The Distance Between A Man And Every Time Required To Distance Point Sona Destabilizes The It's Clear Net Previous - Great Britain Simply Find The Different But Effective Work Ban Hair Serum Deal Deal Deal Time Required In Through 30 Minutes Hours Time Required In Through 30 Minutes Hours So Executive Apply This Formula One So Executive Apply This Formula One Allowed Obscene Man To But They Need To Allowed Obscene Man To But They Need To Request The Minister But Top 3 Tomorrow Request The Minister But Top 3 Tomorrow Morning You Can See But Is You Who Is This Morning You Can See But Is You Who Is This Point To Make From This Point Is On Point To Make From This Point Is On That Auspicious That Auspicious That Auspicious Is The Governor And Ifik Udyan A And Distances Same 2009 Back And Subscribe Now Want The Time Which Needs Page if you liked The Video then subscribe Are You Can Take A Few Years 2007 Earnings improved distance between us the Earnings improved distance between us the Earnings improved distance between us the real estate needle reminder given this real estate needle reminder given this phone lock teacher C but if you who is this phone lock teacher C but if you who is this point and after 10 minutes al hits of what it's point and after 10 minutes al hits of what it's 087 Madheshi subscribe 0 087 Madheshi subscribe 0 I myself so PM I myself so PM that this 390 ironing suit what you can that this 390 ironing suit what you can that this 390 ironing suit what you can I One Value 0a Entry Work Start New Baby 2006 - I Will Give Thee Its Immediate Speed Come Acts Of This Too Difficult Verification President Acid Attack In The Weather You Are Taking Porn And Transport More Video subscribe Video give Vidash subscribe Page if you Page if you Page if you liked The Video then subscribe to liked The Video then subscribe to Ya Bhai Vishesh Hu Is Ya Bhai Vishesh Hu Is This And This Is A Mess This Ki Inko This And This Is A Mess This Ki Inko Diwasiya Share It Will Take Two To Diwasiya Share It Will Take Two To Effects From Na Sohe Gal 335 2323 Shobhan Effects From Na Sohe Gal 335 2323 Shobhan This Confirm Dowry Suppressed Person Subscribe This is beginning is This is beginning is This is beginning is effective from hair soft point is speed come effective from hair soft point is speed come to English which aromatic medicines from to English which aromatic medicines from three and its to switch total 786 three and its to switch total 786 internet internet that this to-do list you loot and oils in front that this to-do list you loot and oils in front of those came the points minus one of those came the points minus one and here and here and here 204 net result is equal to result plus and water max of you drink imt points of i sugiyama to katni beawar to like welcome to 100 200 to zf the voice of ibn18 electronic machine and Dhawan Thing IS Copy The Same Thing Results Aapko Mu Jo Results Aapko Mu Jo Person Desh Loot Hui Ki Is Result Ki And Ki Is Results Icon Zero Payo Payo Dhan Correctly Should Aim To Increase The IS Well So Constitution Bench Straight Line Constitution Bench Straight Line Constitution Bench Straight Line Network Fine But That Test This Begum Acts Network Fine But That Test This Begum Acts Of Two The Of Two The George Media Exposed In A Different George Media Exposed In A Different In Accident In Give Me The Character In Accident In Give Me The Character Also Press Surya Hai Take Care Very Also Press Surya Hai Take Care Very Here Text Is That Tax Collection Here Text Is That Tax Collection Difference And Active Okay Solid Difference And Active Okay Solid Difference And Active Okay Solid Success Fully Hatable And Tours Elections Will Meet In A Cn You Prepare You Prepare Things Should Decide Where Will Also Give Description Things Should Decide Where Will Also Give Description In The Eye Button So You Can Check Out From In The Eye Button So You Can Check Out From Rate Increase Next Video Rate Increase Next Video Bye-Bye Take Care And Subscribe Please Mez Kar Bye-Bye Take Care And Subscribe Please Mez Kar | 2024-03-19 17:50:08 | 1,266 | 1266 Minimum Time Visiting All Points | Leetcode Question 1266 solution | Solution in python |
|
xNHV6zYQcMU | good evening everyone today we are going to do the daily record challenge of 26 to do the daily record challenge of 26 January 2023 that is 787 question number January 2023 that is 787 question number cheapest flight within K stop so the cheapest flight within K stop so the question is saying that there are ncts question is saying that there are ncts which are connected by some number of which are connected by some number of flights and we are given an array of flights and we are given an array of flights and there we are given the flights and there we are given the starting index the ending index and the starting index the ending index and the price to reach that index price to reach that index okay and we are also given three integer okay and we are also given three integer Source destination and K and we have to Source destination and K and we have to return the cheapest price from source to return the cheapest price from source to distance with at most K stops and if distance with at most K stops and if there is no route possible we will there is no route possible we will return -1 okay so this is what our return -1 okay so this is what our question is saying we have to return the question is saying we have to return the cheapest flight from source to cheapest flight from source to destination with at most K steps so destination with at most K steps so let's move on to the example and see how let's move on to the example and see how it is working it is working so in the first example what we are so in the first example what we are given we are given flights from 0 to 1 given we are given flights from 0 to 1 at the cost of 100 flight from one to at the cost of 100 flight from one to two at the cost of 100 right from 2 to 0 two at the cost of 100 right from 2 to 0 at the cost of 100 and flight from one at the cost of 100 and flight from one to three at the cost of 69 flight from to three at the cost of 69 flight from two to three at the cost of 200. what is two to three at the cost of 200. what is our source our source is this index zero our source our source is this index zero index and from Source we have to reach index and from Source we have to reach destination that is 3 in this case and destination that is 3 in this case and what is the value of K in this case it what is the value of K in this case it is 1 so that means we can have at most is 1 so that means we can have at most one step one step that means we can have at most one stop that means we can have at most one stop okay so what are the possible ways to okay so what are the possible ways to reach here one is from 0 to 1 that is reach here one is from 0 to 1 that is 100 100 then 1 to 2 that is another hundred plus then 1 to 2 that is another hundred plus hundred hundred then two to three that is 200 so how then two to three that is 200 so how much it is it is around 400 rupees much it is it is around 400 rupees 400 currency whatever you are thinking 400 currency whatever you are thinking but if we move from 0 to 1 but if we move from 0 to 1 that is hundred plus one two three that that is hundred plus one two three that is 600 so total is 700. is 600 so total is 700. so which is cheapest among these 400 but so which is cheapest among these 400 but it will not be the answer why because we it will not be the answer why because we have to also consider the number of have to also consider the number of stops stops when we move from 0 1 2 then 3 then we when we move from 0 1 2 then 3 then we are having one and two stops but when we are having one and two stops but when we move from 0 1 then 3 then we are only move from 0 1 then 3 then we are only having one stop that is one having one stop that is one so our answer would be 700 let's take so our answer would be 700 let's take another example another example in this question we are given that we in this question we are given that we have at most have at most one stop one stop and our source is zero one stop one stop and our source is zero destination is 2. this is our destination is 2. this is our destination and this is our source destination and this is our source go from source to destination we have go from source to destination we have two ways one is one two two that is 500. two ways one is one two two that is 500. and it is without any stop another is and it is without any stop another is zero to two that is 100 plus 100 that is zero to two that is 100 plus 100 that is 200. 200. so which one of them is cheaper this one so which one of them is cheaper this one is cheaper so we will go with this step is cheaper so we will go with this step yes or no yes or no but if you consider another example in but if you consider another example in this example you are given 0 stops that this example you are given 0 stops that means you have to find a direct way to means you have to find a direct way to this from source to destination and that this from source to destination and that is only possible by is only possible by 500 so in this case 500 would be 500 so in this case 500 would be answered not 200 why not 200 because we answered not 200 why not 200 because we are having one stop and no stops are are having one stop and no stops are allowed in this case allowed in this case so this is you have to do so this is you have to do so to do this question I will give you a so to do this question I will give you a hint you try it and then come back to hint you try it and then come back to the video the hint is you have to apply the video the hint is you have to apply BFS breath versus because you have to BFS breath versus because you have to consider every possible ways and you consider every possible ways and you have to find the cheapest among them and have to find the cheapest among them and for finding the cheapest you will make a for finding the cheapest you will make a distance array so please try this on distance array so please try this on your own and then come back to the video your own and then come back to the video so I hope you tried the question on your so I hope you tried the question on your own so now moving on let me tell you how own so now moving on let me tell you how to do this question so to do this to do this question so to do this question you will make a queue for a BFS question you will make a queue for a BFS and you will also make a and you will also make a distance array in which you will store distance array in which you will store the distances the minimum distances the distances the minimum distances and when you are you have got all the and when you are you have got all the minimum distances you will simply return minimum distances you will simply return the minimum distance of source which was the minimum distance of source which was there okay there okay uh okay F4 uh okay F4 so here what you will do you will start so here what you will do you will start with the source index source is here 0 with the source index source is here 0 in the queue this is your queue in the queue this is your queue and this is your distance array so and this is your distance array so inside the queue what you will push you inside the queue what you will push you will not only push the element also you will not only push the element also you will push the distance so the distance will push the distance so the distance of Q from its source is 0 comma 0. and of Q from its source is 0 comma 0. and initially you will initialize the initially you will initialize the distance array with infinite values distance array with infinite values 4 only 0 1 2 4 only 0 1 2 3 this is nothing you will initialize 3 this is nothing you will initialize them with infinite value them with infinite value and when what is the process of BFS you and when what is the process of BFS you will pop it and you will update it what will pop it and you will update it what is minimum of infinite and 0 it is zero is minimum of infinite and 0 it is zero so here it will be 0 and after when you so here it will be 0 and after when you have popped it you will see what are the have popped it you will see what are the possible waste from zero it is this way possible waste from zero it is this way yes or no that is 1 comma 100 so to yes or no that is 1 comma 100 so to reach 1 we are having 100 unit of time reach 1 we are having 100 unit of time so we will update it here now after this so we will update it here now after this we will compare which is smaller from we will compare which is smaller from 100 and infinite it is 100 so we will 100 and infinite it is 100 so we will update our infinite 200 and then we will update our infinite 200 and then we will pop it and after popping it we have two pop it and after popping it we have two choices first is 2 comma 100 choices first is 2 comma 100 another is another is 3 comma 600. 3 comma 600. so then we will again compare and again so then we will again compare and again update it and then again pop and we we update it and then again pop and we we will do this and whenever we are popping will do this and whenever we are popping after that we will also need a variable after that we will also need a variable steps why steps variable this will count steps why steps variable this will count our total number of steps and it should our total number of steps and it should always be less than K according to our always be less than K according to our question so we do not exceed number of question so we do not exceed number of steps okay steps okay and when next time you will push the and when next time you will push the elements you will push the next method elements you will push the next method so when you upgrade it to 600 you will so when you upgrade it to 600 you will see this but next time when you are see this but next time when you are pushing the next element where that is pushing the next element where that is again you are getting 3 for 200 so this again you are getting 3 for 200 so this time you will time you will push this element as well and update it push this element as well and update it to 200 okay and you are pushing the new to 200 okay and you are pushing the new way here as well and at that time you way here as well and at that time you will notice that the case size is will notice that the case size is exceeded so you will stop our BFS okay exceeded so you will stop our BFS okay and we will not continue our BFS when we and we will not continue our BFS when we are exceeding our case size so let's are exceeding our case size so let's change this in the code and we will change this in the code and we will understand it better so to brief you understand it better so to brief you with the web or approach we had to make with the web or approach we had to make a queue in which we have to pass a pair a queue in which we have to pass a pair of vertices and the cost of vertices and the cost and after we are done with making the and after we are done with making the cube we also need a distance array which cube we also need a distance array which will be storing our minimum distances in will be storing our minimum distances in K steps that is all you have to do so K steps that is all you have to do so let's move on to the coding part let me let's move on to the coding part let me just zoom it for you just zoom it for you so the coding part is very simple we so the coding part is very simple we will start with creating a vector of will start with creating a vector of what what Vector distance which will be Vector distance which will be initialized with into max value that is initialized with into max value that is approximately infinite in the worst case approximately infinite in the worst case okay and we also need to create our okay and we also need to create our adjacency list with adjacency list with appear yes or no why appear because appear yes or no why appear because we need to store the vertices and the we need to store the vertices and the cost both we have to store so we will cost both we have to store so we will initialize our adjacency list like this initialize our adjacency list like this that is pair of end comma end that is pair of end comma end adjacency list so this is our address adjacency list so this is our address incidence and to convert this adjacency incidence and to convert this adjacency list and using these points we will make list and using these points we will make a graph how we do that we run a loop for a graph how we do that we run a loop for vector and and up to where flights flights is our array then what we will do we will initialize in Q is equal to Vector 0 that means starting point then end V is equal to vex 1. that is the destination now after that you will initialize int cost is equal to back 3 that is the cost to travel there and as it is a directed graph you will also need to push the relation adjoint U push back you will push the pair B comma cost you are showing the vertices and the cost that is what I told you in the examples and after that you simply have to apply the BFS for BFS you need to create a queue usually you create a q normal but in this case you need to create a pair of q y pair of Q because you are storing two values the vertices and cost and this in this question you will not create a visited array because there are multiple ways possible to visit a single array and you are comparing all of them to get the cheapest so you will not create a visited array in this case so now what you have to do you have created a cube pair vector and the distance from Source will be and the distance from Source will be zero so you will make the distance of zero so you will make the distance of source to zero and then you will source to zero and then you will initialize our steps which will count initialize our steps which will count the number of K steps possible that is the number of K steps possible that is number of stops number of stops now after that you simply write the BFS now after that you simply write the BFS code what is it while Q is empty and code what is it while Q is empty and what I told you we will also make sure what I told you we will also make sure that steps is less than equal to K we that steps is less than equal to K we should not exceed our steps and then we should not exceed our steps and then we will initialize n10 is equal to Q dot will initialize n10 is equal to Q dot size size while and negative and we will decrement while and negative and we will decrement and that is we are popping element from and that is we are popping element from our queue our queue how we will pop elements we will how we will pop elements we will initialize the front element as the initialize the front element as the first first and we will initialize our distance to and we will initialize our distance to the second that is the cost distance or the second that is the cost distance or cost whatever you want to say let's cost whatever you want to say let's denote it as D it is our second in the denote it as D it is our second in the queue and then we will pop our Q queue and then we will pop our Q after popping the cube we will start after popping the cube we will start iterating in another loop for iterating in another loop for we generally do for end we generally do for end and V2 at joint U but in this case we and V2 at joint U but in this case we are having pair so we will iterate in are having pair so we will iterate in pair pair end comma it so data type will pair pair end comma it so data type will be Parent Command and let's change it to be Parent Command and let's change it to P for better understanding and now P for better understanding and now when we are iterating to our it's all when we are iterating to our it's all adjacent what we will do we will adjacent what we will do we will initialize our B to P DOT first what initialize our B to P DOT first what does it indicate the next iteration the does it indicate the next iteration the next one and we also need to get the next one and we also need to get the cost cost will be P dot second that's cost cost will be P dot second that's what you have to do and if the distance what you have to do and if the distance of V is greater than D Plus cost that is of V is greater than D Plus cost that is the distance is greater then we are the distance is greater then we are updating it to cheaper distance that is updating it to cheaper distance that is what we told you so we will update it to what we told you so we will update it to cheaper distance distance distance B is cheaper distance distance distance B is equal to equal to D Plus cost and when you are done with D Plus cost and when you are done with this you will push it in the queue to this you will push it in the queue to check its corresponding paths the New check its corresponding paths the New Path which it is providing we will push Path which it is providing we will push V comma V comma distance B because it is updated distance B because it is updated and when you are done with this Loop and and when you are done with this Loop and when you are starting again the when you are starting again the again the BFS call we will increment our again the BFS call we will increment our steps steps that way you can exit the final BFS when that way you can exit the final BFS when it exceeds the amount of K possible so it exceeds the amount of K possible so this is all you have to do and when you this is all you have to do and when you are done with the DFS you will check are done with the DFS you will check back there back there in the distance array the source is in the distance array the source is still index if it is still into max that still index if it is still into max that means we did not find any way to reach means we did not find any way to reach it so we will return it so we will return -1 -1 and if it is not in into max we will and if it is not in into max we will return our distance of destination DST return our distance of destination DST it should also be destination not source I hope it is clear let's just run it and um expected okay um expected okay we missed this we missed this now it should work P dot fast P dot fast there should not be some columns there should not be some columns brackets uh integer overflow we have written it zero one two zero base indexing no not one two three it should work now yeah it is working so this is all you have to do let's just so yeah it is accepted so yeah it is accepted so to briefly with the overall approach so to briefly with the overall approach we simply had to apply the BFS we need we simply had to apply the BFS we need to create a distance array to store the to create a distance array to store the distances and while making the adjacency distances and while making the adjacency list we was passing the vertices along list we was passing the vertices along with the cost so we can compare the cost with the cost so we can compare the cost and get the minimum so the time and get the minimum so the time complexity in this case will be o e into complexity in this case will be o e into n and also we are running a loop for n and also we are running a loop for this so it will be what this so it will be what o e into n o e into n plus o n plus o n so that would be our time complexity so that would be our time complexity ultimately it is O A into n and space ultimately it is O A into n and space complexity will also be the same complexity will also be the same so if you have any other doubt please so if you have any other doubt please let me know in the comment section let me know in the comment section please try to do this question on your please try to do this question on your own thank you so much for watching own thank you so much for watching please like share and subscribe bye bye | 2024-03-21 16:52:15 | 787 | 787 Leetcode | Cheapest Flights Within K Stops | DSA buddy | BFS line by line Approach |
|
aEH0SOHb3Rc | foreign [Music] problem which is to rotate an image here a two-dimensional array or a matrix is referred as a image from the problem we can see that the size of the Matrix is given as n by n which means it is a square Matrix and our task is to rotate the square Matrix with an angle of 90 degrees in clockwise Direction if you assume this circle has a clock and the direction shown by the screen color is the to understand it better let's see with to understand it better let's see with an example an example let this blue color Matrix with the let this blue color Matrix with the input Matrix and we are going to rotate input Matrix and we are going to rotate this input Matrix with an angle of 90 this input Matrix with an angle of 90 degrees in clockwise direction that degrees in clockwise direction that means we are going to rotate like this means we are going to rotate like this that means the position of 7 here that means the position of 7 here will be finally settled down at here will be finally settled down at here so the output Matrix will be something so the output Matrix will be something like this 4 1 9 6 3. 9 6 3. till now I think we are clear with the till now I think we are clear with the problem and let's see how we can solo problem and let's see how we can solo this this we are going to solve this problem by we are going to solve this problem by performing two simple steps first step performing two simple steps first step is to perform a transpose to the given is to perform a transpose to the given Matrix transpose of a matrix is nothing Matrix transpose of a matrix is nothing but interchanging of its rows into but interchanging of its rows into columns or it columns into rows that columns or it columns into rows that means means this is a given Matrix this is a given Matrix and and we apply transpose to the given matrix we apply transpose to the given matrix by interchanging its column to the row by interchanging its column to the row that means that means the first column in the given Matrix the first column in the given Matrix will be the first row in the transpose will be the first row in the transpose Matrix that means one Matrix that means one four and seven and the second column in four and seven and the second column in the given Matrix will be the second row the given Matrix will be the second row in the transpose Matrix that means 2 in the transpose Matrix that means 2 5 and 8. similarly the Third six and nine and now we are going to reverse this transposite Matrix in order to get the 90 degrees rotated Matrix the reverse of this transposite Matrix will be our required Matrix that means let's fill this transposing Matrix which is 1 4 7 2 5 8 3 6 9. right so this transposite Matrix should be reverse that means the last column will be transferred to First and the First Column will be transferred to last that means the result Matrix will be 7 four and one and it is eight five and two and it is 9 6 and 3. Now using this logic try to write some code on your own and then come back to check the solution this is the implementation of the logic we discussed here we are taking two sets of nested for loops right and in which one nested for Loop is going to use to find out the transpose of the given Matrix and the other nested for Loop is used to get the reverse of the given transposite Matrix to understand how the transpose of Matrix is happening let's check for the case of I is equal to 0. if I is equal to 0 then J is equal to 0 plus 1 that means J is equal to 1. and the temporary variable which stores the value of Matrix of 0 and 1 which is 2. the value inside the temp will be and then and then The Matrix The Matrix I of J that means the Matrix 0 1 that I of J that means the Matrix 0 1 that means that position of 2 will be swapped means that position of 2 will be swapped with the position of j i that means 1 0. with the position of j i that means 1 0. that means of of I I and J will be equal to and J will be equal to the number and and The Matrix of j i that means will be equal to the value of term that means it is 2. and hence the positions of 0 1 and 1 0 are swapped similarly all the elements all the other elements are also transposed and finally we get the transpose of the given matrix by the end of this for Loop now we are going to reverse the columns in The transposite Matrix when I is equal to 0 the First Column elements are swapped with the last column elements that means the XYZ values are swapped with the last column elements of this three by three Matrix and when I is equal to 1 the First Column the second column elements are swapped with the N minus front column elements and this process will be repeated till I is less than I is equal to Matrix dot length by 2. that's it and we'll after the end of this for Loop we'll get the reverse of the transposite Matrix which is our desired rotated image of the given Matrix [Music] | 2024-03-20 09:45:16 | 48 | Rotate Image Problem on LeetCode(#48) : A Step-by-Step Guide |
|
0gOUxVKFv74 | Hello whom I am Amrita welcome back to our channel technologies so this is lead code channel technologies so this is lead code series in which will be solving lead code series in which will be solving lead code problems one by one if you also wish to solve it jump problems then you can join us and subscribe to our channel and also wish to solve it jump problems then you can join us and subscribe to our channel and also press press press Notification So Nine Let's Move Ahead With Today's Problem Today C Will Be Solving Problem Number 917 Date Is Reverse Only Letter So Let's Get Started Let's First Understand D Problem Given An String S Reverse D String According To The Basically C Need You Basically C Need You Basically C Need You Reverse D String But C Need You Follow D Reverse D String But C Need You Follow D Rules So What Are D Rules Rule Number Van Rules So What Are D Rules Rule Number Van Date Is All The Characters Date Are Not Date Is All The Characters Date Are Not English Letters Remain In D Se Position And English Letters Remain In D Se Position And All D English Letter Should Be Reverse So All D English Letter Should Be Reverse So Basically C Just Need Basically C Just Need Basically C Just Need letters and other respect characters date is not an English letter it should be remaining in D se position in D example you can see R string is now hyphenated CD so the and C is reverse de hyphen remains R D se And A Correct Nine Let's And A Correct Nine Let's And A Correct Nine Let's Understand Ho C Are Going To Solve This Problem Understand Ho C Are Going To Solve This Problem So Let's Safe C Have You Reverse Only So Let's Safe C Have You Reverse Only Simple String Let's C Have All The Simple String Let's C Have All The English Letters Ho Do C Swap It What Is English Letters Ho Do C Swap It What Is D Reverse Swing Date Would B C Be A D Reverse Swing Date Would B C Be A Correct So Correct So Correct So and D First Letter Becomes D Last Letter Basically C Keeps Wepping D Characters First with D Last Second One with D Second Last and If There is a Third One Date Would Be with D Third Last Letter End Till C Position correct but nine in this Position correct but nine in this Position correct but nine in this case let's say if c have a string like this case let's say if c have a string like this now = c question mark the end hyphen now = c question mark the end hyphen tell characters which are the English letters correct so for date what are you going to do see will take tu pointers where would be Pointer And Andar Van Wood B Pointer And Andar Van Wood B Pointer And Andar Van Wood B Pointer End And Let's Break It In D Pointer End And Let's Break It In D Steps So What Would Be D Step Number Steps So What Would Be D Step Number Van Science C Have You S Only D English Van Science C Have You S Only D English Letters Will Be Checking Weather Both Are English Letters Will Be Checking Weather Both Are English Letters Okay So Let's Say If Start It Letters Okay So Let's Say If Start It Not An Not An Not An start position and just writing it start tu represents if character comes from start position it is not an English letter give what do see need do see don't need do anything see just have to move you Character Right Give C Have You Character Right Give C Have You Character Right Give C Have You Just Increment D Start Index Too Just Increment D Start Index Too Move To D Next Character Similarly Next Will Be Move To D Next Character Similarly Next Will Be Checking If Character Ate D Checking If Character Ate D End Position Is Not A Letter Give Also C Have End Position Is Not A Letter Give Also C Have You Just Move To D Next Character You Just Move To D Next Character Date Mains Dicrement The End Index Date Mains Dicrement The End Index Date Mains Dicrement The End Index letters give that many characters what do you need you give that many characters what do you need you just swap d letters and after just swap d letters and after swapping what do you need do you swapping what do you need do you move d next character from both d move d next character from both d sides date mains increment d starting For example firstly you are checking if start is not a letter but start is a letter so this becomes false give check and this is not a letter yes date is true so move on to d next character so date mens Next And This Next And This Next And This Becomes Your End Index Correct So Becomes Your End Index Correct So This Will Be Taste So Date Mens Di Is Your Ate This Will Be Taste So Date Mens Di Is Your Ate First Position And Ate D Second Last First Position And Ate D Second Last Position Because Hiffin Remand D Se Science Position Because Hiffin Remand D Se Science It Is Not An English Letter C Just Move To D It Is Not An English Letter C Just Move To D Next Character Next Character Now You Want so date mains de will be swapped correct so when de will be swapped come come your second position and be come this position this remains come de se position second position and be come this position this remains come de se position correct nine correct nine move on tu de middle van det mens you increment your move on tu de middle van det mens you increment your start start start Start And And Are Not Letters So Date Mens It Remand D Say So This Would Be Your Reverse String Correct Reverse String So This Is Ho You Need To Solve This Problem Now Let's Try D Solution For It So This Is Un Class Date Reverse only letters nine let's try d Reverse only letters nine let's try d Reverse only letters nine let's try d method date would be public static it is method date would be public static it is going to be written d string so date mains it would be string going to be written d string so date mains it would be string reverse only letters reverse only letters and what would be the input would be your string and what would be the input would be your string so nine Firstly what do so nine Firstly what do you need to do you need to do you need to do van not b your start in next date would be start less den and what would be the start less den and what would be the first step they need to first step they need to check wether your character at the start check wether your character at the start index it is not a letter den c have tu move tu d Next Character So Date Mains Increment Your Start In Dex Just Check Your Character And The End Index Date Is Not A Letter Then If You Have To Move To D Next Character So Date Mains Decrement Your End Index And If Both Are Letters Then What Do C need tu swap both d C need tu swap both d C need tu swap both d characters and move tu d next character from both d characters and move tu d next character from both d sides ho do c rapid let's sides ho do c rapid let's take a temporary variable take a temporary variable ch a start index and chs start ch a start index and chs start index is equals tu ch at chs and equals tu temporary if you do Ho to swap d's letters and other Ho to swap d's letters and other Ho to swap d's letters and other numbers c have a separate video on date I will mention numbers c have a separate video on date I will mention d link in d description d link in d description box you can check it out and then box you can check it out and then after stopping move to d next character from both after stopping move to d next character from both d side date mains increment your d side date mains increment your start index and decrement start index and decrement start index and decrement give index correct so come the end see can say write new string ch it tu de string because see need you write de reverse string let's go back tu me function end let's take de say in footage now hiffin cd app see app see need you for watching | 2024-03-25 10:56:24 | 917 | Reverse only letters | Leetcode 917 |
|
kBrTtpMFmjs | hello everyone welcome to clashing coder so in this video we will see the so in this video we will see the question 452 question 452 that is minimum number of arrows to that is minimum number of arrows to burst balloons so it is a medium level burst balloons so it is a medium level question and it is also sometimes asked question and it is also sometimes asked in interviews also in interviews also so let's see the problem statement there so let's see the problem statement there are some spherical balloons are some spherical balloons spread in two dimensional space or 2d spread in two dimensional space or 2d space you can say where x and y space you can say where x and y coordinates are there coordinates are there so for each well whom provided input is so for each well whom provided input is the start and end coordinates of the the start and end coordinates of the horizontal diameter horizontal diameter that's mean that means that you can see that's mean that means that you can see this line so this line is actually this line so this line is actually horizontal you can see horizontal you can see so its diameter is given the diameter or so its diameter is given the diameter or the width of the balloon is given the width of the balloon is given since its horizontal y coordinates does since its horizontal y coordinates does not matter so that means we will not not matter so that means we will not take the the y coordinates into take the the y coordinates into consideration because all the balloons consideration because all the balloons will lie into will lie into like y is equal to 0 for them so x will like y is equal to 0 for them so x will only change only change so hence the x coordinates of the start so hence the x coordinates of the start and the end of the diameter surface and the end of the diameter surface so the start is always smaller than the so the start is always smaller than the end so yes it will be true because end so yes it will be true because the starting point will be always the starting point will be always smaller than the end then only it will smaller than the end then only it will form the diameter otherwise it will be form the diameter otherwise it will be uh different so an arrow can be shot up uh different so an arrow can be shot up exactly vertically exactly vertically from different points along the x-axis from different points along the x-axis so so it means that exactly exactly vertically it means that exactly exactly vertically because we are not considering the y because we are not considering the y axis so axis so we can uh assume that the arrow is also we can uh assume that the arrow is also fired or fired or like i triggered from the same vertical like i triggered from the same vertical position that is y is equal to zero you position that is y is equal to zero you can suppose that can suppose that a balloon with x start and x and burst a balloon with x start and x and burst by an arrow short at x if x start by an arrow short at x if x start is less than equal to x and less than is less than equal to x and less than equal to x equal to x and that means that our x that we are and that means that our x that we are shooting shooting so we are not considering the y axis so so we are not considering the y axis so we are only considering the x axis we are only considering the x axis so if it in uh like uh if like that so if it in uh like uh if like that makes me new actually makes me new actually so in this you can see in this i will so in this you can see in this i will explain you so this explain you so this is the diameter of a balloon that we are is the diameter of a balloon that we are given and we have to given and we have to burst it using the arrow so when we fire burst it using the arrow so when we fire a arrow so this is the start x start a arrow so this is the start x start sorry for the handwriting because i'm sorry for the handwriting because i'm using the mouse so you can using the mouse so you can please uh you can copy that so you can please uh you can copy that so you can see this other starting and see this other starting and end point so our arrow should only be uh end point so our arrow should only be uh arrow can only burst the balloon arrow can only burst the balloon if it passes between these it should be if it passes between these it should be lying between these okay the x should be lying between these okay the x should be lying between these lying between these it cannot lie uh here because if the it cannot lie uh here because if the arrow is fired from here arrow is fired from here so it will not burst the boom so that so it will not burst the boom so that means these are the means these are the like constraints that x should always like constraints that x should always lie between x start and accent that lie between x start and accent that means the diameter or the width of the means the diameter or the width of the balloon balloon there is no limit to the number of there is no limit to the number of arrows that can be shot an arrow once arrows that can be shot an arrow once shot keeps traveling up infinitely so shot keeps traveling up infinitely so that means that if arrow that means that if arrow like burst one balloon okay from here like burst one balloon okay from here then it may also then it may also like not stop and it will also burst the like not stop and it will also burst the next boom if it comes in its way next boom if it comes in its way so that is what it's trying to say so so that is what it's trying to say so given an array uh points where the given an array uh points where the points i points i is equal to points start and end so that is equal to points start and end so that means we are given the means we are given the element as pair of values start and end element as pair of values start and end return the minimum number of arrows that return the minimum number of arrows that must be short must be short to the to burst all the balloons so to the to burst all the balloons so actually if you see the problem actually if you see the problem statement statement it is kind of similar to merge intervals it is kind of similar to merge intervals so actually so actually if you haven't solved that problem in if you haven't solved that problem in lead only it is a problem so i will lead only it is a problem so i will provide you the link in the description provide you the link in the description or in the i button also so you should or in the i button also so you should try to solve the question and i've try to solve the question and i've posted a video in that also you should posted a video in that also you should try to understand the solution from try to understand the solution from there there if you are not able to solve so that if you are not able to solve so that will like save a lot of time and you will like save a lot of time and you will end up having will end up having a solution for this problem also this is a solution for this problem also this is almost similar to that problem almost similar to that problem so the concept that we are going to use so the concept that we are going to use here will be similar to that merge here will be similar to that merge intervals intervals so i i hope you should see that okay so so i i hope you should see that okay so for these these are the examples that for these these are the examples that are given so actually uh you can see are given so actually uh you can see these are the base cases if you want to these are the base cases if you want to like first of all see the base cases so like first of all see the base cases so if you are given one element only or one if you are given one element only or one this input only so that means you have this input only so that means you have only one rune so you need one arrow only only one rune so you need one arrow only because you need at least one arrow to because you need at least one arrow to burst balloon zone burst balloon zone so at least one so you can simply return so at least one so you can simply return one if element is one if there is no one if element is one if there is no element only no balloons element only no balloons that means you rotate an arrow you can that means you rotate an arrow you can return zero so these are some constraint return zero so these are some constraint also you can see also you can see points length will lie between zero to points length will lie between zero to ten to square four and points ten to square four and points length that means the pair or you can length that means the pair or you can say start or end where it is of length say start or end where it is of length two two every element and these are just some every element and these are just some constraint for x so it will lie between constraint for x so it will lie between minus 2 to power minus 2 to power 31 to 2 power 31 minus 1 okay so these 31 to 2 power 31 minus 1 okay so these are some constraints so let's see the are some constraints so let's see the example example so actually this is the example that so actually this is the example that we're given you can see this is the we're given you can see this is the first example that we are given first example that we are given and here the output is two and let's see and here the output is two and let's see how that output is two how that output is two actually as i told you let me draw this actually as i told you let me draw this line as i told you line as i told you we are not considering any vertical axis we are not considering any vertical axis so we are only considering if the blues so we are only considering if the blues is here so it is actually like this the is here so it is actually like this the balloon is like this balloon is like this it is not having any vertical or it is not having any vertical or vertical coordinates it is only having vertical coordinates it is only having horizontal coordinates that are start horizontal coordinates that are start and the end point and the end point so let's see how we can solve this so if so let's see how we can solve this so if you see this spoiler point so you see this spoiler point so then uh for example you can see the then uh for example you can see the minimum value here is 1 so the line is 1 minimum value here is 1 so the line is 1 and the maximum is 16 so this will be 16 and the maximum is 16 so this will be 16 if you see this balloon so it is of if you see this balloon so it is of radius uh you can see six and uh radius uh you can see six and uh diameter six diameter six and it is starting from 10 so exactly 16 and it is starting from 10 so exactly 16 is here so you can suppose n is here is here so you can suppose n is here so 10 and it is going to okay sorry for so 10 and it is going to okay sorry for the writing actually the writing actually it is going till six so the 16 so that it is going till six so the 16 so that means the plume is off with this you can means the plume is off with this you can see this is the fifth of balloon so that see this is the fifth of balloon so that means we need one arrow to burst it okay means we need one arrow to burst it okay we need one arrow to burst it we need one arrow to burst it now if you see this two and eight so now if you see this two and eight so this is another balloon this is another balloon so it is two and eight so two will be so it is two and eight so two will be somewhere here and it will be the system somewhere here and it will be the system so it will be you can suppose so it will be you can suppose here so now you can see these balloons here so now you can see these balloons are not overlapping are not overlapping so as it is written that arrow will so as it is written that arrow will travel infinitely after bursting the travel infinitely after bursting the balloon also balloon also so if one balloon lies here and this one so if one balloon lies here and this one is here arrow passes through the race is here arrow passes through the race so it is merging or you can see so it is merging or you can see overlapping this is overlapping with overlapping this is overlapping with this so arrow will also burst this this so arrow will also burst this balloon but balloon but in this case you can see this balloon is in this case you can see this balloon is not overlapping with this balloon so we not overlapping with this balloon so we require two arrows you can see require two arrows you can see if we was this there is no chance that if we was this there is no chance that this will uh this building also will this will uh this building also will burst burst so you have to require you will require so you have to require you will require two arrows you can see this will require two arrows you can see this will require uh the different arrow now if you see uh the different arrow now if you see one and six so one way one is here one and six so one way one is here six will be eight is around here so six six will be eight is around here so six will be around here so i'm just will be around here so i'm just supposing so okay supposing so okay this will be the another one you can see this will be the another one you can see so now this is the first balloon this so now this is the first balloon this one one down one here okay and this is the down one here okay and this is the second balloon now if you see arrow second balloon now if you see arrow passes from this point so it will end up passes from this point so it will end up bursting the both the balloons so we bursting the both the balloons so we require two arrows for now also require two arrows for now also this is for this balloon and this arrow this is for this balloon and this arrow will burst two balloons off you see this will burst two balloons off you see this seven and twelve so seven will be around seven and twelve so seven will be around here eight is here so seven is here six here eight is here so seven is here six is this is this okay seven and twelve two so twelve will okay seven and twelve two so twelve will be around here be around here so now if you see if you see seven or so now if you see if you see seven or twelve so it can be busted by po twelve so it can be busted by po uh by this room you can see this because uh by this room you can see this because here if you try to uh use this arrow here if you try to uh use this arrow okay so it will not burst this balloon okay so it will not burst this balloon so to burst this balloon so to burst this balloon it will we will have to pass a point it will we will have to pass a point between this okay this arrow would it between this okay this arrow would it will be will be like let me change this color so one like let me change this color so one arrow will be passing from here and one arrow will be passing from here and one arrow you can see these are overlapping arrow you can see these are overlapping okay these balloons are overlapping so okay these balloons are overlapping so if you pass one arrow from here so you if you pass one arrow from here so you will require will require at low at me at least or you can say at at low at me at least or you can say at max two arrows only to burst all the max two arrows only to burst all the balloons so this is what our problem is balloons so this is what our problem is trying to say trying to say so we have to output the minimum number so we have to output the minimum number of arrows required to burst all the of arrows required to burst all the balloons balloons and we have to actually merge the and we have to actually merge the intervals or you can say these are intervals or you can say these are intervals uh i will intervals uh i will recommend you to watch the video that i recommend you to watch the video that i will show you in the uh the info button will show you in the uh the info button you can check it from there you can check it from there afterwards uh before watching this video afterwards uh before watching this video actually so you can see we have to merge actually so you can see we have to merge these intervals if you see these intervals if you see we can let me erase this so we are given we can let me erase this so we are given this okay so we are actually this okay so we are actually trying to merge these sequences if this trying to merge these sequences if this is 10 and 16 is 10 and 16 okay 10 and 16 is there now is there any okay 10 and 16 is there now is there any sequence which overlaps with 10 and 16 sequence which overlaps with 10 and 16 that means a number becoming between 10 that means a number becoming between 10 and 16 or and 16 or this line comes between some number you this line comes between some number you can see here so you can see can see here so you can see 10 okay 10 and 16 is here and 7 10 okay 10 and 16 is here and 7 and 12 is coming between this 10 and 6 and 12 is coming between this 10 and 6 so that means these this is one balloon so that means these this is one balloon okay this is one room okay this is one room and this is second balloon so you can and this is second balloon so you can see they're overlapping actually see they're overlapping actually so an arrow can burst both of them if it so an arrow can burst both of them if it passes between this seven and twelve so passes between this seven and twelve so it will end up bursting 10 and 16 also it will end up bursting 10 and 16 also so we have to require we need to output so we have to require we need to output the minimum number of arrows required the minimum number of arrows required using this using this technique so let's see the algorithm so technique so let's see the algorithm so actually it is actually it is quite similar to the merge merge quite similar to the merge merge intervals only so you can see intervals only so you can see first we will initialize the count as first we will initialize the count as one because at least we require one one because at least we require one arrow if arrow if we will check the base conditions if we will check the base conditions if there is only one of the balloon then we there is only one of the balloon then we can simply turn one can simply turn one either if there is no balloons we can either if there is no balloons we can return zero otherwise return zero otherwise if it is not the base condition end of if it is not the base condition end of the base conditions we will have to the base conditions we will have to initialize the count as one because we initialize the count as one because we at least require one arrow so we have to at least require one arrow so we have to start with the one start with the one so let me write it so our count will be so let me write it so our count will be at least one okay at least one okay so it will be one then we have to so it will be one then we have to initialize a previous variable also initialize a previous variable also let's see see let's see see what we will do with that but actually what we will do with that but actually if you see in this if you see in this okay so for merging the intervals okay so for merging the intervals actually we cannot merge the intervals actually we cannot merge the intervals till we sort them so we have to sort the till we sort them so we have to sort the array also because we array also because we have to use the greedy approach in the have to use the greedy approach in the merge intervals also we sorted the array merge intervals also we sorted the array so in this we have to sort the array to so in this we have to sort the array to merge the intervals merge the intervals we cannot merge the intervals without we cannot merge the intervals without sorting the array so it is actually a sorting the array so it is actually a greedy approach greedy approach so you can see in this how we can merge so you can see in this how we can merge so we will merge using the ending value so we will merge using the ending value or you can say the end point of the or you can say the end point of the end point or and coordinate of the end point or and coordinate of the balloon or diameter so you can see we balloon or diameter so you can see we will merge will merge or we can we will sort the array using or we can we will sort the array using these elements so let's these elements so let's sort them so you can see here one two sort them so you can see here one two three four and three four and four five and two three so you can see four five and two three so you can see one two so two is smaller one two so two is smaller out of all so we will uh first the out of all so we will uh first the element will coming is element will coming is one and two now again now see which is one and two now again now see which is smallest out of this four smallest out of this four five and three so this three is smaller five and three so this three is smaller so here it will come so here it will come two and three okay now again you can see two and three okay now again you can see the two elements the two elements are only left so this will be smaller are only left so this will be smaller three and four so we'll write simply three and four so we'll write simply three and four so the left over element three and four so the left over element will be four and five so you can see we will be four and five so you can see we have sorted our array have sorted our array using a compare function you can say we using a compare function you can say we will use a compare function and sort it will use a compare function and sort it according to the second value in this according to the second value in this element or this pair element or this pair so this is what we are doing sort the so this is what we are doing sort the first we have to initialize these first we have to initialize these variables and variables that we will be variables and variables that we will be using using then we have to sort the array then only then we have to sort the array then only we will be able to merge them we will be able to merge them so now how we can merge them actually we so now how we can merge them actually we will first of all will first of all we will need account as one so we have we will need account as one so we have initialized account as well now we will initialized account as well now we will start from the second element start from the second element uh in the area or you can say first uh in the area or you can say first element this is the zeroth element so we element this is the zeroth element so we will start from the second element will start from the second element this is where from where we will start this is where from where we will start and we will set our x or you can see and we will set our x or you can see this previous value of t okay i have this previous value of t okay i have written previous okay written previous okay so we'll set the previous value as this so we'll set the previous value as this value value that is two so uh actually okay so i that is two so uh actually okay so i have have not written it so previous value will be not written it so previous value will be actually array of actually array of okay 0 and 1 okay okay 0 and 1 okay this will be what we have to uh this will be what we have to uh initialize this previously with so it initialize this previously with so it will be initialized with will be initialized with actually x is two for this or previous actually x is two for this or previous is two so now we will start our loop is two so now we will start our loop from this point okay you can see from this point okay you can see i is starting from n i one until uh it i is starting from n i one until uh it is running till n is running till n so now if you see our previous value is so now if you see our previous value is this it is not x actually this it is not x actually so sorry for that so actually it is our so sorry for that so actually it is our previous value so now previous value so now if we are at this element and you will if we are at this element and you will check this condition if array of i zero check this condition if array of i zero array of i array of i is this and zero value is this 2 so it is this and zero value is this 2 so it will end up having value 2 will end up having value 2 so you can see here it will be giving 2 so you can see here it will be giving 2 and 2 and 2 is less than equal to previous value is less than equal to previous value that we were having 2 so you can see that we were having 2 so you can see it is actually equal so that means we it is actually equal so that means we will simply will simply continue and don't like skip the steps continue and don't like skip the steps so we will simply continue and skip so we will simply continue and skip these steps these steps so that means that we have found a pair so that means that we have found a pair or pair of numbers which or pair of numbers which are balloons which are actually are balloons which are actually overlapping if you see overlapping if you see this two and two so if we draw this in this two and two so if we draw this in line line in this actually if we draw this line so in this actually if we draw this line so one is here okay one is here okay two is here and three is here so this is two is here and three is here so this is our one balloon our one balloon and sorry this is our one balloon and sorry this is our one balloon actually starting off with two actually starting off with two and this is our second balloon now if we and this is our second balloon now if we pass error through this pass error through this two then we will end up bursting the two then we will end up bursting the both columns so that means they are both columns so that means they are overlapping so we can simply overlapping so we can simply skip this loop and our count variable skip this loop and our count variable will actually return the number of will actually return the number of arrows that we require arrows that we require so our count will not increment it is so our count will not increment it is still one because we can burst these two still one because we can burst these two balloons by one you only balloons by one you only one arrow only so that means we are one arrow only so that means we are skipping this step so now i will come skipping this step so now i will come here here so i will come here now our previous is so i will come here now our previous is still two still two now we will check for this i is this now we will check for this i is this okay i is two okay i is two and for i of two we will check for the and for i of two we will check for the first element first element is 3 first element first element is 3 so now if you check 2 okay this actually so now if you check 2 okay this actually value will be 3 value will be 3 first value will be 3 okay 3 is less first value will be 3 okay 3 is less than this previous value is 2 you can than this previous value is 2 you can see 2 see 2 so 3 is less than equal to 2 so this so 3 is less than equal to 2 so this condition is not true so that means we condition is not true so that means we will have to skip this if will have to skip this if condition and that means this element or condition and that means this element or this balloon this balloon these values are not overlapping so that these values are not overlapping so that means we require means we require a more arrow or require another arrow a more arrow or require another arrow because if you see because if you see okay so now if you see this okay so now if you see this three so okay uh let me draw again one three so okay uh let me draw again one right so excuse me one and two right so excuse me one and two and three and four so one balloon is and three and four so one balloon is over this point one and two over this point one and two another point a balloon is over this another point a balloon is over this point two and three and the last balloon point two and three and the last balloon sorry sorry for the drawing it's actually this so for the drawing it's actually this so this is the last blue this is the last blue so if you see actually uh let me so if you see actually uh let me check here so yes so if you see now check here so yes so if you see now this arrow that we will be requiring this arrow that we will be requiring will be only will be only so where would we so you can see we will so where would we so you can see we will skip this condition so actually we will skip this condition so actually we will have to increment our count have to increment our count okay this three is less than the okay this three is less than the previous so that is not true we will not previous so that is not true we will not uh end up into this condition uh end up into this condition and we will skip it so if we skip it so and we will skip it so if we skip it so for count will become plus plus so the for count will become plus plus so the count was one count was one so it will now become two now you can so it will now become two now you can see a count has become two another see a count has become two another previous value will previous value will update to the next value that we have so update to the next value that we have so actually it will be actually it will be uh i is at this okay i is at this and we uh i is at this okay i is at this and we will update is to four will update is to four so it will be updated to four now you so it will be updated to four now you can see it is updated to 4. now if you can see it is updated to 4. now if you see this 4 see this 4 now we will increment the i to the next now we will increment the i to the next point so it will be here point so it will be here let me draw it carefully so yeah so i let me draw it carefully so yeah so i will be here so i will be here so i is here let me erase this all so now you is here let me erase this all so now you can understand can understand so yeah so now when i is here our so yeah so now when i is here our previous value is 4 previous value is 4 and if you see this 4 is equal to this 4 and if you see this 4 is equal to this 4 okay okay if you in this condition you can see if you in this condition you can see array of i 0 i 0 is 4 array of i 0 i 0 is 4 and our previous value is also 4 4 is and our previous value is also 4 4 is less than equal to 4 this condition will less than equal to 4 this condition will be true actually be true actually so we will simply continue because this so we will simply continue because this four and three these are overlapping four and three these are overlapping actually three four actually three four and four and five these are overlapping and four and five these are overlapping but in this case i but in this case i which i was telling you let me explain which i was telling you let me explain you further so if you see in this point you further so if you see in this point if you see we are if we pass an arrow if you see we are if we pass an arrow from this point yeah these are the from this point yeah these are the merging balloons okay one two that we merging balloons okay one two that we were having you can see one two and were having you can see one two and two three let me draw it here only two three let me draw it here only one okay two and three so now you can one okay two and three so now you can see see this balloon these two balloons can be this balloon these two balloons can be bursted by only one arrow if you pass it bursted by only one arrow if you pass it from the two point from the two point okay two in uh coordinate but if you try okay two in uh coordinate but if you try to pass it from this also this is our to pass it from this also this is our next one so it will be three and four next one so it will be three and four if you see we if we pass uh if we this if you see we if we pass uh if we this is also merging actually this three and is also merging actually this three and four but four but you cannot pass an arrow from this three you cannot pass an arrow from this three and four if you try to pass the arrow and four if you try to pass the arrow from three and four that you won't be from three and four that you won't be able to burst the balloon able to burst the balloon at one and two so that means you can at at one and two so that means you can at least at most least at most merge two will not only over here so you merge two will not only over here so you will require one arrow extra will require one arrow extra for this if one arrow will be required for this if one arrow will be required to burst one and two and two or three to burst one and two and two or three balloons because two is overlapping balloons because two is overlapping and another arrow will be required to and another arrow will be required to burst balloon at three and four but burst balloon at three and four but we will end up having saving more arrows we will end up having saving more arrows because the next because the next balloon which is at four and five it can balloon which is at four and five it can be merged by this point be merged by this point so you can see we were having let me so you can see we were having let me draw again actually draw again actually so this example will be cleared to you so this example will be cleared to you and you will not require to solve any and you will not require to solve any example but i will recommend to you to example but i will recommend to you to solve it once uh yourself solve it once uh yourself this example with using this algorithm this example with using this algorithm so actually you can see we have got a so actually you can see we have got a result for this we have got a result of result for this we have got a result of countable 2 because we have merged this countable 2 because we have merged this you can see this previous will be equal you can see this previous will be equal to or this element so it is equal to to or this element so it is equal to also you can see so it will be also you can see so it will be continuing so continuing so we will be getting our simply the count we will be getting our simply the count we can return the count so 22. you can we can return the count so 22. you can see answer two see answer two but now if you see so this one and two but now if you see so this one and two so suppose one and two is this and so suppose one and two is this and again two and three so two and three is again two and three so two and three is this so we can simply pass the arrow this so we can simply pass the arrow from two from two to point so it will burst two balloons to point so it will burst two balloons so we require one arrow okay so we require one arrow okay now if you see three and four three and now if you see three and four three and four is actually merging with the last four is actually merging with the last balloon balloon but if you see if we pass the arrow from but if you see if we pass the arrow from this three and four this three and four then how we can burst this balloon which then how we can burst this balloon which was first this one and two so we will was first this one and two so we will require require at least two arrows so that's why we are at least two arrows so that's why we are using two now using two now instead of using the arrow here if you instead of using the arrow here if you see this four and five so it will be see this four and five so it will be here coming here here coming here so now we can pass the arrow from here so now we can pass the arrow from here so if we pass these two arrows from here so if we pass these two arrows from here so we can simply burst all the balloons so we can simply burst all the balloons so where our output will be two so i so where our output will be two so i hope you got the algorithm how we have hope you got the algorithm how we have to do it to do it so actually let me explain you the so actually let me explain you the algorithm or give your summary again so algorithm or give your summary again so we have to initialize count s go to one we have to initialize count s go to one because because at least we require one arrow and this at least we require one arrow and this previous will store this value previous will store this value actually so we will have to check if it actually so we will have to check if it is merging with is merging with uh this element the next one or not so uh this element the next one or not so then we have to sort the array according then we have to sort the array according to the to the last value or the end value or the end last value or the end value or the end uh coordinate of the balloon or diameter uh coordinate of the balloon or diameter then we will run a loop from starting then we will run a loop from starting from the one till n from the one till n and we will merge the intervals or we and we will merge the intervals or we can simply uh we will can simply uh we will increment our count only if the last increment our count only if the last value is not merging with the first value is not merging with the first value value if this last value is actually one and if this last value is actually one and the second first value of the this the second first value of the this second element you can say is two so second element you can say is two so these are not merging you can see 10 is these are not merging you can see 10 is one is less than two so it will not one is less than two so it will not merge one is here okay merge one is here okay two is here it will not merge if this two is here it will not merge if this value is actually one so it will be at value is actually one so it will be at the same point the same point if it is zero so you can see zero and if it is zero so you can see zero and one then again one then again we are having zero and three so these we are having zero and three so these are merging you can see we can simply are merging you can see we can simply uh get a common area from them uh get a common area from them so actually if you see the time so actually if you see the time complexity for doing this all will be complexity for doing this all will be only enough log n because we are sorting only enough log n because we are sorting the array for sorting you can see we are the array for sorting you can see we are using the embed function so it will be using the embed function so it will be using merge sort so it will end up using merge sort so it will end up having the time complexity of n log n having the time complexity of n log n so it is uh like efficient also and the so it is uh like efficient also and the space concept space concept complexity only will be one or the complexity only will be one or the constant decrease of one constant decrease of one because you can see we are only using because you can see we are only using some variables to show the values that some variables to show the values that is count and the previous value is count and the previous value other than that we are not using any other than that we are not using any variable so this is only our simple variable so this is only our simple algorithm algorithm and only we have to use the compare and only we have to use the compare function also custom compare because we function also custom compare because we are are having this pair so we have to sort it having this pair so we have to sort it accordingly so let's see the code accordingly so let's see the code actually i will show you the code in the actually i will show you the code in the c plus plus and i will also share this c plus plus and i will also share this code in the description code in the description i hope you like this video and do i hope you like this video and do subscribe this channel also subscribe this channel also let's see the code now so actually if let's see the code now so actually if you see this is our uh main function you see this is our uh main function so this is our compare function let's so this is our compare function let's see the main function first so if you see the main function first so if you see in this function we are given the see in this function we are given the vector of vector end of points vector of vector end of points so we are given the points okay so we so we are given the points okay so we will check if the points or sides is will check if the points or sides is zero that means we don't have any zero that means we don't have any balloon so we can simply return zero balloon so we can simply return zero if we have only one balloon then we will if we have only one balloon then we will require one arrow so we can return one require one arrow so we can return one now this is where we sort our array okay now this is where we sort our array okay we sort our array points or begin and we sort our array points or begin and point sort and point sort and this is our custom compare function this is our custom compare function let's see so uh this is a compare let's see so uh this is a compare function you can see bool function you can see bool a true or not so it will run a true or not so it will run accordingly now you can see we are accordingly now you can see we are having the first element and the second having the first element and the second element element and we have to sort according to the and we have to sort according to the first value or you can say second value first value or you can say second value but this is but this is according to zeroth index so zero will according to zeroth index so zero will be first value and one will be the be first value and one will be the second value so we are sorting according second value so we are sorting according to a to a of one okay a of one will be this two of one okay a of one will be this two and b of one will be this four if we are and b of one will be this four if we are passing this two values passing this two values so it it will check who is less than so it it will check who is less than four so yes it is true so it will add four so yes it is true so it will add into the value accordingly into the value accordingly if it is like four and two okay if we if it is like four and two okay if we are having the first value is four and are having the first value is four and the second value as the second value as two so it will return false that means two so it will return false that means this is not true so it will accordingly this is not true so it will accordingly sort sort and build okay so let's see so we are in and build okay so let's see so we are in uh initializing account variable as i uh initializing account variable as i told you count will be always one told you count will be always one at la at start then we are taking this x at la at start then we are taking this x or that or that that i read out here as previous okay that i read out here as previous okay this will be using for our this will be using for our merging so then we are writing the merging so then we are writing the simple loop it will start from one until simple loop it will start from one until it it it will run till n and if the point it will run till n and if the point merges with merges with x or the previous value and if two x or the previous value and if two balloons are merging so that means we balloons are merging so that means we don't require any any don't require any any arrow for that so we do need not to arrow for that so we do need not to increment any arrow so we will simply increment any arrow so we will simply continue this so it will continue this so it will skip this loop and it will increment the skip this loop and it will increment the i to 2 so now if you check if sometimes i to 2 so now if you check if sometimes fl fl it will not merge so we will increment it will not merge so we will increment our count or the arrow number of arrows our count or the arrow number of arrows accordingly accordingly and we will also update when we count and we will also update when we count the upgrade our arrow so that means we the upgrade our arrow so that means we are not able to merge so we will have to are not able to merge so we will have to update our previous value or the x value update our previous value or the x value also also so then only we will be comparing if you so then only we will be comparing if you keep comparing the two with this four keep comparing the two with this four it will not end up having the all the it will not end up having the all the correct answers correct answers so it will it should be a it should be so it will it should be a it should be like change or updated to the full like change or updated to the full afterwards if we afterwards if we increment this count so let's see and increment this count so let's see and submit this code so at last don't forget submit this code so at last don't forget to this to this return this count so yeah return this count so yeah so let's see so i hope you got this so let's see so i hope you got this solution solution so guys do like this video and subscribe so guys do like this video and subscribe this channel for more such videos thank this channel for more such videos thank you for watching guys you for watching guys so you can see this got submitted thank so you can see this got submitted thank you for watching | 2024-03-22 14:21:49 | 452 | Minimum Number of Arrows to Burst Balloons | Leetcode 452 | Interview Question | C++ |
|
HiuoGkBMJdc | hello friends so today in this video we're gonna discuss a problem from lead we're gonna discuss a problem from lead code problem name code problem name array nesting so i will first tell you array nesting so i will first tell you the problem statement it's still like the problem statement it's still like it's tell that you are given an integer it's tell that you are given an integer array nums where this nums array is array nums where this nums array is actually a permutation of different actually a permutation of different numbers from ranging from zero to n numbers from ranging from zero to n minus one so they are encoding so from minus one so they are encoding so from zero to l minus one there are numbers zero to l minus one there are numbers which are permutation from like zero to which are permutation from like zero to n minus one okay n minus one okay now what you actually have to do here is now what you actually have to do here is you have to you have to find out the longest cycle in this what find out the longest cycle in this what what what i mean by cycle is what what i mean by cycle is let's assume that you choose any index let's assume that you choose any index okay so uh okay so uh let's assume that you choose uh let's assume that you choose uh as you can see in the example this this as you can see in the example this this exact index which is the youth index exact index which is the youth index okay okay so you start from this youth index and so you start from this youth index and then you go to the fifth index which is then you go to the fifth index which is the number at this point so you go to the number at this point so you go to the fifth and edge the fifth and edge which is six now you go to the sixth which is six now you go to the sixth index which is two index which is two okay now you go to the two index which okay now you go to the two index which is this zero is this zero and you again called zero index which is and you again called zero index which is five so as you can see it is forming five so as you can see it is forming like a loop like a loop so you start from this earth index then so you start from this earth index then you go to the fifth then six you go to the fifth then six then so fifth sixth and then go to the then so fifth sixth and then go to the second and then again to the zeroth second and then again to the zeroth index index so we have to find out as you can see so we have to find out as you can see this is a cycle this is a cycle or loop of size four so i have to turn or loop of size four so i have to turn out four out four so you have to find out what is the so you have to find out what is the maximum length cycle in this problem maximum length cycle in this problem now what you can easily understand from now what you can easily understand from two three examples which are given to two three examples which are given to you you that the cycle are isolated from each that the cycle are isolated from each other what i mean by this is let's assume that i have an array and it has different numbers okay i do not write down the numbers but i just tell you that that maybe this is a cycle so i go from this index to this index then this index then this index and then again to the this index stack so as you can see now it cannot happen that for this number i can again go to this index why because see from this number i can go to this index so if this is like this with index it should be two because from this index i should go to two but this cannot happen at this i from this also i can go to two because then it cannot be a competition permutation are unique numbers so it means that this path is not valid i cannot go to the same loop again so it can happen that from this point these two numbers are taken i can go to this point that this point and then back to this point this can be two loops so as you can see what i can easily do in this problem is maintain a visited vector which means that whatever numbers i have already visited because if that number is some sort some part of a loop what i mean by this is let's assume i start from this and i go in this manner and i completed one loop if i come to this point again while it trace like while it trading from left to right i'm going from left to right and checking for every starting point so i haven't taken out a loop from this point so i will go and find out a loop from this point and it ended at this point so it is fine now i take starting from point at this go from this to this and then come back to this point again so it is forming another loop now i come to this point so as you can see this is a part of a loop which i have already traveled because i have traveled this part so i do not have to do it again because if i do it again i will i will get the same loop again so i don't want to do that so it means that i can keep a visited vector whatever numbers i've already seen so that i cannot do it again because it is already a part of a loop which i've already seen so it means that i only have to travel over every number only once because i'm only touching it once while finding out a particular loop and when i find out a loop i actually store that what is the longest loop length and that's the answer i hope you get the point so i can show you the code part now so uh because i want to store whatever points are actually visited so i can make a global biscuit vector because the length is set to a five so just make it 10 to a five plus like 10 to the five plus five okay or ten plus five plus six anything greater than ten percent and this is the maximum length i can get this is the uh nested array function the starter function the length because i have to rotate from left to right so i iterate over from left right for every starting point as you can see and i only do my okay function or this iteration function only when i find out that the particular ith element is not visited if it is not visited i will call this okay function over the starting point which is i and what is the total length i have seen till now which is like zero and i have to also send the array because i have to check that what is the next point to jump on the next point to jump on okay and in the end we just return on maximum how this okey function is calling is if this loop is completed i have to first always write down the base condition in recursive function so the base condition is i have encountered the same number again so it means that i have this is a starting point which is not registered so i will go from this to this this to this this to this when will this recursive function stop this recursive function will stop when i come to the same point again which is always visited so i have already visited out because i start from this point so at this point it should break so it will break when i hit a block which is already visited so as you can see if i've already visited out the visited of that point is equal to one that i have completed my total journey so my total length of this journey is stored in total so i will maximize my total maximum global maximum with this total value and return out of this recursive function else if i haven't come to a point or a block which i've already seen which means that this is a new block so i will first mark it out one that okay i have seen this block now so now from this block i've seen this i will call this recursive function again to the new jump ring position the new jumping position will be the current index i am on find out the value of that so if i'm on the fifth index okay from fifth index what is the number at the fifth index it is telling you three so go to the third index now so my new jumping position will be nums of i okay and you'll just tell the nums again and because i've taken one more number so that total will increment because now my chain has incremented by one position because i've taken the particular number and go to the next question and just that's the recursive question i hope you understand the logic and the code part for this problem if you have any doubts you can mention down i will see in the next one and then keep | 2024-03-20 11:39:42 | 565 | 565. Array Nesting | LEETCODE MEDIUM | DFS | CODE EXPLAINER |
|
4Ftyegg3M-0 | Everybody Gets All the Best Problem Bank Shopping for Giving Relief Victory Procession Half Are Shopping for Giving Relief Victory Procession Half Are Performing in Wave Subscribe Like This Away from You Performing in Wave Subscribe Like This Away from You for Example 814 Subscribe 1234 Turn on the Operation in To-Do List of the Content of This Problem Key tune of from Key tune of from Key tune of from one to the for example 3512 possible one to the for example 3512 possible birthday all end after sending equinox 123 birthday all end after sending equinox 123 that porn so my for elements and that porn so my for elements and 900 episode 354 is on the end right now for 900 episode 354 is on the end right now for is on this index michigan index to is on this index michigan index to visit to take this point to right so visit to take this point to right so visit to take this point to right so one to take this point to the first will move this point to the state of the video clip this point subscribe button to subscribe button to A Position Of And No Way Can Reduce Like A Position Of And No Way Can Reduce Like Beer Beer Can Remove 49 Will Reduce Come To Beer Beer Can Remove 49 Will Reduce Come To This Point To That Electronic Display This Point To That Electronic Display 1653 Subscribe Our Video Clip Of 2312 1653 Subscribe Our Video Clip Of 2312 Subscribe To Floor Mills Subscribe To Floor Mills That 2131 For This Is It A Prank Clip Of That 2131 For This Is It A Prank Clip Of 383 Subscribe 90 Connect subscribe 1234 subscribe 1234 that hence this can be given only solution that hence this can be given only solution situations like his adopted daughter element situations like his adopted daughter element first position and the element subscribe first position and the element subscribe also maximum to the like subscribe to subscribe also maximum to the like subscribe to subscribe and subscribe the and subscribe the amazing Internet Thursday From Noida Plus amazing Internet Thursday From Noida Plus App App that this offer is equal to target that this offer is equal to target that this offer is equal to target return diary don't want the tarzan - subscribe video subscribe video like share and subscirbe from 0 to sleep sleep will start from this will money aghi na af plus plus 2 f ki jan26 - - beerwah to elements and monitor person then subscribing element Like Subscribe Class 9 Widely Like Subscribe Class 9 Widely Like Subscribe Class 9 Widely Loud Subscribe comment and subscribe the 102 209 First Will Find Index of the This Element Current Element By Calling Different Method Subscribe 125 Wishes Answer Is Not Subscribe 125 Wishes Answer Is Not Clearly No Problem No Will Be Reduced Clearly No Problem No Will Be Reduced Values in this will start at one end and Values in this will start at one end and research will be plus way from list daughter and will return research will be plus way from list daughter and will return all the subscribe button to subscribe must subscribe must that and a maximum clear doing hair to that and a maximum clear doing hair to star till lips chief min hair to start and star till lips chief min hair to start and end space end space end space Like and subscribe to receive notifications | 2024-03-25 14:08:56 | 969 | pancake sorting leetcode | leetcode 969 | selection sort approach |
|
h_1ZYPGj9IE | guys welcome back to my channel the goal of my channel is to go through every of my channel is to go through every lead code SQL questions with you and to lead code SQL questions with you and to support you in the interview preparation support you in the interview preparation process and future work and I'm going to process and future work and I'm going to resolve every L code sqle question in a resolve every L code sqle question in a systematic way I have five magic steps systematic way I have five magic steps here I listed them here step one is to here I listed them here step one is to define the result table and the columns define the result table and the columns step two is based on the result table we step two is based on the result table we can identify the relevant tables needed can identify the relevant tables needed and step three is based on the relevant and step three is based on the relevant tables we identified in step two we need tables we identified in step two we need to find a correct way to join the tables to find a correct way to join the tables together it it could be left join right together it it could be left join right join inner join or outer join and step join inner join or outer join and step four is after step one 2 3 or we already four is after step one 2 3 or we already have a preliminary table but step four have a preliminary table but step four is way further filter the unnecessary is way further filter the unnecessary roles based on the condition so step roles based on the condition so step four is to filter out unnecessary rows four is to filter out unnecessary rows based on the condition and the last step based on the condition and the last step is to sort the table if the legal CLE is to sort the table if the legal CLE question requires you to do so okay here question requires you to do so okay here are the five steps and I'm going to go are the five steps and I'm going to go through the 1757 question with you through the 1757 question with you following the five steps so in following the five steps so in 1757 when we have only one table the 1757 when we have only one table the table has three columns product ID low table has three columns product ID low fats and recyclable product ID is the fats and recyclable product ID is the primary key of the table so it's a primary key of the table so it's a unique identifier of the table and the unique identifier of the table and the type of it is integer and low fast is a type of it is integer and low fast is a enum category is a enum uh variable so enum category is a enum uh variable so enum means categorical variable it has enum means categorical variable it has the value Y and N so the field low fats the value Y and N so the field low fats only only have two values available it's only only have two values available it's either y or n and the third column is either y or n and the third column is the recycle recyclable which is very the recycle recyclable which is very similar to the low fats it's an enom similar to the low fats it's an enom variable with the type Y and N here y variable with the type Y and N here y means the product is recyclable and N means the product is recyclable and N means it is not so the question require means it is not so the question require us to write a solution to find the IDS us to write a solution to find the IDS of products that are both low fat and of products that are both low fat and recyclable so following the steps here recyclable so following the steps here step one Define the result table the step one Define the result table the result table is the IDS of the products result table is the IDS of the products and we know the column is only one and we know the column is only one column it is the ID of the products so column it is the ID of the products so we can write it we can write it select select product ID and step two is to identify product ID and step two is to identify the relevant tables needed and step two the relevant tables needed and step two we only since we only have one table uh we only since we only have one table uh products products table so we know the products products table so we know the products table is our relevant products table is our relevant table from products and we can skip the table from products and we can skip the steps three since we only have one table steps three since we only have one table and step four we are going to filter and step four we are going to filter rows based on the condition in this rows based on the condition in this question we are going to find the IDS of question we are going to find the IDS of the products that are both low fat and the products that are both low fat and recyclable so low fat and recyc are the recyclable so low fat and recyc are the conditions of the result Pap we can use conditions of the result Pap we can use the low fats column to filter out uh the the low fats column to filter out uh the rows so when low fat is y that means the rows so when low fat is y that means the product is low fat so we can put our product is low fat so we can put our wear condition here wear low fat equal wear condition here wear low fat equal to to Y and another condition is recyclable so Y and another condition is recyclable so recyclable is an enom variable of types recyclable is an enom variable of types Y and N where y means the product is Y and N where y means the product is recyclable so we can put the second recyclable so we can put the second condition here recycle LEL equal to condition here recycle LEL equal to Y and the last step is to sort the table Y and the last step is to sort the table if needed in this question uh we can if needed in this question uh we can return the table result table in any return the table result table in any order so we don't have to sort it so we order so we don't have to sort it so we finished our five steps and here is our finished our five steps and here is our result then let try to run result then let try to run it okay it's correct and let's submit it okay we got the result and we passed the test okay here is our video today and happy coding see you next | 2024-03-22 12:08:26 | 1,757 | Leetcode SQL Questions - Leetcode 1757 |
|
JRqDwT_n7AE | guys, once again welcome to guys, once again welcome to all of you in the video of Tier-3 Daraz on your YouTube channel. The all of you in the video of Tier-3 Daraz on your YouTube channel. The list has a very list has a very interesting question and the interesting question and the logic of the question is logic of the question is applicable in many ransom cars. applicable in many ransom cars. applicable in many ransom cars. is Find the Maximum Hypnotized Triangle No Rajasthan So basically it is a metric life, it is understood on the white board that it is a metric life and in that matrix what has been told to us that tell us the maximum which is garlic and Yes, meaning, now it Yes, meaning, now it Yes, meaning, now it can be of any color, it can be of this whole, of this, of this, can be of any color, it can be of this whole, of this, of this, of this, sometimes, it has of this, sometimes, it has become the Everest Canto of a thing, whose face has to be become the Everest Canto of a thing, whose face has to be told in this type, how much is the maximum, told in this type, how much is the maximum, which is garlic and request. which is garlic and request. which is garlic and request. you have missed it, we will tell you okay, there is no problem, so now to do this, between two, yes, we can do this, we can generate a private address in a way, can generate a private address in a way, take milk in which we can now let us do what we can do. take milk in which we can now let us do what we can do. Our top most coordinator will Our top most coordinator will start it loudly and it will change every time, start it loudly and it will change every time, like first this, then like first this, then this, then this, okay sister, we will still take the prostate type here, then here, then here, then here, here, here. we will still take the prostate type here, then here, then here, then here, here, here. B Hydration will be B Hydration will be completed, we will change our top most cord completed, we will change our top most cord from where from where we will strengthen the prostate roots here, we will make it on zero command1 we will strengthen the prostate roots here, we will make it on zero command1 and then do the same process that once we and then do the same process that once we placed our bottom coordinate or then placed our bottom coordinate or then placed it here then placed it here again or placed it here then placed it here again or placed it here then placed it here again or here again placed here Similarly Top Most Prominent Considering this cord as a toss all those placed in front of those whose request is handled the maximum has been picked up Time Process for this This will This will This will make this the top most medical brother, make this the top most medical brother, giving respect to life here, then this giving respect to life here, then this day, this one, this one, this one, this one is fine, day, this one, this one, this one, this one is fine, similarly, we or this one has become the top most, similarly, we or this one has become the top most, after that we will make this one the top most, from here after that we will make this one the top most, from here this one and this one, then this one will become this one and this one, then this one will become this one and this one, then this one will become made, if this will be made then the top most prominent martyrs will keep on doing this and internally we are supporting it because we need 100 grams internally also, if we put the loop then the time complexity will increase a lot, so that's why Even if we make it and Even if we make it and Even if we make it and tell us about this region that Sri Lanka is all over, it is the tell us about this region that Sri Lanka is all over, it is the evening of this region, then what should I do, from the entire time of this region till here - make it up to here - add it and add Why should I do it because it Why should I do it because it Why should I do it because it became the subject twice, once when became the subject twice, once when we all tweeted from here to here, this area we all tweeted from here to here, this area also got included in it, then when we also got included in it, then when we selected the word 'Kasam' which is from here to here, selected the word 'Kasam' which is from here to here, then this sexual thing was improved again. then this sexual thing was improved again. then this sexual thing was improved again. reason for having two boring roads is that we had to keep it once whereas if it is done twice then I will add it once so below this, what can we say and our coordinator for any coordinator access oil if this Live without you want to listen to Live without you want to listen to Live without you want to listen to do, if we want do, if we want this rectangle, then what will it go to the this rectangle, then what will it go to the whole, understand who will be the training From here to here the whole will be From here to here the whole will be created created where is the anger if this is what if where is the anger if this is what if this this but if this is this this point this point but if this is this this point this point - 110 that they one minus one - this entire Lanka - 110 that they one minus one - this entire Lanka time - what do we have for this time - what do we have for this What will be the stop for this What will be the stop for this that every day who we had if this is the that every day who we had if this is the explain point then who explain point then who will be this upper one this point election - one ko ma action will be this upper one this point election - one ko ma action minus one coma in minus one coma in Y2's problem medicines not in Y2 and in plus Y2's problem medicines not in Y2 and in plus in plus because two in plus because two cut it once, then which cut it once, then which region is this? Exam Form of Expansion - One region is this? Exam Form of Expansion - One End Why One Minus One Diner Lever End Why One Minus One Diner Lever Breezers One Minus Point Delivery So this is Breezers One Minus Point Delivery So this is our question accordingly. our question accordingly. our question accordingly. whatever I understand at this time, whichever is the maximum of the online question will become the immortal answer. Okay, so let's just record now. You have come to my training, tell everyone how it is generated. We are eager to generate it for us. We will make it, we will We will make it, we will We will make it, we will accept the oven and will do the wedding like this, this is your accept the oven and will do the wedding like this, this is your boy, we will do the boy, we will do the wedding like this, we will do all these 0's, we will wedding like this, we will do all these 0's, we will cut it, which means to say - 1, cut it, which means to say - 1, but the doctors start but the doctors start our life from zero, the fun of Bansal is the result of the above. our life from zero, the fun of Bansal is the result of the above. our life from zero, the fun of Bansal is the result of the above. pending so that our question will be easy in terms of intake, medicine scan, then we have to keep face conditions for the poor laborers, it is not there, hence we will do it, there For the code For the code For the code side and for the court, we start in this, side and for the court, we start in this, our professor makes it and our professor makes it and then we do something or the other in it, otherwise there is then we do something or the other in it, otherwise there is another way, it is another way, it is made through minor research, it is a little different in that made through minor research, it is a little different in that we first we first we first life got tips, the end of this entire region will be searched in it, which maximum means maximum number of mails per day and request is made, then that is also acceptable and this is acceptable, so much so that there will be no problem in it, okay, so let's do it. They are towards start coding so what did you do? so what did you do? First of all, we quickly made one of our indies RAM and First of all, we quickly made one of our indies RAM and Nikam took it out and kept it Nikam took it out and kept it because it is Bose's definition, so take it out. because it is Bose's definition, so take it out. because it is Bose's definition, so take it out. correct and Na Agarwal later again we have to write on this soil, then the matrix that Arjun Adher DTH will make digi as if I made DP, then how will we make DP in mother prefecture, we will make PM plus one plus one extra because of wedding so that Index you can waste time in this Index you can waste time in this Index you can waste time in this otherwise it would have been a problem this became you I have it otherwise it would have been a problem this became you I have it now we will fill our dp point now we will fill our dp point ivory coast off islab request oh mi ivory coast off islab request oh mi plus plus plus plus and and vintage boston1 the day request 10:00 vintage boston1 the day request 10:00 plus plus no do this plus plus no do this plus plus no do this Bloody Mary has only one filling, how to fill it, like I am going to fill this channel, I am going to fill this channel, then what will happen to this light, how will I take out this year's evening? Light because according to the matrix, according to the matrix, put this one in DP, I will be me, because because of the wedding broke, who was that in the matrix, I - bank manager - one will be the office, because I am tiffin If you want to If you want to If you want to add current element, add current element, then Matrix of I - 121 then Matrix of I - 121 Ki Agyeya - Dad, do it okay. Plus I have now Ki Agyeya - Dad, do it okay. Plus I have now added, so now how have we added together, added, so now how have we added together, who were the reasons and have to add, along with this we have added who were the reasons and have to add, along with this we have added this matter. this matter. sexual intercourse till here and till here sometimes there is current value in plus and sexual intercourse till here and till here sometimes there is current value in plus and explicitly explicitly that even if you want the complete history till now then that even if you want the complete history till now then also you will do it, add porn till the whole time also you will do it, add porn till the whole time and here and here means I and J - Monica and Eyeliner means I and J - Monica and Eyeliner and because you see that when I and because you see that when I add this express entry twice then add this express entry twice then this will also be done twice so this will also be done twice so it will have to be subscribed once and then General it will have to be subscribed once and then General Mathematics Mathematics Mathematics so you try inviting him on this, then I set his alarm, then I - me and I - set his alarm, then I - me and I - then I comment - then I comment - I comment, Jai minus one is also added and it I comment, Jai minus one is also added and it happened twice. happened twice. happened twice. then they are Constructed by BPO I - One Comedy - It is the first that we have kept it all tight, now our wife is completely gone again, let's like our one three below, let's support the missions Printed minimum value Maximum wish is to do Maximum wish is to do Maximum wish is to do our we take out everyone's point i20 is our we take out everyone's point i20 is judgment i that emma is i plus judgment i that emma is i plus and these days ago 0 who and these days ago 0 who is the land g plus plus that nine after doing this now tell us that yes now in our actual this we Actually, now we have Actually, now we have Actually, now we have grabbed the experts at zero, for the top most grabbed the experts at zero, for the top most corner, the one who is going to be in our top most is going to be like this in the dead top post, be like this in the dead top post, so now we will add two more looks for the water motor so now we will add two more looks for the water motor and these and these This request I Yashwant we are plus one This request I Yashwant we are plus one and this kaun taak costume tak a and this kaun taak costume tak a a plus plus a plus plus a remedy for bs well points page a remedy for bs well points page 2010 Stuart will get the gap Laxman 2010 Stuart will get the gap Laxman ne se 20 loosening and 210 that Android plus plus Method of Method of Method of deep temporary something, how will we take out the time, deep temporary something, how will we take out the time, Sri Lanka, I have taken the last location Sri Lanka, I have taken the last location of the entire location, because look at the of the entire location, because look at the celebration, because celebration, because in actual also, you will see in actual also, you will see SinghVP that when the payment is cleared, that is SinghVP that when the payment is cleared, that is why the coordinator has been kept at zero size and why the coordinator has been kept at zero size and Deepika. Deepika. Deepika. will be from its plus one plus one, so this much value is there, how to update from that, I had asked to update the volume same one Amazon Amazon - in bp.ed icon also If the chapter is If the chapter is If the chapter is done twice then I will have to add a rally of fun done twice then I will have to add a rally of fun - - Youth - 151 - What Action - 151 - Manju Youth - 151 - What Action - 151 - Manju In the original this happens, if it is difficult then you In the original this happens, if it is difficult then you are Laxman, then I will have fun and with the are Laxman, then I will have fun and with the interests of interests of interests of preambles, you will get to know how to make a statement, much respect, calculate area etc., read mail messages, you can do it like this and you can do it by sending zero too, if we have a lot of time, That loosening is done, so That loosening is done, so That loosening is done, so from Dhan VPN that yes, what from Dhan VPN that yes, what can we do, at this time we can say our answer, can we do, at this time we can say our answer, answer can also answer can be maximum of answer, answer can also answer can be maximum of answer, we are in coma, we can say this we can say this and the last moment when all and the last moment when all and the last moment when all also Apni Tange Sthali and Anshu Maximum Ishwari Main Run and Anshu Maximum Ishwari Main Run Maximum In Jawa In This Matter But Maximum Maximum In Jawa In This Matter But Maximum Mo Loot Ok So You Must Have Liked This Video Full This Video Guys Please Comment Channel Subscribe Our Channel And I Bhi I also want to I also want to I also want to upload Qawwali, all that was left was the time of upload Qawwali, all that was left was the time of clothing and job, it clothing and job, it is fine in her play list, ok baba guys. | 2024-03-24 11:26:35 | 363 | Leetcode 363. Max Sum of Rectangle No Larger Than K |
|
q1RR8gk47Cg | hello and welcome back to the cracking fang youtube channel today we're going fang youtube channel today we're going to be solving lead code problem 415 to be solving lead code problem 415 add strings let's read the question add strings let's read the question prompt prompt given two non-negative integers num1 and given two non-negative integers num1 and num2 represented as strings return the num2 represented as strings return the sum of num1 and num2 as a string sum of num1 and num2 as a string you must solve the problem without using you must solve the problem without using any inbuilt library for handling large any inbuilt library for handling large integers such as big integer you must integers such as big integer you must also not convert the inputs to integers also not convert the inputs to integers directly directly so for example if we were given the so for example if we were given the number 456 number 456 and 77 we would want to return 533 and 77 we would want to return 533 let's see how they did that and let me let's see how they did that and let me change my pen here to be more visible change my pen here to be more visible okay okay so we see that we have the number 456 so we see that we have the number 456 [Music] [Music] and we want to add 77 to it well if you and we want to add 77 to it well if you remember from i guess elementary school remember from i guess elementary school how to do division um not division uh how to do division um not division uh addition addition what we need to do is basically add what we need to do is basically add these numbers and take care of the carry these numbers and take care of the carry so 7 plus so 7 plus 6 is going to be 13 so we have 3 carry 6 is going to be 13 so we have 3 carry the 1 5 plus 7 is 12 plus the one that the 1 5 plus 7 is 12 plus the one that we carried so three we carried so three and then we carry a one again and then and then we carry a one again and then four plus one five thirty three which is four plus one five thirty three which is um what we can see is our answer here so um what we can see is our answer here so essentially what we've done here is essentially what we've done here is we've lined up our values here and we've we've lined up our values here and we've added them added them so we want to do the exact same thing so we want to do the exact same thing for our strings basically we want to for our strings basically we want to align them align them and then go from you know right to left and then go from you know right to left and add the values at whatever index but and add the values at whatever index but you'll notice here that this string on you'll notice here that this string on top the 456 is actually longer than 77 top the 456 is actually longer than 77 so what happens when we get here where so what happens when we get here where there's nothing well what we want to do there's nothing well what we want to do is is you know if we're traversing and we're you know if we're traversing and we're at an index in our one of our strings at an index in our one of our strings that is not accessible because it would that is not accessible because it would be out of bounds then we would just want be out of bounds then we would just want to treat that index as a zero so if we to treat that index as a zero so if we just pretended that this was zero seven just pretended that this was zero seven seven then we could do the additions as seven then we could do the additions as much as we wanted and this four five six much as we wanted and this four five six could have any other things in front of could have any other things in front of it we would just treat those indexes as it we would just treat those indexes as zero that way we can just add directly zero that way we can just add directly and we wouldn't have to worry about and we wouldn't have to worry about anything anything so that's the idea that we're going to so that's the idea that we're going to use two pointers one to start here at use two pointers one to start here at the beginning the beginning sorry the end of our first string and sorry the end of our first string and one at the other uh end and we're just one at the other uh end and we're just going to go from left to right going to go from left to right extracting the value at the current extracting the value at the current index and remember that since we're index and remember that since we're going from right to left we're going to going from right to left we're going to be decrementing our index each time so be decrementing our index each time so if the index for a particular string if the index for a particular string ever goes below zero that means that ever goes below zero that means that we've exhausted that string entirely we've exhausted that string entirely therefore we instead of extracting therefore we instead of extracting whatever value is at the index for that whatever value is at the index for that uh particular string we're just going to uh particular string we're just going to extract the value zero extract the value zero and that way we can just continue doing and that way we can just continue doing the addition to parse through the longer the addition to parse through the longer string and then we're gonna have to string and then we're gonna have to maintain a carry variable here to you maintain a carry variable here to you know keep track of these carries that we know keep track of these carries that we had each time and had each time and you know we'll just do the addition each you know we'll just do the addition each time and then add that to some sort of time and then add that to some sort of like string builder and then join it all like string builder and then join it all back together so we can return our you back together so we can return our you know result here as a string as it asks know result here as a string as it asks for so that might be a little bit for so that might be a little bit confusing but let's go to the editor and confusing but let's go to the editor and once you see the code everything will be once you see the code everything will be super clear this problem is quite simple super clear this problem is quite simple and it does lay the foundation for some and it does lay the foundation for some other problems on lead code so other problems on lead code so definitely want to know how to set up um definitely want to know how to set up um this problem this problem but like i said it's super simple so but like i said it's super simple so let's go to the editor and see the code let's go to the editor and see the code we're back in the editor and let's write we're back in the editor and let's write the code so the code so like i mentioned in the explanation like i mentioned in the explanation portion we're gonna want portion we're gonna want two pointers one pointing to the end of two pointers one pointing to the end of num1 and one pointing to the end of num2 num1 and one pointing to the end of num2 so let's declare those variables so so let's declare those variables so we're gonna say i equals the length of we're gonna say i equals the length of num1 minus one that's the last index and num1 minus one that's the last index and we're gonna say j equals the len of num2 we're gonna say j equals the len of num2 minus 1. minus 1. now what we want to do is remember that now what we want to do is remember that we need to keep track of the carry so we we need to keep track of the carry so we can add that each time when we do our can add that each time when we do our addition so we're going to say carry addition so we're going to say carry equals 0 and we're going to say res equals 0 and we're going to say res which is where we're going to store our which is where we're going to store our result here result here is going to be an empty list is going to be an empty list now what we need to do is we need to now what we need to do is we need to exhaust both num1 and num2 so we need to exhaust both num1 and num2 so we need to move our pointers until we've done all move our pointers until we've done all the possible additions that we have the possible additions that we have so we're going to say while i is greater so we're going to say while i is greater than or equal to zero than or equal to zero or j is greater than equal to zero and or j is greater than equal to zero and remember we're using or here because remember we're using or here because once if they're both the same length and once if they're both the same length and it's really simple they'll both end at it's really simple they'll both end at the same time because we're decrementing the same time because we're decrementing by one each time but if one is actually by one each time but if one is actually longer than the other it will take longer than the other it will take longer to reach its end and then while longer to reach its end and then while that one is processing the other one that one is processing the other one that has already been exhausted we're that has already been exhausted we're just going to instead of extracting the just going to instead of extracting the value at its index we're just going to value at its index we're just going to extract the value 0 extract the value 0 because obviously adding 0 to anything because obviously adding 0 to anything doesn't change the computation so doesn't change the computation so with that explained let's now extract with that explained let's now extract the values we have at the i and j index the values we have at the i and j index so we're going to say cur i is going to so we're going to say cur i is going to be the integer of num be the integer of num of of sorry num1 of i sorry num1 of i and we're allowed to do this because and we're allowed to do this because remember we can't convert the entire remember we can't convert the entire thing to an integer but we can convert thing to an integer but we can convert pieces of it to an integer and use that pieces of it to an integer and use that to do our calculation so remember we to do our calculation so remember we have to extract have to extract num1 of i if i is valid right if i was num1 of i if i is valid right if i was actually less than zero then you know we actually less than zero then you know we would be extracting the wrong thing would be extracting the wrong thing python actually lets you do negative python actually lets you do negative indexing indexing you know lookups but you know you know lookups but you know we would get the wrong values so we just we would get the wrong values so we just if it's greater than or equal to zero we if it's greater than or equal to zero we want to extract the value otherwise we want to extract the value otherwise we want to extract zero and we're gonna do want to extract zero and we're gonna do the same thing for j the same thing for j we're gonna say equals to int num2 we're gonna say equals to int num2 of j of j if j greater than or equal to 0 else if j greater than or equal to 0 else we're just going to get the value 0. now we're just going to get the value 0. now what we want to do is the current sum of what we want to do is the current sum of our our position is going to be whatever the position is going to be whatever the carry is from the previous sum carry is from the previous sum plus the current i plus the current j now we need to append that value to our result but what happens if we have something like 13 obviously we only want to append the three and we want to carry the one for the next iteration how do we do that well what we want to append to our result is going to be cursom modulo 10. so remember that you know 10 mod 13 modulo 10 would return three because it's basically the remainder of what happens when you divide by 10. so that would give us this one's digit position item so that's how we extract that one but now we also need to keep track of the carry so the carry this time is going to be and do note here that we're converting back to string because at the end we're going to join all of these items together and return it as a string and you can't actually join in python if all the elements that you're joining together are not strings that's why we cast back to a string getting back to carry what we want to do is we're going to do curse some integer divided by 10. so if we had something like 13 integer divided by 10 this would divide this would be one so basically what is the result of integer dividing by 10 so we're going to get you know the 1 there so at this point what we need to do is we need to decrement i and we need to decrement j and then our while loop can continue and we're going to do that until we've parsed out the entirety of num1 or num2 whichever one is longer if they're the same then they'll end at the same time if not one will end before the other now what we need to do is before we can actually return our results we need to check if carry was still left over it could be the case for example if we had the number you know 999 plus 999 that you know when we're adding these last two nines you know we'll still have a carry left over but there's nothing to add here because we've already computed both of the values so we'll still have a carry that needs to be taken care of so we do need to make note of that and we're going to say if carry so basically if it's not 0 we're going to say res.append whatever the current carry value is so we're going to say string carry now at the end all we need to do is simply return our result but remember we were processing this number from right to left which means that as we were appending our value will actually be in the opposite order that we need it to so we need to reverse our result before joining and that's the last thing we need to do so we're going to say return string dot join reversed res so that will give us our answer so let's just submit this to make sure we haven't made any mistakes here hopefully okay cool didn't embarrass myself there all right so our solution works now what is going to be our runtime complexity well we know that we need to process the entirety of num1 and num2 so that's going to be big o of n plus m where n represents the length of num1 and m represents the length of num2 and what our solution here is going to be it's also going to be big o of n plus m because we need to account for basically the sum of these two which is going to be you know dependent on the length of n plus m uh what our actual result ends up being so that's going to be our run time complexity here and our space complexity that's how you solve add strings there is a problem where i think it's called add binary which is literally the exact same code except now our numbers are not going to be um base 10 they actually mean base two so you can literally just replace this with a two and this with the two when solving that question and you will be able to solve it it's the exact same code you just need to remember that it's binary for that one whereas this one is uh base 10 so that's why we're you know modulo 10 and divided by 10. anyway uh that's the solution for this problem i hope you enjoyed this video if you did please leave a like comment and subscribe check out my other videos if you're preparing for on-site interviews | 2024-03-15 18:39:27 | 415 | ADD STRINGS | PYTHON SOLUTION | LEETCODE 415 |
|
lQkwmbfrKhg | Hello Hi Everybody Welcome To My Channel Today Is The Second Last Date Of Units Wedding Chalen Is Is The Second Last Date Of Units Wedding Chalen Is Dahej Ki Problem Is Unique 500 Dahej Ki Problem Is Unique 500 Vs Laptop Left Most Corner Of M Vs Laptop Left Most Corner Of M Cross And Great Hair This Start Cross And Great Hair This Start Points And Notes Can Only Move On The Points And Notes Can Only Move On The Dawn And Right At Dawn And Right At Dawn And Right At Android Trying To Reach At This Point For This Is And You Have To Find Out Channel Subscribe Now To Channel Subscribe Now To Great Hair Soft Videos And Columns Great Hair Soft Videos And Columns From This Conic 10 - 151 This Opinion From This Conic 10 - 151 This Opinion Unlimited Unlimited Unlimited Basis Of All Way N Crime Ek Option Robot For Them Road Reach Subscribe And Donate 100 Road Possible Options Subscribe Can Very From Where From The Side And Subscribe Our Channel Like This Way Can Come From To Three To The Answer And To Three To The Answer And To Three To The Answer And Sorry For The Robot Subscribe Sorry For The Robot Subscribe According To Agro Robot From Here Someone Way According To Agro Robot From Here Someone Way All In The Air 1512 From A Great To Three All In The Air 1512 From A Great To Three Floor 500 600 3060 Had To 100 Will Not Floor 500 600 3060 Had To 100 Will Not Right Side Download To Check Particular Right Side Download To Check Particular Coordinator Robot Can Only Coordinator Robot Can Only Coordinator Robot Can Only that this is minus one coordinate and the I - one is called Maje Coordinator from being left side Sudhir and 10:00 So what we can do The number of tourists can form of I understand that can be written S D P F that can be written S D P F that I - that I - that I - Majhe APlus A Hai Aa A Hai Aa J - 1m J - 1m Slack Try to First Form Dainik Cursive Slack Try to First Form Dainik Cursive Solution Handed Over Let Me Call The Everywhere The Solution Handed Over Let Me Call The Everywhere The Total In Part UP From Record Total In Part UP From Record Chintu This Point Acidity Se - Oil - 110 The Chintu This Point Acidity Se - Oil - 110 The Soul From This Pat Soul From This Pat Soul From This Pat No One Can Come Only From Two Where From Here A Minus Two And Country One Life Amazon Voice Mail In Coma - 2 And From Which Coordinator Which Is Is Akin To - Two And Other Same Inventions And Columns So What We Can Columns So What We Can Columns So What We Can Benefit From It - 151 - One Will Go Benefit From It - 151 - One Will Go To The Way UP Of - 251 To To The Way UP Of - 251 To End And This One More Minute To Sum Up India End And This One More Minute To Sum Up India -Foreign Tweet UP Total Links From Pat -Foreign Tweet UP Total Links From Pat - 151 - To Reduce Father Will Go Alone In - 151 - To Reduce Father Will Go Alone In - 151 - To Reduce Father Will Go Alone In free to champion again more the robot to the point will return from the middle of 10000 subscribe up returns page after - one to three boys top the software will have or private method tent tube which will get into it's a shame Mind 0 I will check only MS Word 120 and I am the this vansh and other wise only family 20 and this vansh and other wise only family 20 and here and 10 here and 10 that he will return 020 that he will return 020 that hero otherwise will return social POP that hero otherwise will return social POP of feminines one plus side manas Subscribe Like this is the Father Govind Subscribe Like this is the Father Govind Str on - Pratima Str on - Pratima that and minus one and which one will visit that and minus one and which one will visit UP after oo UP after oo that UP is off - to to butter - 2 acid less that UP is off - to to butter - 2 acid less from which branch this tweet UP after - 2m from which branch this tweet UP after - 2m - to - to This anniversary is a serious problem even from the right side, This anniversary is a serious problem even from the right side, this is repeated hair, for example, all this is repeated hair, for example, all problems, thoughts, updates, Wilks result, problems, thoughts, updates, Wilks result, officer problem, this, Zauq Singh, I am letting me use this officer problem, this, Zauq Singh, I am letting me use this in teenagers, a map of string for my hand, a juicer, juicer, a map, nickel to a new house, a map. a map, nickel to a new house, a map. 200 what will to will create from that 200 what will to will create from that bill se speech in the soil with string key bill se speech in the soil with string key request to plus request to plus $1 we using an india limited because they remind $1 we using an india limited because they remind me to different this festival delete me to different this festival delete meter can give the same that maybe will create subscribe content's Will Will Will Returns The Ki Hum Aap.net Ki Is Saade Se And Indian Hair And Wealth Will Just Place Value In The Letter This Is The Topper Place Value In The Letter This Is The Topper Us Implementation Of Problem Solve Us Implementation Of Problem Solve Picture In This Way Solution Citizen Compiling Picture In This Way Solution Citizen Compiling Running Running Running baby very soon where written in correct taking too much time e this is all height for digital sign hai starring 102 102 ki rishi taking too much time encompassing ki rishi taking too much time encompassing also collect code in this verse Submit This The City Has Accepted And Same Time Complexity Of Dissolution Of This All Time Complexity Of Dissolution Is Form Of M Com And Space Complexities Us My Name As Given Subha Channel Se Implement This Problem Using The Water Mob Dance Programs Let's Video Course For Will Just One Too Today In Tv Today Will Just One Too Today In Tv Today Will Just One Too Today In Tv Today Are Dp Images Interface Size Plus Top Are Dp Images Interface Size Plus Top Color Loud Plus For 10 Subscribe Color Loud Plus For 10 Subscribe Tomorrow Morning 6Pe New Hair Resignation Tomorrow Morning 6Pe New Hair Resignation Strawberries Only One Way Robot Nuvve And Strawberries Only One Way Robot Nuvve And Columns To What We Can Do 504 Columns To What We Can Do 504 And J0 Case Will Awards Pema And J0 Case Will Awards Pema And J0 Case Will Awards Pema swelling other wise words page if his defeat after - one subscribe plus subscribe 220 layton dpi ko maf my name a minus one corner and minus one saudi system approach solid solid is earning that undertaking sometime e don't know weather Silvat Session Judge Singh Ya Silvat Session Judge Singh Ya Silvat Session Judge Singh Ya Wedding Correct Answer So Let's Acid Wedding Correct Answer So Let's Acid Hua Hai The Hua Hai The Site Is Accepted For The Time Site Is Accepted For The Time Complexity Of Dissolution Is Mess This Complexity Of Dissolution Is Mess This Channel Subscribe Button Carefully See What They Are Channel Subscribe Button Carefully See What They Are Doing This Relation Is This Is Equal To Of Them Doing This Relation Is This Is Equal To Of Them And Top 5200 2MB Subscribe And And Top 5200 2MB Subscribe And Switch on share mode Switch on share mode that you turd what we can do hair drink that you turd what we can do hair drink spreading witch will update dros using the model spreading witch will update dros using the model to like involve will update roadways to like involve will update roadways bus se continue like this they will update the verses will just bus se continue like this they will update the verses will just rot this with subscribe rot this with subscribe who hair is film and who hair is film and who hair is film and Bittu An Indian Vijay Returns Again Dashami Mod With To Subscribe Hindi Mein Yes The Judge Yes The Judge And Now Any Sphere Cutting Correct And Now Any Sphere Cutting Correct 100MB Submit Dashrath Accept So Her Not Been 100MB Submit Dashrath Accept So Her Not Been Optimized Subscribe To Optimized Subscribe To 210 Problem Can Also Be Thinking Other Way 210 Problem Can Also Be Thinking Other Way Of Of Of to total - they number coordinator right side and total minus one side total vote's mood plus minus b hua hai - one plus and minus one hand they have to white dream defect is mathematics implementation implementation Thank you in comment section please like share and subscribe Thank you in comment section please like share and subscribe my channel | 2024-03-20 10:53:13 | 62 | unique paths | unique paths leetcode | leetcode 62 |
|
WqoPfWQmktA | let's solve the problem 1710 maximum units on a truck so the question goes units on a truck so the question goes like this so you'll be like this so you'll be given a truck size a truck size is given a truck size a truck size is nothing but a capacity of the trucks nothing but a capacity of the trucks okay so let's take an example so say the okay so let's take an example so say the in this example you are given a truck in this example you are given a truck size of size of 10 okay so my 10 okay so my capacity is to store 10 boxes capacity is to store 10 boxes okay and then there is an array that okay and then there is an array that they provide with different types of they provide with different types of boxes okay that doesn't matter but what boxes okay that doesn't matter but what matters is within this each type of box matters is within this each type of box they are giving us two information one they are giving us two information one is the number of is the number of boxes of that boxes of that type and the number of units type and the number of units per box how many units can be stored in per box how many units can be stored in one one box right so that's what they are giving box right so that's what they are giving us so in this example particularly they us so in this example particularly they are saying that of the first typ there are saying that of the first typ there are five boxes and each of those five are five boxes and each of those five boxes can store 10 units each okay in boxes can store 10 units each okay in the second type of box there are two the second type of box there are two boxes in each of those box can store boxes in each of those box can store five units each third type of box are of five units each third type of box are of are four there are four SE are four there are four SE boxes and each stores seven boxes and each stores seven units and then there is units and then there is [Music] [Music] fourth which is three fourth which is three boxes and each of those stores 9 units boxes and each of those stores 9 units each so I need to figure out with such each so I need to figure out with such an an example how many units can example how many units can you load into the truck given that you you load into the truck given that you can load maximum 10 boxes or whatever can load maximum 10 boxes or whatever the capacity that they the capacity that they provide how many units can provide how many units can be up loaded into the truck maximum be up loaded into the truck maximum units that can be loaded into truck so units that can be loaded into truck so in this example what I'll do is to in this example what I'll do is to resolve this what I can do is the best resolve this what I can do is the best way would be to take the boxes with the way would be to take the boxes with the maximum units first right so I can maximum units first right so I can maximize my units maximize my units so the first so the first one for each box I get 10 units it takes one for each box I get 10 units it takes just one box away and adds 10 units just one box away and adds 10 units right so definitely I'll take this one right so definitely I'll take this one next I'll go with this right the second next I'll go with this right the second largest number of units per largest number of units per box then I'll go with this the third box then I'll go with this the third largest units per box and then finally largest units per box and then finally if there's any then I'll go with the if there's any then I'll go with the fourth one so I'll first reorder it this fourth one so I'll first reorder it this way then I'll start way then I'll start counting how many units can I go so I'll counting how many units can I go so I'll see can I add five boxes certainly I see can I add five boxes certainly I have capacity of 10 I can certainly add have capacity of 10 I can certainly add five boxes so how many units do I get 50 five boxes so how many units do I get 50 5 into 10 50 units then I can reduce the 5 into 10 50 units then I can reduce the capacity now my left capacity has 5 capacity now my left capacity has 5 boxes I'll go to the next one can I add boxes I'll go to the next one can I add three boxes yes I three boxes yes I can so 3 into 9 how many units I'm can so 3 into 9 how many units I'm getting getting 27 right I'll reduce the capacity by 27 right I'll reduce the capacity by another three I'm left with two back box another three I'm left with two back box capacitor space can I add four boxes no capacitor space can I add four boxes no four is greater than the my capacity so four is greater than the my capacity so what I'll do is I'll just stick two of what I'll do is I'll just stick two of these boxes so I'll add 2 into these boxes so I'll add 2 into 7 14 units I cannot take all four boxes 7 14 units I cannot take all four boxes but I can take two boxes so I'll but I can take two boxes so I'll multiply 2 into 7 multiply 2 into 7 I'll get 14 units so finally the sum of I'll get 14 units so finally the sum of all this 50 + 27 + 40 is all this 50 + 27 + 40 is 91 so total units I can carry is 91 91 so total units I can carry is 91 right this is what I need to code it right this is what I need to code it okay so how will I do first of all okay so how will I do first of all count is equal to count is equal to zero right and zero right and then then while or I could do for I in range length of box type box types okay and then before this as we had discussed we will sort box types by the number of units per box and in descending order so how will be Lambda Lambda is a function that I'm writing Lambda it takes in each box and sort it sorts it out on the first index element of it zeroth index tells me about the number of books the first index tells me about number of units per book so I want to sort it by that s pass or pass X at index one okay also I need to reverse is equ to true so that it does it in a descending order so I get the highest number of units at the top at first and or or on the left of the array and lower numbers as we proceed to the right so now I can go with for I in range length of box if if box types at i is is less than or equal to to Tru Tru size then in that case what I'll do size then in that case what I'll do is I'll add it to my count so count plus is I'll add it to my count so count plus equals equals to types at 0 multiplied by box types of I have one so boxes multiplied by units so that manyan count will be increased in case my box types number of boxes in that at that index is less than the less than or equal to theze else if it is greater than or equal to remaining I'll put the remaining uh space multiplied by so remaining spaces whatever the truck size is also I need to reduce my truck size here while I'm using those boxes I can reduce that much capacity from the truck size so now I can take the remaining than count at count of boxes than count at count of boxes so I can take truck size so I can take truck size into into units or box why units or box why because only that many boxes out of all because only that many boxes out of all the boxes in of that index I can use up the boxes in of that index I can use up right so truck size into box right so truck size into box type of box units per box that that I type of box units per box that that I added into the count and finally added into the count and finally return the count so I can do it return the count so I can do it something like something like this count this count plus plus size this and I can return this at this size this and I can return this at this point because after this my truck size is totally come full there is no capacity left so I can return whatever the answer is no need to continue the loop after it but if say the loop gets over before the truck size is filled which means that I have taken all the boxes Till There is space in the truck or I have taken all boxes and there is no space in the truck in both those cases the loop will run completely and it will never reach this point right so it will never returns off the loop is complete I'll return units of count okay let's look at this I put brackets here to just explicitly tell that multiply this first then add to the works that works that worked beautiful so that's how this can be solve let's look at for some of the solutions from other people and this is the best solution it's just doing let's look at one more doing let's look at one more solution all of them are following solution all of them are following something very similar to what we have something very similar to what we have done so that's how you can solve the done so that's how you can solve the problem 1710 maximum units on a truck problem 1710 maximum units on a truck see in the next we | 2024-03-20 15:11:24 | 1,710 | Leetcode 1710. Maximum Units on a Truck |
|
3OamzN90kPg | hey everyone welcome back and let's write some more neat code today so today write some more neat code today so today let's solve contains duplicate this is let's solve contains duplicate this is another problem from the blind 75 list another problem from the blind 75 list of questions we've been working on so i of questions we've been working on so i like this problem because it's a good like this problem because it's a good problem for beginners but there's also problem for beginners but there's also multiple solutions to it that i'd like multiple solutions to it that i'd like to go over in this video so we're given to go over in this video so we're given an array of numbers we want to return an array of numbers we want to return true if there's any value in that list true if there's any value in that list of numbers that appears at least twice of numbers that appears at least twice but maybe it could appear three times or but maybe it could appear three times or four times write just at least twice and four times write just at least twice and we want to return false if there aren't we want to return false if there aren't any values that appear at least twice any values that appear at least twice basically what that means is that every basically what that means is that every value in the array is distinct so let's value in the array is distinct so let's take a look at an example we have one take a look at an example we have one two three and then we have 1 again so of two three and then we have 1 again so of course this has duplicates right so we course this has duplicates right so we return true and the easiest way we would return true and the easiest way we would be able to detect that is by brute be able to detect that is by brute forcing this so given these numbers the forcing this so given these numbers the first thing we do is look at the first first thing we do is look at the first number it's 1. how do we know if this is number it's 1. how do we know if this is a duplicate or not well we'd have to a duplicate or not well we'd have to compare it to every single number in the compare it to every single number in the rest of the array so that would be a big rest of the array so that would be a big o of n time operation just to check if o of n time operation just to check if the first number is a duplicate or not the first number is a duplicate or not and then we'd have to do that for every and then we'd have to do that for every number then we have to check is the number then we have to check is the second number a duplicate how do we know second number a duplicate how do we know we have to compare it to every other we have to compare it to every other number we do the same thing with the number we do the same thing with the third one and the last one and so since third one and the last one and so since we're doing it for every number in the we're doing it for every number in the array the overall time complexity is array the overall time complexity is going to become n squared and by the way going to become n squared and by the way in this case n is just the size of the in this case n is just the size of the input array so the brute force solution input array so the brute force solution is big o n squared time complexity but is big o n squared time complexity but the good thing is we don't need any the good thing is we don't need any extra memory so the memory complexity is extra memory so the memory complexity is big of one it's definitely not a bad big of one it's definitely not a bad solution but the question is can we do solution but the question is can we do better than that and yes we definitely better than that and yes we definitely can a second approach that will help us can a second approach that will help us is sorting what happens if we took this is sorting what happens if we took this array and we sorted it it would look a array and we sorted it it would look a little bit different it would look like little bit different it would look like this okay but how does sorting help us this okay but how does sorting help us well let's think about it if we sort the well let's think about it if we sort the input then any duplicates that do exist input then any duplicates that do exist in the array and clearly we see that two in the array and clearly we see that two duplicates exist at the beginning of the duplicates exist at the beginning of the array they're going to be adjacent so array they're going to be adjacent so when we're when we're trying to detect any duplicates in here trying to detect any duplicates in here we only have to iterate through the we only have to iterate through the array once and as we do that we're just array once and as we do that we're just going to be comparing two neighbors in going to be comparing two neighbors in the array checking if they're duplicates the array checking if they're duplicates next we're going to shift our pointers next we're going to shift our pointers to the next spot are these duplicates to the next spot are these duplicates are these duplicates etc etc until we are these duplicates etc etc until we finish the entire array in this case we finish the entire array in this case we see that these two adjacent values are see that these two adjacent values are duplicates so we can return true and duplicates so we can return true and what's the time complexity of this well what's the time complexity of this well the one pass is just going to be big o the one pass is just going to be big o of n but we know that sorting does take of n but we know that sorting does take extra memory or not extra memory it does extra memory or not extra memory it does take uh extra time complexity and that take uh extra time complexity and that time complexity is n log n so that's the time complexity is n log n so that's the bottleneck in this solution but again we bottleneck in this solution but again we don't need extra space if you don't don't need extra space if you don't count the space that's used by the count the space that's used by the sorting algorithm so in this case we do sorting algorithm so in this case we do have a slightly better solution than have a slightly better solution than brute force but actually if we use a brute force but actually if we use a little bit extra memory and it's really little bit extra memory and it's really a trade-off if we sacrifice space a trade-off if we sacrifice space complexity we can actually achieve complexity we can actually achieve better memory complexity and let me show better memory complexity and let me show you how so suppose we don't sort our you how so suppose we don't sort our input we're given the default input but input we're given the default input but we use extra memory we use a hash set we use extra memory we use a hash set but what exactly is a hash set gonna do but what exactly is a hash set gonna do for us it's gonna allow us to insert for us it's gonna allow us to insert elements into the hash set in big o of elements into the hash set in big o of one time but it's also gonna allow us to one time but it's also gonna allow us to check we can ask our hashmap does a check we can ask our hashmap does a certain value exist we want to know does certain value exist we want to know does this 1 exist in the hashmap well if we this 1 exist in the hashmap well if we start at the beginning of the array so start at the beginning of the array so far nothing is in our hashmap so a 1 far nothing is in our hashmap so a 1 does not exist in our hashmap that means does not exist in our hashmap that means this 1 is not a duplicate you can see this 1 is not a duplicate you can see that this is an improvement over the that this is an improvement over the brute force previously to determine if brute force previously to determine if this was a duplicate we had to check this was a duplicate we had to check every other value in the array this time every other value in the array this time we don't but after we have checked if we don't but after we have checked if this is a duplicate we do have to add it this is a duplicate we do have to add it to our hash set because later on if we to our hash set because later on if we encounter a one like over here then we encounter a one like over here then we determine that this is a duplicate determine that this is a duplicate because we know that there's already a because we know that there's already a one in our hash set so next we're gonna one in our hash set so next we're gonna check two two is not a duplicate added check two two is not a duplicate added here is three a duplicate nope add it here is three a duplicate nope add it here one is this a duplicate yep there's here one is this a duplicate yep there's a one over here so we return true this a one over here so we return true this does contain duplicates and by the way does contain duplicates and by the way since each operation was just big o of since each operation was just big o of one we had to do that for every value in one we had to do that for every value in the input array and we only had to scan the input array and we only had to scan through the list of inputs once the time through the list of inputs once the time complexity is going to be big o of n but complexity is going to be big o of n but the space complexity we did have to the space complexity we did have to sacrifice a little bit we have to create sacrifice a little bit we have to create a hash set and the memory that that hash a hash set and the memory that that hash set will use could be up to the size of set will use could be up to the size of the input array which is n so we do end the input array which is n so we do end up using extra memory but that's not too up using extra memory but that's not too bad this is about as efficient as we can bad this is about as efficient as we can get in terms of time complexity so let's get in terms of time complexity so let's get into the code now okay so now let's get into the code now okay so now let's get into the code so the first thing i'm get into the code so the first thing i'm going to do is create that hash set in going to do is create that hash set in python you can do that just like this python you can do that just like this it's just called a set and then the it's just called a set and then the simple thing is just going through every simple thing is just going through every value in the input array nums and value in the input array nums and before we end up adding it to our hash before we end up adding it to our hash set because remember we want to add set because remember we want to add every one of these values to our hash every one of these values to our hash set just like this but before we even do set just like this but before we even do that we want to know is n a duplicate that we want to know is n a duplicate does this value already exist in our does this value already exist in our hash set and if it does we know that our hash set and if it does we know that our array contains duplicates so we don't array contains duplicates so we don't even have to continue through the rest even have to continue through the rest of the array we can immediately return of the array we can immediately return true because we found a duplicate but if true because we found a duplicate but if it doesn't contain a duplicate we're it doesn't contain a duplicate we're going to add that value then iterate going to add that value then iterate through the rest of the array of nums through the rest of the array of nums and then the loop will exit and then we and then the loop will exit and then we can return false to indicate that we did can return false to indicate that we did not find any duplicates in the array now not find any duplicates in the array now let's run the code to make sure that it let's run the code to make sure that it works and on the left you can see that works and on the left you can see that yes it does work and it is about as yes it does work and it is about as efficient as we can get so i really hope efficient as we can get so i really hope that this was helpful if it was please that this was helpful if it was please like and subscribe it supports the like and subscribe it supports the channel a lot consider checking out my channel a lot consider checking out my patreon where you can further support patreon where you can further support the channel and hopefully i'll see you the channel and hopefully i'll see you pretty soon thanks for watching | 2024-03-22 10:43:23 | 217 | Contains Duplicate - Leetcode 217 - Python |
|
5tHVZmAB2L8 | me Brea me let me the lungs inside you and the black me the lungs inside you and the black and eyes make my way into your and eyes make my way into your mind just to know what you knew rest mind just to know what you knew rest every time we start locking as all oh I every time we start locking as all oh I lost control oh oh is Paradise with a lost control oh oh is Paradise with a nasty nasty B wi the dead of the night let the darkness take [Music] control let the darkness take let the darkness take control Darkness take control Darkness take control May the darkness take [Music] control take me in small breathe in and let me go sink to your heart to find you open up your eyes till you're blinded by the lights so you can see what you do rest every time we start Ling as oh lost control oh is Paradise with our nasty by in the dead of the night tear drops on the FL the Fain is over field the darkness [Music] [Music] control control [Music] [Applause] take that you should know I've been take that you should know I've been going so low one my love baby going so low one my love baby ear yeah doesn't on my own see if you ear yeah doesn't on my own see if you you can follow got me feeling Al you can follow got me feeling Al lie one go control is is real all I feel real real real I do what I want o I do what I want o I do what I want ooh I do what I want I want I want I want hear me now I do what I want are you ready now cuz it won't be easy only get what you work for got to go all out whenever you see me don't be wasting my time watch me go control is this real I feel bre my signs tell's be real be real real I do what I want hey I do what I [Music] want I do what I want I want I want I want I do what I want I want I want I want hear me know watch me go control want hear me know watch me go control real all I [Music] [Music] I do what I want I do what I want I do what I [Music] [Music] want I do what I want I I I me now I do want I do what I want I I I me now I do what I want like me small breathe me in and let me go feeling the lungs inside you and the black and eyes make my way into your mind just to know what you knew rest every time we start locking eyes oh I lost control is dice with a nasty night let the darkness take night let the darkness take [Music] control let the darkness take let the darkness take control Darkness take control Darkness take control May the darkness take [Music] control like me in small breathe me in and let me go sink to your heart to find you open up your eyes till you're blinded by the lies so you can see what you do Restless every time we start Ling as oh lost control oh is Paradise with our nasty by now in the dead of the [Music] [Music] [Applause] | 2024-03-25 17:25:00 | 1,095 | 1095: Find in Mountain Array | LeetCode Explained | C++ | |
|
IPiMr4AmMOE | it was a guy's nick wife here at attacking coding stuff on twitch in attacking coding stuff on twitch in youtube and do all the solutions to all youtube and do all the solutions to all the hacker ink and lead code problems so the hacker ink and lead code problems so just check my playlist it's on my just check my playlist it's on my channel I have them for both channel I have them for both this one's called unique email addresses this one's called unique email addresses it's really easy every email consists of it's really easy every email consists of a local name and a domain name separated a local name and a domain name separated by an @ symbol for example an Alice at by an @ symbol for example an Alice at Lee code comm Alice is the local name Lee code comm Alice is the local name Lee cocom is the domain name besides Lee cocom is the domain name besides lowercase letters the emails can contain lowercase letters the emails can contain period or plus symbols addition symbols period or plus symbols addition symbols if you had periods between some of the if you had periods between some of the characters in the local name part of an characters in the local name part of an email address mail will be sent there to email address mail will be sent there to the same address without dots in the the same address without dots in the local name so we see periods we just local name so we see periods we just ignore them ignore them for example Alice dot C will just be a for example Alice dot C will just be a lousy forward to the same email address lousy forward to the same email address if you see a plus in the local name if you see a plus in the local name everything after the plur first plus everything after the plur first plus sign will be ignored this allows emails sign will be ignored this allows emails to be filtered for example m dot y plus to be filtered for example m dot y plus name will be my email com so just ignore name will be my email com so just ignore anything after the plus and before they anything after the plus and before they add symbol so how do we do this it's add symbol so how do we do this it's pretty easy we're just gonna loop pretty easy we're just gonna loop through this well first of all we're through this well first of all we're gonna have a hash set because we want gonna have a hash set because we want the count we're gonna be outputting the count we're gonna be outputting we're gonna be in we're gonna have the we're gonna be in we're gonna have the input of a bunch of different emails and input of a bunch of different emails and we're gonna have to you know obviously we're gonna have to you know obviously do what we fix these addition and split do what we fix these addition and split it into local name and domain name fix it into local name and domain name fix the addition and periods but we want the the addition and periods but we want the unique email addresses out of the list unique email addresses out of the list that we're given so we're gonna have a that we're given so we're gonna have a hash set because we can just loop hash set because we can just loop through all these emails this array of through all these emails this array of emails fix will create a fixed version emails fix will create a fixed version of each email and then we'll put them of each email and then we'll put them into a hash set and return the count at into a hash set and return the count at the end because a hash set only keeps the end because a hash set only keeps unique things unique values so that's unique things unique values so that's the method here we're gonna have a hash the method here we're gonna have a hash set of strings called unique emails we're gonna do a loop we're gonna use the kind of object loop here so for string email and emails so we have access to the current email as we loop then we're gonna go first we're gonna get the index so we're gonna get I'm gonna call it split position we're gonna get the index of the at symbol in the current email and then this is how we split we're gonna use the substring method so we're gonna do local name is equal to e mail dot substring from 0 to split position so now we have the local name in the domain name domain name is going to be set to email dot substring just a split position because by default this will just give us the rest of from split position to the end of the emails length that's pretty much it and then all we have to do is if local name doc now now we split the email up into before the @ symbol and after the @ symbol so we have the perfect local name a domain name so now what we have to do is we have to fix the local name because any other errors are gonna be here at the periods and the plus symbols so first thing we'll do is just fix the plus symbol anything after the plus sign what can be ignored so we're just gonna get rid of that so if local name contains the plus symbol we're gonna do the same thing we just did above we're gonna get you know plus position is going to be equal to local dot index of the plus symbol snow in the position of that and then we're just gonna do local name is equal to local name dot substring of 0 to plus position because we only want the things before the we only want to keep what's before the plus symbol so this just resets our local name to the same thing with the stuff before the plus a little super easy right there now all we have to do is use the built in java method replace all replace all periods we just don't we want to ignore peer it just says ignore peer it's pretty easy so we just reset local name now that we just have the beginning part before the plus symbol to local name dot replace all and the period is a special character so we have to use us we have to escape it with the double backslash here and then just replace all of the periods in the string with an empty string so that just gets rid of them and there we go now we have the local name correct and the domain name are correct we can just construct a new string so new name is equal to local name plus domain name you don't have to do this you can just do all this in one step I'm just doing for code readability and then we just add it into the hash step so unique emails to add new name and now all of these new names will be perfect we'll add them into the hash set as we loop through and the only unique values will remain in the hash set and then we can just only want the number of unique emails left so we just return unique emails dot size hopefully that made sense to you guys it's basically just knowing that hash that's what's going on here domain name email oh sorry about this and forgot a equal sign syntax syntax error so you know there we go okay there works this problem is pretty easy it's just knowing that a hash that has unique values so that's just what hash that's our fill for whenever you see unique think hash that I guess we reconstruct it with the rules that were given just ignoring periods and removing anything after the plus sign and before the @ symbol we split it in two parts add them back together and then check for unique values so return the saw slash so that's it thank you guys for watching please check out my | 2024-03-25 11:29:48 | 929 | LeetCode Unique Email Addresses Solution Explained - Java |
|
qBbZ3tS0McI | so yeah as an egg-white here I do technically stuff on twitch and YouTube technically stuff on twitch and YouTube check the description for all my check the description for all my information yeah we do all the Wako information yeah we do all the Wako problems and I got a big playlist so problems and I got a big playlist so we're gonna check them out we got we're gonna check them out we got generate parentheses for some reason we generate parentheses for some reason we missed this one even though it's very missed this one even though it's very popular I feel like I did it on a bunch popular I feel like I did it on a bunch of other videos though given n pairs of of other videos though given n pairs of parentheses write a function to generate parentheses write a function to generate all combinations of well-formed all combinations of well-formed parentheses this is a really popular parentheses this is a really popular problem there's a million ways to do problem there's a million ways to do this to give you backtracking dynamic this to give you backtracking dynamic programming stacks like all you know programming stacks like all you know just different ways to do it you can just different ways to do it you can just use pointers you know there's just use pointers you know there's different ways it solve the parentheses different ways it solve the parentheses and it's usually a variation problem and it's usually a variation problem there's a little some different ways to there's a little some different ways to do that they explain the parentheses but do that they explain the parentheses but in this case we want well-formed in this case we want well-formed parentheses and we're gonna be returning parentheses and we're gonna be returning a list of them based on a number okay so a list of them based on a number okay so we're gonna get a number right we're we're gonna get a number right we're function takes in a number and it function takes in a number and it returns a list so what is the number the returns a list so what is the number the number is n pairs of parentheses so number is n pairs of parentheses so that's how many pairs of parentheses that's how many pairs of parentheses that we're gonna be returning right so that we're gonna be returning right so if we have three as the number N equals if we have three as the number N equals three then we are going to return every three then we are going to return every possible combination of three pairs of possible combination of three pairs of well-formed parentheses and well form well-formed parentheses and well form parentheses basically if we look at this parentheses basically if we look at this example here we could see that well form example here we could see that well form parentheses means each opening parentheses means each opening parenthesis has a corresponding closing parenthesis has a corresponding closing parenthesis so in this case this opening parenthesis so in this case this opening parenthesis Court has this corresponding parenthesis Court has this corresponding closing one this opening one has this closing one this opening one has this closing one and they're nested right so closing one and they're nested right so there's two types you get up nested or there's two types you get up nested or you could have next to each other right you could have next to each other right so these two are next to each other but so these two are next to each other but they're nested in these outer ones right they're nested in these outer ones right and that's fine this is these two are and that's fine this is these two are nested within this pair right and then nested within this pair right and then there's a pair right here so as long as there's a pair right here so as long as there's an opening and the corresponding there's an opening and the corresponding closing with that opening that's fine closing with that opening that's fine there cannot be closing braces before there cannot be closing braces before opening braces that's not well-formed opening braces that's not well-formed right that's gonna be incorrect it right that's gonna be incorrect it cannot look like this that is not how cannot look like this that is not how we're gonna be doing it here okay all we're gonna be doing it here okay all right I think we understand so how do we right I think we understand so how do we do this do this it looks like the best solution to do it looks like the best solution to do this is backtracking definitely not the this is backtracking definitely not the easiest I'd say stacks are probably the easiest I'd say stacks are probably the most just easy in general but you know most just easy in general but you know we're gonna do backtrack it is one of we're gonna do backtrack it is one of the easiest ways to understand the easiest ways to understand backtracking this is one of the easiest backtracking this is one of the easiest backtracking problems so I'm gonna just backtracking problems so I'm gonna just set up the template backtracking code so set up the template backtracking code so this is the template backtracking code this is the template backtracking code you have a separate method called you have a separate method called backtrack and then that's you know and backtrack and then that's you know and then basically you have your usually then basically you have your usually backtracking involves a list and backtracking involves a list and returning a list so what you're gonna do returning a list so what you're gonna do in this case is just set up your list in this case is just set up your list we'll call it output array and it's just we'll call it output array and it's just gonna be an array list basic array list gonna be an array list basic array list boom and you return that output array boom and you return that output array after you call the backtracking method after you call the backtracking method so you call the backtracking method and so you call the backtracking method and you pass it in your output array this is you pass it in your output array this is literally template code right literally template code right you're gonna take in the output right you're gonna take in the output right here boom so we take it in right and here boom so we take it in right and what we're gonna do is our base case what we're gonna do is our base case this is how it works and halt this is how it works and halt backtracking problems so we have some backtracking problems so we have some base case oops some base case some base base case oops some base case some base condition some base case where we condition some base case where we actually add something onto the list the actually add something onto the list the output array so this output array will output array so this output array will be adding some kind of data here and in be adding some kind of data here and in this case it's going to be strings okay this case it's going to be strings okay so we're actually gonna be adding so we're actually gonna be adding strings in this backtrack problem so strings in this backtrack problem so we're gonna do say back that backtrack we're gonna do say back that backtrack current string this is still template current string this is still template code so this is the data type you're code so this is the data type you're gonna be adding in the base case so gonna be adding in the base case so we're gonna be adding current string in we're gonna be adding current string in our base case our base case will get hit our base case our base case will get hit this is a recursive function backtrack this is a recursive function backtrack was recursive and when the base case was recursive and when the base case gets hit we add a new string onto our gets hit we add a new string onto our output array and at the end of that output array and at the end of that would just write return right so this is would just write return right so this is all just standard template code the all just standard template code the other template code is you're gonna be other template code is you're gonna be making dish decisions backtracking making dish decisions backtracking always involves decisions and you make always involves decisions and you make all possible decisions in these all possible decisions in these recursive calls so what is the base case recursive calls so what is the base case gonna be I guess base case is base case gonna be I guess base case is base case is going to be while we're looking we're is going to be while we're looking we're looking at pairs right we're looking at looking at pairs right we're looking at N equals 3 so all possible combinations N equals 3 so all possible combinations so what we're gonna want to keep track so what we're gonna want to keep track of is the maximum number of parentheses of is the maximum number of parentheses we can have so basically what we're we can have so basically what we're gonna do is if the current string is gonna do is if the current string is equal so this is the base case if the equal so this is the base case if the current string dot length is equal to current string dot length is equal to max' max' times two then we're going to add our times two then we're going to add our string onto the output array because string onto the output array because that means that if the currents if max that means that if the currents if max is three like in this case if the is three like in this case if the current string is size six that means current string is size six that means there's three pairs of parentheses there's three pairs of parentheses because there's two parentheses per pair because there's two parentheses per pair so we just do max because that's the so we just do max because that's the number of pairs times two to get the number of pairs times two to get the actual length of the string that we want actual length of the string that we want right yeah so that looks pretty right yeah so that looks pretty straightforward there now we just have straightforward there now we just have to actually handle our decision so what to actually handle our decision so what our decisions gonna be based on well we our decisions gonna be based on well we need to actually handle parameters our need to actually handle parameters our max is gonna come from just n we need in max is gonna come from just n we need in our current string is gonna start as an our current string is gonna start as an empty string we need to handle our empty string we need to handle our decisions and we're going to do that decisions and we're going to do that using variables open and close to handle using variables open and close to handle the number of opening and closing the number of opening and closing parenthesis that we'll have so we're parenthesis that we'll have so we're just gonna send in 0 and 0 because at just gonna send in 0 and 0 because at first we have an empty string 0 opening first we have an empty string 0 opening 0 closing parentheses right and then 0 closing parentheses right and then we'll say okay if open is less than max we'll say okay if open is less than max if open because max is the number them if open because max is the number them gonna be the maximum number of opening gonna be the maximum number of opening in the maximum number of closing in the maximum number of closing parentheses we can have so open is less parentheses we can have so open is less than max which is 3 then that means we than max which is 3 then that means we can backtrack we can call our recursive can backtrack we can call our recursive method with the output array we call it method with the output array we call it with the current string but we're gonna with the current string but we're gonna add an opening parenthesis 2 because add an opening parenthesis 2 because open isn't at the maximum number of open open isn't at the maximum number of open parenthesis we can have yet then we're parenthesis we can have yet then we're going to Inc we're gonna pass in our going to Inc we're gonna pass in our open variable plus 1 and then we're open variable plus 1 and then we're gonna just pass in the same closing gonna just pass in the same closing variable we're not adding it closing variable we're not adding it closing here and then max so this is a decision here and then max so this is a decision that we're making so you hit you call that we're making so you hit you call all possible decisions what's the other all possible decisions what's the other decision decision well if closed is less than open because well if closed is less than open because we have this condition if closed if we we have this condition if closed if we we would do closed less than max 2 we would do closed less than max 2 because we want to have the maximum because we want to have the maximum number of opening and closing number of opening and closing parentheses right parentheses right but we do closes less than open because but we do closes less than open because we cannot have closing parenthesis we cannot have closing parenthesis before opening parenthesis so there you before opening parenthesis so there you go this time it's the same thing this is go this time it's the same thing this is our other decision but you have that our other decision but you have that check because you can't have closing check because you can't have closing before opening so as long as closes less before opening so as long as closes less than open that means there's an open and than open that means there's an open and you could have a corresponding closing you could have a corresponding closing one there so we had a closing one this one there so we had a closing one this time open stays the same and then we do time open stays the same and then we do closed plus one and these will do closed plus one and these will do recursive calls and I'll do a recursive calls and I'll do a walk-through of how this works so this walk-through of how this works so this should be pretty much it so these the should be pretty much it so these the string basic I'll talk about it one more string basic I'll talk about it one more time error cannot be applied to given time error cannot be applied to given types what is this so we pass in the types what is this so we pass in the output array which is the list of output array which is the list of strings straight up within sorry we strings straight up within sorry we didn't add the parameters for those so didn't add the parameters for those so we say int open and to close I have to we say int open and to close I have to redo this video because it's a little redo this video because it's a little bit messy there we go so that is the bit messy there we go so that is the solution for the backtracking solution solution for the backtracking solution great let me do a code walkthrough I great let me do a code walkthrough I wrote this out a couple minutes ago and wrote this out a couple minutes ago and let me just talk about it one more time let me just talk about it one more time so let's just think about it so let's just think about it backtracking is where you have we have backtracking is where you have we have this list right and it's usually done this list right and it's usually done with permutations or subsets or with permutations or subsets or generating you know different kind of generating you know different kind of permutations or different get all permutations or different get all possible combinations where our possible combinations where our backtracking does that kind of stuff backtracking does that kind of stuff usually it's like two to the end kind of usually it's like two to the end kind of problems all right and basically this is problems all right and basically this is how it looks every single time you just how it looks every single time you just have your your output data structure you have your your output data structure you call a backtrack method with some call a backtrack method with some initial data and there's these possible initial data and there's these possible decisions you can make so you have your decisions you can make so you have your backtrack method here you take in your backtrack method here you take in your data structure and you call these data structure and you call these possible decisions right this in this possible decisions right this in this case our possible decisions is okay we case our possible decisions is okay we have this current string we have this have this current string we have this empty string do we want to add an empty string do we want to add an opening or do we want to have a closing opening or do we want to have a closing to it right now and we always want to to it right now and we always want to add opening before closing so you just add opening before closing so you just do as long as opening isn't at the do as long as opening isn't at the maximum number of opening parenthesis we maximum number of opening parenthesis we can have because we can only have up to can have because we can only have up to a certain amount of pairs then we add an a certain amount of pairs then we add an opening and as long as closed is less opening and as long as closed is less than open because we can't have closing than open because we can't have closing before opening parenthesis then we add a before opening parenthesis then we add a closing brace we increment these closing brace we increment these counters and we do these checks just to counters and we do these checks just to make sure we're not going out make sure we're not going out sounds like the openings less than max sounds like the openings less than max closings less than opening and we just closings less than opening and we just check we the string will always when it check we the string will always when it gets added to that output array be the gets added to that output array be the size of max times two that's exactly size of max times two that's exactly what we're aiming for right because we what we're aiming for right because we want this number of pairs of parentheses want this number of pairs of parentheses right so three number of pairs of right so three number of pairs of parentheses gonna be size six string parentheses gonna be size six string every time so we just do a check okay is every time so we just do a check okay is our current string at the maximum length our current string at the maximum length times two and we could add it to our times two and we could add it to our output array and we do this and if you output array and we do this and if you go through the test cases here I have go through the test cases here I have this big thing written out right so this big thing written out right so let's look at a test case of size two so let's look at a test case of size two so n is equal to two right basically well I n is equal to two right basically well I have it written out so I have all the have it written out so I have all the variables right now current is set to variables right now current is set to zero is set to an empty string this is zero is set to an empty string this is our output array we're looking at n is our output array we're looking at n is two right that's what we hit pass in our two right that's what we hit pass in our max is two because we send it we take in max is two because we send it we take in max as a parameter and we pass in 2n as max as a parameter and we pass in 2n as max right so the max pairs we could have max right so the max pairs we could have is to open and close start at zero so is is to open and close start at zero so is open less than max is open less than max open less than max is open less than max that's what we're checking right away is that's what we're checking right away is zero less than two yes it is so you do a zero less than two yes it is so you do a recursive call and you do the string recursive call and you do the string plus an opening parenthesis and you plus an opening parenthesis and you increment open now this is all recursion increment open now this is all recursion inside of there the other call after inside of there the other call after that is is close less than open is close that is is close less than open is close less than open false because zero is not less than open false because zero is not less than zero at this point okay great less than zero at this point okay great we're inside that that's this whole we're inside that that's this whole first recursive call doesn't even get first recursive call doesn't even get called so this never gets called called so this never gets called initially on there now we're inside of initially on there now we're inside of the recursion right so we're inside we the recursion right so we're inside we got now open is one so we do another now got now open is one so we do another now we have these methods again inside of we have these methods again inside of the recursive call because it does the recursive call because it does everything over again okay it's one less everything over again okay it's one less than two so it's another recursive call than two so it's another recursive call in there and you add another opening so in there and you add another opening so this is double openings and you can see this is double openings and you can see where that gets goes headed and then where that gets goes headed and then close is close less than opening yes close is close less than opening yes zero is less than one inside of the zero is less than one inside of the recursive call and then you do the recursive call and then you do the opening and then the closing parenthesis opening and then the closing parenthesis and then it's another you know and then and then it's another you know and then it keeps going in the recursive call I it keeps going in the recursive call I don't want this video to go on too long don't want this video to go on too long so maybe you could pause and like look so maybe you could pause and like look at all of the stuff I planned out but at all of the stuff I planned out but basically there's recursion inside of basically there's recursion inside of there so it was opening less than max there so it was opening less than max yes it's one less than two so then you yes it's one less than two so then you add add another opening and then eventually it's another opening and then eventually it's another recursion down here is two less another recursion down here is two less than two so that's false in that point than two so that's false in that point and then it closed less than open is one and then it closed less than open is one less than two yes so it ends up being less than two yes so it ends up being this open and closing opening closing this open and closing opening closing which is one of the answers and then which is one of the answers and then there would be deeper recursion in here there would be deeper recursion in here which would end up being I don't even which would end up being I don't even think I wrote all this out think I wrote all this out open open close close and those are the open open close close and those are the two for the two so maybe pause that and two for the two so maybe pause that and look at it that was just a walk through look at it that was just a walk through if you walk through even just N equals if you walk through even just N equals one it'll help you understand this is a one it'll help you understand this is a little bit different than backtracking little bit different than backtracking because we're not doing we have these because we're not doing we have these conditions here which are a little bit conditions here which are a little bit unusual to backtracking but so it kind unusual to backtracking but so it kind of stops us from actually going of stops us from actually going backwards backwards all that much but yeah that's pretty all that much but yeah that's pretty much it for this problem let me know if much it for this problem let me know if you have any questions backtracking you have any questions backtracking problems are probably some of the problems are probably some of the hardest to explain as well as dynamic hardest to explain as well as dynamic programming but you know the template programming but you know the template code is essentially you have a base case code is essentially you have a base case you do all these decisions and when the you do all these decisions and when the condition gets hit it gets added to the condition gets hit it gets added to the output array and returns and eventually output array and returns and eventually you just return the output array after you just return the output array after all the stuff it's usually kind of slow all the stuff it's usually kind of slow compared to other algorithm solutions so compared to other algorithm solutions so let me know if you guys have any let me know if you guys have any questions about this let me know if the questions about this let me know if the solution I give or the explanation I solution I give or the explanation I gave kind of suck I didn't feel perfect gave kind of suck I didn't feel perfect about it here but I felt I don't know I about it here but I felt I don't know I feel okay about it but not that good I feel okay about it but not that good I don't know I'm gonna do a bunch of don't know I'm gonna do a bunch of backtracking once so check out for those backtracking once so check out for those maybe they'll be a little bit better in maybe they'll be a little bit better in the future so let me know what I think the future so let me know what I think let me know if you understand please let me know if you understand please like and subscribe and yeah thanks for like and subscribe and yeah thanks for watching see you in the | 2024-03-19 17:17:48 | 22 | LeetCode 22. Generate Parentheses |
|
XY403-p4dT0 | hello guys welcome to another video in the series of coding let's do the the series of coding let's do the problem which is called rotate list so problem which is called rotate list so given the head of a linked list you have given the head of a linked list you have to rotate the list to write by k places to rotate the list to write by k places let's try to take an example to let's try to take an example to understand this suppose this is a linked understand this suppose this is a linked list that you have list that you have so let's say k is equal to one what are so let's say k is equal to one what are you doing you are rotating all the you doing you are rotating all the elements by one places right elements by one places right and then the last element will come here and then the last element will come here so what will the linked list become one so what will the linked list become one two three four five six and the last two three four five six and the last element seven will get connected if k is element seven will get connected if k is equal to two what what will the linked equal to two what what will the linked list become again you will shift all the list become again you will shift all the elements by one places and then the last elements by one places and then the last element again shifts so what will the element again shifts so what will the linked list become 1 2 3 4 5 and then linked list become 1 2 3 4 5 and then you have 6 7 and then 7 will get you have 6 7 and then 7 will get connected to this okay so if k is equal connected to this okay so if k is equal to 2 this is your answer now let's try to 2 this is your answer now let's try to solve this problem considering this to solve this problem considering this case k is equal to 2 right let's try to case k is equal to 2 right let's try to solve this problem using this example so solve this problem using this example so what do you have to achieve let me write what do you have to achieve let me write it again so uh we have the linked list 1 it again so uh we have the linked list 1 2 3 4 5 6 7 for k equal to 2 what do you 2 3 4 5 6 7 for k equal to 2 what do you have to do have to do for k equal to 2 you have to for k equal to 2 you have to get 1 2 3 4 5 here ok so this block has get 1 2 3 4 5 here ok so this block has to come here 1 2 3 4 5 has to come here to come here 1 2 3 4 5 has to come here then you have to get this remaining then you have to get this remaining block 6 7 at the front once you got this block 6 7 at the front once you got this block you have to connect this block now block you have to connect this block now you have to connect 7 to 1 okay so what you have to connect 7 to 1 okay so what are we doing 7 is what 7 is the last are we doing 7 is what 7 is the last element 7 is the last element 7 is the element 7 is the last element 7 is the last element and one is what one is the last element and one is what one is the first element so basically what are we first element so basically what are we doing one is basically head right so one doing one is basically head right so one is head and seven is let me write last is head and seven is let me write last last note okay last element so last note okay last element so what are you doing once you make these what are you doing once you make these blocks right one to five and then you blocks right one to five and then you have six to seven after which you are have six to seven after which you are connecting seven and one so basically connecting seven and one so basically you are connecting the last element to you are connecting the last element to the head okay the head okay so this is the first thing that we want so this is the first thing that we want to do first we have to get the last to do first we have to get the last element then we have to get the head and element then we have to get the head and we have to connect last element to head we have to connect last element to head so let's go step by step okay so let's so let's go step by step okay so let's make this connection first of all what make this connection first of all what are we doing let me repeat once again we are we doing let me repeat once again we we know k is equal to two that means two we know k is equal to two that means two elements have to come at the front five elements have to come at the front five elements have to come at the back and elements have to come at the back and the last element which is 7 has to get the last element which is 7 has to get connected to the head 7 should get connected to the head 7 should get connected to 1 so let's do one thing connected to 1 so let's do one thing let's try to just do this step then we let's try to just do this step then we will see the further steps okay so let will see the further steps okay so let me start me start basically what you are going to do you basically what you are going to do you are going to find out the last element are going to find out the last element how do you find out the last element how do you find out the last element finding out the last element is very finding out the last element is very simple right we will start with the simple right we will start with the temporary variable okay and then we'll temporary variable okay and then we'll keep moving the temporary variable till keep moving the temporary variable till till what so let's move our temp so temp till what so let's move our temp so temp is equal to times next we will keep is equal to times next we will keep moving our temp we will keep moving our moving our temp we will keep moving our time till we reach this time till we reach this when how do we find the last element so when how do we find the last element so we know the last element when the next we know the last element when the next of temp is equal to null that means we of temp is equal to null that means we reached our last element okay that is a reached our last element okay that is a simple line of code basically if you simple line of code basically if you have seven elements right how many times have seven elements right how many times you will change temp one two three four you will change temp one two three four five six six times if you jump you will five six six times if you jump you will be able to reach the last element okay be able to reach the last element okay so if you have seven elements six times so if you have seven elements six times you make the jump you move temp is equal you make the jump you move temp is equal to ok simply how do you make the jump to ok simply how do you make the jump just give the simple line of code temp just give the simple line of code temp is equal to times next okay this simple is equal to times next okay this simple line of code you will give six times six line of code you will give six times six times it will run so you will reach the times it will run so you will reach the last element how do you know is the last last element how do you know is the last element seventh next will be equal to element seventh next will be equal to null okay so let's write the code then null okay so let's write the code then it will be much more clearer we want to it will be much more clearer we want to just reach the last element okay so let just reach the last element okay so let me write it me write it so reach the last element why do you so reach the last element why do you want to read the last element because want to read the last element because when we rotate by k places what is when we rotate by k places what is happening happening last element is getting connected to last element is getting connected to head so what is happening in our example head so what is happening in our example seven should get connected to one this seven should get connected to one this is what we want so for that we need to is what we want so for that we need to find the last element we already have find the last element we already have the head once we know the last element the head once we know the last element we can just connect seven and one we can we can just connect seven and one we can connect the last element with the head connect the last element with the head okay that's what we want to do so how do okay that's what we want to do so how do we reach the last element so very simple we reach the last element so very simple just i trade the just i trade the i trade the link list okay so reaching i trade the link list okay so reaching the last element is very simple just the last element is very simple just iterate the linked list let me give a iterate the linked list let me give a variable temp temp is equal to head so variable temp temp is equal to head so while temps next is still valid what while temps next is still valid what we'll do we'll do temp is equal to we'll do we'll do temp is equal to thames next okay thames next okay if you if you simply give while temp if you if you simply give while temp then what will happen this will keep then what will happen this will keep running unless temp becomes equal to running unless temp becomes equal to null but we don't want that we want to null but we don't want that we want to make temp equal to the last element okay make temp equal to the last element okay so that's why i am giving this condition so that's why i am giving this condition so what will happen temp will become so what will happen temp will become equal to what temp will become equal to equal to what temp will become equal to 7 and this will exit the loop when temp 7 and this will exit the loop when temp is equal to 7 because 7th next is null is equal to 7 because 7th next is null right so it will not enter this loop right so it will not enter this loop when when it sees that the next of 7 is when when it sees that the next of 7 is null okay so temp will point towards the null okay so temp will point towards the node which is having a value of 7 okay node which is having a value of 7 okay now what you want to do you have got now what you want to do you have got your temp which is the last element now your temp which is the last element now connect this okay connect this and make connect this okay connect this and make its next equal to head so what are we its next equal to head so what are we doing we are connecting seven to one doing we are connecting seven to one which is what we wanted right which is which is what we wanted right which is what we wanted we wanted to connect what we wanted we wanted to connect seven to one so i have connected by seven to one so i have connected by giving this line okay now while we are giving this line okay now while we are doing this what we can do we can also doing this what we can do we can also see how many times we are jumping how see how many times we are jumping how many times are we jumping we are jumping many times are we jumping we are jumping six times right so why is this useful six times right so why is this useful let's see why is that useful okay so we let's see why is that useful okay so we know we are jumping six times so n is know we are jumping six times so n is equal to zero and if we jump six times equal to zero and if we jump six times we will reach the last element now how we will reach the last element now how will we use this n okay let's see now will we use this n okay let's see now what do we have to do next what have we what do we have to do next what have we done till now let me write it again so done till now let me write it again so till now what have we done till now what have we done we have a linked list one two three four we have a linked list one two three four five six seven so what we did now we five six seven so what we did now we reached the last element we know that reached the last element we know that last element was pointing towards null last element was pointing towards null so we broke this connection and we made so we broke this connection and we made the last element point towards one so the last element point towards one so currently we have achieved this but what currently we have achieved this but what do we want to actually achieve if we do we want to actually achieve if we want to rotate by two places what we want to rotate by two places what we want to do we want to achieve one two want to do we want to achieve one two three four five to get connected and we three four five to get connected and we want 6 7 to get connected they are want 6 7 to get connected they are already actually connected we have made already actually connected we have made this connection 7 is connected to one this connection 7 is connected to one okay this part is achieved now we also okay this part is achieved now we also want to achieve the next part what is want to achieve the next part what is the next part next part is we want the next part next part is we want we want phi to point to null okay second we want phi to point to null okay second step is now we want five to be the end step is now we want five to be the end of the linked list currently seven was of the linked list currently seven was the end of the linked list but we the end of the linked list but we connected seven to one okay first part connected seven to one okay first part we have done but the next part is we we have done but the next part is we want to get phi attached to null okay want to get phi attached to null okay because the link list should end after because the link list should end after phi okay this is what we want so how phi okay this is what we want so how will we achieve this will we achieve this see so we want to reach the node which see so we want to reach the node which node do we want to reach we want to node do we want to reach we want to reach the node 5 because we want to reach the node 5 because we want to reach this and make its next equal to reach this and make its next equal to null because when we rotate by two null because when we rotate by two places v d the last node should be equal places v d the last node should be equal to five and its next should be null so to five and its next should be null so how will he reach five it's very simple how will he reach five it's very simple see if k is equal to two right if k is see if k is equal to two right if k is equal to two equal to two if k is equal to two that means that if k is equal to two that means that means means there are two nodes in the beginning and there are two nodes in the beginning and there are five nodes in the end okay if there are five nodes in the end okay if k is equal to two that means there are k is equal to two that means there are two nodes in the beginning there are two nodes in the beginning there are five nodes in the end how will you get five nodes in the end how will you get five nodes in the end so very simple you five nodes in the end so very simple you start again let's say you start a temp start again let's say you start a temp okay you start a temp you keep moving okay you start a temp you keep moving the temp you keep moving the temp how the temp you keep moving the temp how many times you will keep moving the temp many times you will keep moving the temp if you keep moving the temp right if you if you keep moving the temp right if you keep moving the temp till you reach this keep moving the temp till you reach this value right till you reach five so one 2 value right till you reach five so one 2 3 4 4 times you should move the node 3 4 4 times you should move the node temp you will be able to reach the node temp you will be able to reach the node 5. why do you want to reach the node 5 5. why do you want to reach the node 5 phi is the ending node which should be phi is the ending node which should be connected to null we want to reach this connected to null we want to reach this node 5 because we want to connect it to node 5 because we want to connect it to null okay currently it's connected to null okay currently it's connected to seven currently this is connected to uh seven currently this is connected to uh to six currently this connected to this to six currently this connected to this block six seven we want to break this block six seven we want to break this connection i think it's become very connection i think it's become very messy but uh let me try to see this is messy but uh let me try to see this is the connection that we want to break we the connection that we want to break we want to break this connection and we want to break this connection and we want to connect phi to null okay so what want to connect phi to null okay so what we are doing we are jumping temp one two we are doing we are jumping temp one two three four times if we make temp jump by three four times if we make temp jump by four times and we reach this temp here four times and we reach this temp here so we will reach the ending node five so so we will reach the ending node five so how are we going to achieve that so we how are we going to achieve that so we know what is our end n is equal to 6 now know what is our end n is equal to 6 now what is k k is equal to 2 6 minus 2 is what is k k is equal to 2 6 minus 2 is equal to 4 that is the number of times equal to 4 that is the number of times you want the temp to jump okay so if you you want the temp to jump okay so if you jump 10 by 4 times you will reach the jump 10 by 4 times you will reach the node 5 which which is the ending node node 5 which which is the ending node okay so that's why okay so that's why so what we are doing n is equal to 6 so what we are doing n is equal to 6 right n is equal to 6 so what we will do right n is equal to 6 so what we will do we will do n minus k ok this is the we will do n minus k ok this is the number of times you want to number of times you want to make your node jump so let me write jump make your node jump so let me write jump okay this is the number of times okay this is the number of times 6 minus 2 is equal to 4 in our example 6 minus 2 is equal to 4 in our example that means if you make temp if you make that means if you make temp if you make okay this temp which is starting from okay this temp which is starting from the head if you make it jump four times the head if you make it jump four times what will happen you will reach the what will happen you will reach the ending node which you want okay so let ending node which you want okay so let me give the condition while jump me give the condition while jump okay okay let me let me give the condition so give the condition so um um currently uh what is happening is let me currently uh what is happening is let me give again let me give temp temp to give again let me give temp temp to point towards the head okay temp is point towards the head okay temp is starting from the head again so temp is starting from the head again so temp is equal to equal to m star next and jump minus minus so m star next and jump minus minus so these many times if you jump these many times if you jump where will temp point towards stem will where will temp point towards stem will point towards the node phi point towards the node phi why do you want the node five you want why do you want the node five you want to make its next equal to null okay so to make its next equal to null okay so temps next should be equal to null okay temps next should be equal to null okay very good very good now now if you make temps next equal to null if you make temps next equal to null simply okay what will happen if you make simply okay what will happen if you make the node 5 if you make the node 5 its the node 5 if you make the node 5 its next point towards null what will happen next point towards null what will happen you will lose this you will lose this you will lose this you will lose this connection right so you will lose this connection right so you will lose this connection connection you will lose this connection but we you will lose this connection but we want this connection because this 6 7 want this connection because this 6 7 this is the connection that we want if this is the connection that we want if you simply make it null you simply make it null without saving this connection you will without saving this connection you will lose this connection 6 7 we want 6 7 lose this connection 6 7 we want 6 7 because 6 because 6 is the head of the linked list that we is the head of the linked list that we want finally in the answer okay so want finally in the answer okay so before making this null before making before making this null before making this null what we will do we will also this null what we will do we will also store this this is going to be our next store this this is going to be our next head right so this is what we want to head right so this is what we want to return so list node star return so list node star okay ah the head that you want to return okay ah the head that you want to return so let me just call it return this head so let me just call it return this head okay this is thames next because what is okay this is thames next because what is this five is next is what six right so this five is next is what six right so you want to return six six is the head you want to return six six is the head six is the head so before making five six is the head so before making five next equal to null currently the next of next equal to null currently the next of 5 is equal to 6 right this this is the 5 is equal to 6 right this this is the return head that i am declaring return return head that i am declaring return the side because we want to return this the side because we want to return this head so this head i will save in a head so this head i will save in a variable called return head and what i variable called return head and what i will do i will just save it in a will do i will just save it in a variable return head so this is pointing variable return head so this is pointing towards six then i will make them next towards six then i will make them next equal to null so when i do this what equal to null so when i do this what will happen when i do this what will will happen when i do this what will happen this connection will break off happen this connection will break off this connection will break off and files this connection will break off and files next will point towards null okay i have next will point towards null okay i have already stored this already stored this okay that's it so i have achieved okay that's it so i have achieved whatever i wanted to achieve okay whatever i wanted to achieve okay now what i can do i can just give return now what i can do i can just give return return head okay that's it this is a return head okay that's it this is a simple code now it will not work for all simple code now it will not work for all the test cases first of all let's see if the test cases first of all let's see if it's working for the given test case it's working for the given test case see it's working for this test case now see it's working for this test case now for which test case will it not work for which test case will it not work just consider this example too right now just consider this example too right now in this case what are you doing you are in this case what are you doing you are rotating by four times but the length of rotating by four times but the length of the linked list is what length of the the linked list is what length of the linked list is only three so if you are linked list is only three so if you are rotating by four times what are you rotating by four times what are you doing it is same as rotating by one doing it is same as rotating by one times right so what you have to do times right so what you have to do one simple thing you have to do k is one simple thing you have to do k is equal to k mod n that is what you have equal to k mod n that is what you have to do because rotating by four times is to do because rotating by four times is same as rotating by one times okay when same as rotating by one times okay when when when when your size of linked list is three when your size of linked list is three okay so k is equal to k mod n will okay so k is equal to k mod n will ensure that ensure that always uh you your number of rotations always uh you your number of rotations never exchange the size of the link list never exchange the size of the link list okay now let's run the code and see if okay now let's run the code and see if it's going to work so let's submit and see if it's working okay uh that uh i understand why uh why okay uh that uh i understand why uh why it's not working because here n is what it's not working because here n is what n is not the size of your linked list n n is not the size of your linked list n is six right n is six but the size of is six right n is six but the size of the linked list is 7 so we should give k the linked list is 7 so we should give k mod n plus 1 because uh n is 6 but the mod n plus 1 because uh n is 6 but the size of the linked list is 7 so 6 plus 1 size of the linked list is 7 so 6 plus 1 is 7. so the size of the linked list is 7. so the size of the linked list should be the size of the linked list is should be the size of the linked list is n plus 1 but here we give n n plus plus n plus 1 but here we give n n plus plus uh and n became only six so this should uh and n became only six so this should be n plus one now i guess it should work be n plus one now i guess it should work let me sum it and see it should work for let me sum it and see it should work for all the possible test cases okay so now it's not working for the empty test case why is it not working so we should uh because this is not valid right here it's giving error so we can also give one base test case what is the test case if your head is null right so let me give the test case if your head is null or k is equal to 0 in that case you can return head because the no need to do any rotations if k is equal to 0 means no need to do any rotations if your head is null also that's it's pointless okay so it's working for all | 2024-03-20 10:49:36 | 61 | Leetcode 61. Rotate List | Linked Lists | Rotate linked list by k places to right |
|
fSaQhXWe_Z8 | Hello guys morning zinc etc co dot problem nadu solution special in this problem problem nadu solution special in this problem difficult and date of all the is difficult and date of all the is reception level officer and distress and what reception level officer and distress and what mintu mintu time and essence of him and every mintu mintu time and essence of him and every day take bollywood talk time great Can give divine Can give divine Can give divine one to three layer and M2 one to three layer and M2 respectively with me all decisions to get respectively with me all decisions to get jhalar jhalar like time profits of light and like time profits of light and appreciated and bring to front maximum appreciated and bring to front maximum likes and custom of light and opted for likes and custom of light and opted for best possible after dispute preparation best possible after dispute preparation for dipping and features can be prepared for dipping and features can be prepared in in in Certificate In Which I Am Subjective So Different From Latest Crops So Edison Electronic 1250 Add Order And Speed Solution Will Be Difficult For Citizens Should Take A Look At This Problem Number 400 From Development Viewpoint Repairing Biscuit First Giving Taste His Second Hand Due Respect To His Sacrifice For Preparation And This Situation Order In Which Is Preparing To One Thing Which Cannot Be Set Up At A Distance Heavy Fighter Satisfaction Elevated Later Wash Combination Feedback Him Like Never Define Number And Given Date Will Be Pad First Should Be That That election like a writers and top up That election like a writers and top up That election like a writers and top up small number of his adopted such things will be doing this small number of his adopted such things will be doing this website and website and satisfaction on twitter hua tha hua tha 210 satisfaction return gift doesn't mean that you will find a debate on Tuesday and defense staff and debate on Tuesday and defense staff and dissatisfaction among all dissatisfaction among all dissatisfaction among all mx100 it is the president problem vikas they can reduce that to 9 9 the electrical shop so let me show you how candidate who letter suppose i am defining speed that i kamal jeet ke member i represent up to how much Being selected and issues and presents Being selected and issues and presents Being selected and issues and presents how many distance of the how many distance of the solver answer solver answer itself detail should itself detail should that can be reduced available products because of this that can be reduced available products because of this proposal and to fight proposal and to fight decision z is handset selection in few decision z is handset selection in few cases it is rs is have interacted cases it is rs is have interacted and come there is different and and come there is different and and come there is different and show in case if this has been selected then that show in case if this has been selected then that person - one area plus person - one area plus satisfaction S to Z which is the time that taken together 12345 Sez Pe Fasal Moment Page80 Place 12345 Sez Pe Fasal Moment Page80 Place In Fact Were So Is Method Bhavya Jatin Case In Fact Were So Is Method Bhavya Jatin Case In K Sp Sided Picture And When E Decided To Have In K Sp Sided Picture And When E Decided To Have Not Been Shifted Half Velvet Just Dpi Not Been Shifted Half Velvet Just Dpi Famous - One Is Related To Z Minimum Minimum Set Forth Divya Kit Hai to ki in order to calculate spear duty matrix a week and make user today rate the a week and make user today rate the soul is present state bank th10 soul is present state bank th10 president and floated develop office tpi ko president and floated develop office tpi ko me this method limits of interior soya me this method limits of interior soya manager places 500 meters patient care for its quality It It It happened happened that I'm using one plus one year because you will be getting strong that I'm using one plus one year because you will be getting strong with with a ring of disbelief and from icon 202 a ring of disbelief and from icon 202 miles away towards miles away towards betterment today met like it betterment today met like it lusted for his nice lusted for his nice 29 minutes 29 minutes chalu motu patlu chalu motu patlu 25000 better decided 25000 better decided minus one is minus one is minus one is hain to in this case very * thanks for possible sudesh tvs i to maje lo e will be e i maths of maths of a dispute positive a a dispute positive a 102 102 a specific want to time management a specific want to time management chairman s one plus change with time taking chairman s one plus change with time taking and and substance akram the Five minutes ago ki Five minutes ago ki pawar pawar db5 maine se one comedy aa db5 maine se one comedy aa hai hai third wicket third wicket 1530 e sucked and just in case a minus 1530 e sucked and just in case a minus one is not contained from painters painters one is not contained from painters painters deposit hai jo after 10 long pieces accepted as having and value of a The fifth and what will you to kids maximum value from laptop to consider the maximum value of guest cases related to SD card and a debit so let's make this a who is Maxwell that in no way to treat for varicocele phone silent be Bus stand Bus stand Bus stand is a stand is their vestige which has dual which has dual a pig to tp link wifi a pig to tp link wifi i slept that bihar got quality max i slept that bihar got quality max value monitoring of the latest ai instantly transform into sports that 24 nodal influential english App the basis of what do you think specific latest you what do you think specific latest you batting a | 2024-03-21 01:09:35 | 1,402 | LeetCode 1402. Reducing Dishes (Hard) | Dynamic Programming | C++ |
|
MSFlDAPMA3Q | uh today we're gonna be working on need code question number 44 wild card code question number 44 wild card matching matching given an input string s and a pattern p given an input string s and a pattern p implement wildcard pattern matching with implement wildcard pattern matching with support of question mark and star support of question mark and star so the question mark matches any single so the question mark matches any single character character whereas the star matches any sequence of whereas the star matches any sequence of characters including the empty sequence characters including the empty sequence so in this example so in this example s is equal to a a s is equal to a a and b is equal to a so the answer is and b is equal to a so the answer is equal to equal to false false and a does not match the entire string and a does not match the entire string in the second example s is equal to a a in the second example s is equal to a a and b is equal to star and b is equal to star that is also true that is also true as the start match is una super as the start match is una super third example c b third example c b and question mark and a which is equal and question mark and a which is equal to false to false so yeah basically so yeah basically as the rule says we're gonna be as the rule says we're gonna be following we're gonna be trying to following we're gonna be trying to implement all of them implement all of them and and this is gonna be done using uh this is gonna be done using uh using recursion at first we have the at first we have the s pointer and the p pointer both of them s pointer and the p pointer both of them pointing at zero pointing at zero then we have a start index equals to then we have a start index equals to minus 1 and a point 3 equals to minus 1 minus 1 and a point 3 equals to minus 1 okay okay then while then while the pointer is less than equal to y well we pointer is less than equal to y well we are actually are actually while we are trading through the uh the while we are trading through the uh the whole string whole string and our pointer is within that uh and our pointer is within that uh string string if the okay the pointer we are at is less than the and the other one we have to do that like if the for the pattern pointer is less than the p length and uh the the pointer and inside the basically we are saying that at the same point if they are equal if they are exactly equal definitely we will just kind of continue or just we don't have to worry about anything everything is passing both of the characters are the same that is an that is an easy goal we we're just gonna continue easy goal we we're just gonna continue that that or or we the other thing is we the other thing is what if the pointer what if the pointer is equal to a question mark is equal to a question mark right right and the point is equal to the question and the point is equal to the question mark even then mark even then uh uh it means that we can actually say that it means that we can actually say that okay they are okay they are equal equal so we're gonna then increment both the string point and otherwise otherwise what we're gonna be doing what we're gonna be doing is like is like we're gonna be we're gonna be saying is like if the pointer is within saying is like if the pointer is within the range the range for the for the the pattern the pattern and and the value at the the pattern is equal to a star right in that case we're gonna you make use of the start we're gonna you make use of the start index and the pointer index and the pointer so first of all we're gonna say so first of all we're gonna say that that the start index is equal to the the start index is equal to the uh the pattern the p pointer okay so that we remember that where did we see the star and the pointer is gonna become equal to the okay okay and the other thing is that we're gonna and the other thing is that we're gonna increment the increment the uh the p point uh the p point so basically the s pointer is staying so basically the s pointer is staying where it was where it was only the p point is getting incremented only the p point is getting incremented and now and now we want to check that if the star we want to check that if the star this is a star index this is a star index just our index is equal to minus 1 just our index is equal to minus 1 then then that means that that means that we can return false we can say it is we can return false we can say it is it can't be true otherwise it can't be true otherwise the last thing is that if the the last thing is that if the p pointer is equal to the star p pointer is equal to the star uh star index uh star index plus one otherwise we're gonna make the the the pointer for the pattern equal to the star index plus one and the s pointer equal to the pointer plus one and the point is going to become equal to the string pointer and in the end if everything but just before that but just before that uh in the end there's a uh in the end there's a personality check personality check that our index is gonna start with the the patterns pointer and it's gonna stay within the if if the value of the the pattern is not the value of the the pattern is not equal to star we're gonna return otherwise we are returning the otherwise we are returning the true so yeah basically over here first of all uh sorry it's not a recursive it's an iterative uh way of doing it we're not doing the recursion here uh recursion would be another method um of actually doing this thing but we we have done it iteratively and uh basically we are just uh pro program the uh all the different steps they ask for so it did pass so it did pass and now yes if you look at the last step the pointer we the pointer we because because the while loop is just for the string there is a there is a possibility there is a there is a possibility that as pointer has like where we are that as pointer has like where we are out of the we have hydrated the whole out of the we have hydrated the whole string string but still the p pointer has not been but still the p pointer has not been finished yet so there is a possibility finished yet so there is a possibility for that so that's why these line number for that so that's why these line number 30 to 34 is basically checking 30 to 34 is basically checking that that uh basically it is checking that uh if we still have some values left in the p string we're gonna be returning false so that's the last insanity check we had yep yep and it passed all the tests | 2024-03-20 09:28:12 | 44 | Leetcode Question 44 "Wildcard Matching" in Javascript |
|
wCScUo019So | Jhaal Ajay Ko Hello Hello friends welcome to my YouTube channel Teaser CEA Today they are going to solid problem More than 300 problem name is the longest in increasing path in matrix the problem seems to be heart problems between the medium and Bigg Boss Bigg Boss Bigg Boss Problem Statements Similar Dolata Problem Statements Similar Dolata Problems Which After You Need For The Number Problems Which After You Need For The Number And Five From The Sources Destination Problem And Five From The Sources Destination Problem Solved Problems Treatment And Solved Problems Treatment And Research Research Center Should Be Written Language Starting From Written Language Starting From Delhi Police To Delhi Police To That Subscribe Now To Cash Details In This Book Subscribe Now To Cash Details In This Book Subscribe Now To Cash Details In This Book one month ago and continued to modify the small element and oil we don't have to dabodia until we have crossed Pandey so we can free so how can we do it like we have 4630 I have to start each mode from a specific playlist, hey traveling and how long can I keep traveling there, I will keep getting bigger, we reached here from here, we could have brought from here also, so we will add edifice from here to more from here and add to both of them more from here and add to both of them We will also take it into this so that We will also take it into this so that when we come again from this location while doing a table, we will when we come again from this location while doing a table, we will know what we get from here onwards, know what we get from here onwards, how much Navlesh Pathak does because how much Navlesh Pathak does because look, there will be time problem overlap because look, there will be time problem overlap because when I start Monday, I will spend Monday when I start Monday, I will spend Monday somewhere else. somewhere else. somewhere else. and then I will return from there, then I have the post of some teacher that education further does not make any belongings pregnant, see it works, can go to the temple of education, last but that means can especially the body is small And anyway, if he cannot go up to the next third, And anyway, if he cannot go up to the next third, And anyway, if he cannot go up to the next third, then dip maintenance will be done along with it then dip maintenance will be done along with it and we will use it so that and we will use it so that if tomorrow we are in the same position, then we will know if tomorrow we are in the same position, then we will know how much more office we could get from that position. how much more office we could get from that position. cut quickly come that cut quickly come that Bhojpuri every to variable eminent today Bhojpuri every to variable eminent today mission for the matrix images to make this planet and request mission for the matrix images to make this planet and request matrix 80 daughter length le deutsch ki no real estate answer pimple contain very ki no real estate answer pimple contain very place bear place bear ki insan sir ko maximum karna toh ki insan sir ko maximum karna toh interest and interest and interest and install democracy in minimum, it has to be maximized, after that comes visit, we make boolean type visit here on a request, we are bullion as a cute about that too, cute about that too, seams. seams. seams. paper interior because in this we will check whether it is tap or not because if we make morning curve then default value is toe, if we make capital ampere then money default value is smell that this amendment that The point is The point is The point is request to sir request to sir phone point is request to sir roy is phone point is request to sir roy is letter mi plus plus app hai aur intaj try roz cent and z plus ki after this why will the answer go answer is question math dot maximum ho ki they sansad By using fashion type, By using fashion type, By using fashion type, visit it and now once, we will start from here, so there is no value before this, compare it, then call it - - - - - - - Verb - and in the last turn on Great do Great do Great do private institute is difficult-1 Hum private institute is difficult-1 Hum previous value first kitni vyatipat hi it will take we previous value first kitni vyatipat hi it will take we retail pack hum retail pack hum Columbus se Columbus se zara type matrix hai the matter zara type matrix hai the matter poems and big billion type hai poems and big billion type hai ek budhiya revisited and also takes ek budhiya revisited and also takes interior type today are hindi interior type today are hindi ki ki Entry conditions in nine What if disease maintenance becomes Entry conditions in nine What if disease maintenance becomes zero then zero then go then go then our column but becomes zero or our column but becomes zero or our stop and greater than become our stop and greater than become matrix start land from net minus one matrix start land from net minus one or a or a room column greatest me from matrix room column greatest me from matrix or WhatsApp or WhatsApp give the condition of 1000 villages. Then it comes that if it give the condition of 1000 villages. Then it comes that if it is Britain, we is Britain, we can check the validity that if there can check the validity that if there is something in BP then return DP it is O Ma in Hindi Peeth R Ko Mixi Snow Devotional It is not codinal then we It is not codinal then we It is not codinal then we can check the cancel of the record can check the cancel of the record in the beginning that if it is visited in the beginning that if it is visited or visited or or visited or at that position of the matrix which was the value of R to Christ, what should it be what should it be Bujlu strain or equal to that. Bujlu strain or equal to that. Bujlu strain or equal to that. want feminine gender, we can't take them one time, we can get 141, we want only you after Vansh, then equal to the previous value, top seed return 087 of Om Shri Nandishwar, who went and calls, four very brahmins take your It happened, I became brown, I turned left, left for the It happened, I became brown, I turned left, left for the It happened, I became brown, I turned left, left for the shell shell and right, ok, right side, call for the moment, there is and right, ok, right side, call for the moment, there is talk of media, celebration, when will we change the previous value, from whom will the current Baloch be ours, that after this, everything will Syria's net Syria's net Syria's net will go and if you know then you mean in Kaya Ro me will go and if you know then you mean in Kaya Ro me minus one minus one melted can visit Android melted can visit Android DPO gone and shampoo for remaining free from DPO gone and shampoo for remaining free from the A variable Here also we will just the A variable Here also we will just change the deductions Do dipna do change the deductions Do dipna do - from one - from one Assessment and lunar hai toh roz day scholar Assessment and lunar hai toh roz day scholar minus one right hain to go to roz justice column minus one right hain to go to roz justice column plus one quote I one thing and when we come, what am I to do first of all Existed Markar why did he visit his mother on that point Let's do that he has to Let's do that he has to Let's do that he has to fold the widget, why fold the widget, why not fold it and I have found out from the technicalities not fold it and I have found out from the technicalities how much is the long waiting pass, if I do how much is the long waiting pass, if I do n't force it then it will travel in one go n't force it then it will travel in one go and then after that it will not and then after that it will not work again. You will keep getting returns from the visit. work again. You will keep getting returns from the visit. Daily what we have is return last declared Daily what we have is return last declared fit in DP and on the machine fit in DP and on the machine what will be the rally to the value death in method mixer is method maximum of again e method maximum of again e is to take maximum with it is to take maximum with it that I dot maximum officer up of wheat that I dot maximum officer up of wheat which mixer which mixer which mixer last with him left and finally question why question is the point in which he started in one count go to New Delhi ok is regular ok semicalculus New Delhi ok is regular ok semicalculus is meeting is meeting 8th location 8th location Jhala ok that 515 Kumar takes a look, I break the maximum objective, okay, you, it was a mistake, we have time, got the DP checked in advance, a chairman will check the DP first, then if tomorrow I know that while entering from here, it will I know that while entering from here, it will I know that while entering from here, it will not be there in the DP not be there in the DP because already once our loop had because already once our loop had started due to this quiet, now only started due to this quiet, now only Pina will match its next Pina will match its next value. If you have made small or big deposits, then get value. If you have made small or big deposits, then get that checked first. that checked first. that checked first. this sequence later, if we are feeling dizzy then it is wrong, this is why ours is the longest fiber while it is four because they will check it without returning it from DP, then we will keep the duty for later, So we will give an example on this, once you see the summit, there was loot on this occasion, so if you liked the video, please comment, subscribe the channel, | 2024-03-24 10:39:18 | 329 | Leetcode 329. Longest Increasing Path in a Matrix |
|
CrDZmxtb2_k | Hello guys welcome to code fix otherwise so let's start now date code problem start now date code problem date code problem i maximum score of good date code problem i maximum score of good all so let's get into this problem so all so let's get into this problem so today's problem today's problem is a little tricky to understand. is a little tricky to understand. is a little tricky to understand. very simple to solve, so if you listen a little carefully, in this question you must have given yourself an array and a value. Now what do you have to do? Find one such answer from this array. Whose value of this formula should be maximum and we have to return the same maximum value, this is our simple question, now once we see this formula, then what do You have to You have to extract the minimum value from the one you have chosen and you have to substack both the positions from which you have chosen in the morning and add plus one inside it, then you will multiply these two values. So your formula will be created, okay, and you have to tell yourself which of your items are there for which the value of this formula will be maximum and you have to return the same maximum value, this is your simple question, now you must be That all this is fine but That all this is fine but That all this is fine but what is the use of this here, so this is the work of this what is the use of this here, so this is the work of this here, there is one more condition in it that here, there is one more condition in it that whatever position we take in the morning, this whatever position we take in the morning, this position must come in it, so whatever we take in the position must come in it, so whatever we take in the morning morning morning and from that, the maximum value of our formula should come and we will return the same maximum value. This is a simple question, so if we look at this question with this example, then In the example, I have In the example, I have In the example, I have given this one to myself and this is my cape. given this one to myself and this is my cape. Now, which is my third position, this is my Now, which is my third position, this is my zero position, first position, second zero position, first position, second position and third position, meaning this is the seven, come position and third position, meaning this is the seven, come in your own hands. in your own hands. in your own hands. should come and then tell yourself that if you apply this formula in your morning then who is the person for whom the value of this formula will be maximum and you will return the same maximum value, okay If we see, If we see, If we see, to solve this, to solve this, first of all we will keep only one value in our sabre, first of all we will keep only one value in our sabre, that will be the value of Apna, then what will that will be the value of Apna, then what will become of our sabre? Surf in our sabre, we will have only one value, that will be s. become of our sabre? Surf in our sabre, we will have only one value, that will be s. Now, Now, what will be the starting position of our sabre? what will be the starting position of our sabre? what will be the starting position of our sabre? equal to k, meaning it will be equal to k and its ending position will also be equal to k and it has satisfied its condition that whatever is i is also equal to k and whatever is h is also equal to k, okay. So once you find out the value of this formula then what you have to do is you have to find the minimum value of your morning. Now there is only one value in your morning then that will be its minimum If you If you If you calculate and see that the value of your last and first calculate and see that the value of your last and first is the same then your 3rd and first minus will become is the same then your 3rd and first minus will become zero and you will be left with only one, zero and you will be left with only one, then what will be the value of this formula of yours, if then what will be the value of this formula of yours, if 7 new equals to 7 then what will you do with 7 new equals to 7 then what will you do with this once you get the result? this once you get the result? this once you get the result? that after this, if we find any such sub-section, then for this we are getting a big value from this formula, then what will we do, we will update our result. Okay, so our first sub-section is What will you do in your next sub-section? We will What will you do in your next sub-section? We will expand our sub-section a little, now we will expand it like this because we want the minimum value of our formula to be a little bigger so that if the value of this formula becomes big, what will we If we If we If we look at the value below, we have two values, look at the value below, we have two values, three and four. Okay, then which of those two three and four. Okay, then which of those two values will we keep in our sub array? Obviously we will keep four in our sub array because our minimum value keep four in our sub array because our minimum value should be a little larger. should be a little larger. should be a little larger. minimum value becomes large, then the value of your formula will also become big. Okay, so along with intake in the morning, we also keep four in our morning. Okay, then The starting The starting The starting value of is still three and its ending value of is still three and its ending value has become four. Okay and value has become four. Okay and what is the minimum value of its morning? The minimum value of its morning has become what is the minimum value of its morning? The minimum value of its morning has become four and if we four and if we calculate this portion then our j4 calculate this portion then our j4 is and i3. is and i3. is and i3. one and if we do our plus one inside it then it will become two, so the value of our formula is 4 * 2 which is eight which is greater than seven, so by OK, OK, OK, now we will go back to the same formula. Now now we will go back to the same formula. Now what is the value of front and back of this saber? what is the value of front and back of this saber? 3 of F. If there is obviously a five out of these two, 3 of F. If there is obviously a five out of these two, then what will we do? We will then what will we do? We will choose our five and add five to our sabre. choose our five and add five to our sabre. Okay, now your starting Okay, now your starting value is still the same and value is still the same and what is your ending value? Your ending value has become what is your ending value? Your ending value has become five and five and what is the minimum value from inside it? The minimum value from inside this what is the minimum value from inside it? The minimum value from inside this is four and if you have this portion. is four and if you have this portion. is four and if you have this portion. calculate j - aa, how much is j minus eight, then if you add plus and within it, you will get 3, then 4 * 3, how much will 4 * 3 become, then you will get 12, so update your result to 12. Okay, now let's go back to the front and back values of our saber. Now there is no value left behind, so what will we do? If we add the front value to our saber, then Now Now Now what is your starting value left? Now your what is your starting value left? Now your starting value has become to and your starting value has become to and your ending value is still there. Okay, ending value is still there. Okay, now what has become the minimum value in your morning? What has become the now what has become the minimum value in your morning? What has become the minimum value in your morning? minimum value in your morning? And your ending value is still there. And your ending value is still there. And your ending value is still there. calculate the potion, then j minus a will become 3 and plus and will become 4. Okay, so 3 and 4 will return 12, which is equal to your result, so we will not update our result, We will We will We will add the value inside our sub-bar add the value inside our sub-bar which will be four, which is still our minimum which will be four, which is still our minimum value, our minimum value is still three, our value, our minimum value is still three, our range has been updated, the range has been updated, the starting value has become our one starting value has become our one and the ending value is now and the ending value is now and the ending value is now okay, your minimum value is three now and what will you do with it, if you multiply 5 - 1 4 by 1 5, then how much does 3 * 5 become, it becomes 15, which is We will We will We will update it to 15. update it to 15. Okay, then what will we do? We will Okay, then what will we do? We will increase our range again and will increase our range again and will also add one in our sub area. Now also add one in our sub area. Now what is our range? Starting what is our range? Starting value is zero and ending value is five value is zero and ending value is five but now our but now our What has become the minimum value of Saberi? It has become one. Okay, What has become the minimum value of Saberi? It has become one. Okay, and what will we add inside it? 5 - 0 and what will we add inside it? 5 - 0 5 + 1 6 So what is your answer? Your 5 + 1 6 So what is your answer? Your answer is six, which is much smaller than 15, answer is six, which is much smaller than 15, so so so and 15 is your answer, that means both your question and approach have understood well what you will do, you will try to make all the priority first of all, keep only the value of your a in it, which will Once you find your value from it, you will Once you find your value from it, you will Once you find your value from it, you will see your answer. Whatever the answer see your answer. Whatever the answer is, you will store it in your result. is, you will store it in your result. Then you will see what is the Then you will see what is the front and back value of your value. We will front and back value of your value. We will create two points for both, which will be create two points for both, which will be create two points for both, which will be value will be larger, we will add that value to our sub-array and update our range accordingly. Okay, then we will extract our minimum value from that sub-array and multiply it by whatever is there in It is It is It is fine with that value, then if whatever result you fine with that value, then if whatever result you get is greater than your previous result, then get is greater than your previous result, then what will you do? You will what will you do? You will update your result and update your result and do the same for the whole morning and do the same for the whole morning and whatever your answer will be in the last, you will update it. whatever your answer will be in the last, you will update it. whatever your answer will be in the last, you will update it. This is my simple question. Once you see its coat, I have done something new for its coat. This time I have used do by loop because I have not used do by loop for a long time. So, this is a question in which you can use your for loop. Before this, what did I do? I have created a minimum inside which we will see the minimum of our morning. What did I do inside that? Now I have given my key value i.e. the key I have kept the value I have kept the value I have kept the value because there is only one value in my saber, because there is only one value in my saber, that is my kth value, so that is my kth value, so what I have done to it is that I have stored it in my minimum, my what I have done to it is that I have stored it in my minimum, my i means my starting value, my i means my starting value, my starting position will also be starting position will also be equal to k. equal to k. equal to k. also be equal to k and its result will be its kth value in that case because what will happen inside this is that the minimum value of k which I see is also its geth value, let's assume seven is okay Along with that, we will also multiply our one by one Along with that, we will also multiply our one by one Along with that, we will also multiply our one by one because if our starting and ending because if our starting and ending positions are the same, then both of them will be minus positions are the same, then both of them will be minus zero and only our one zero and only our one will be left inside it. Since 7 * 1 is obviously the same, we will will be left inside it. Since 7 * 1 is obviously the same, we will multiply our one with any one. multiply our one with any one. multiply our one with any one. same answer, what did I do in my result? Apna names off means I stored the value of Apna. Then what I did was I used my do by loop. Inside this I first said is is is also greater than zero and your ending also greater than zero and your ending position is also smaller than the size of your array, position is also smaller than the size of your array, then what will you do, i.e. the then what will you do, i.e. the position of i - 1 and the position of i - 1 and the position of t i - i, i.e. one in position of t i - i, i.e. one in front and one in the back of your array. front and one in the back of your array. front and one in the back of your array. to see which one is bigger. If the value of our starting position is bigger then we will make our Aa minus minus that means we will take the value of our starting position as our left otherwise we will Well Well Well position means we will give the value of ending p, position means we will give the value of ending p, ok then what will we say ok then what will we say that if this condition is not true, if there is that if this condition is not true, if there is a but value, it has already exceeded its a but value, it has already exceeded its meaning aa if equal has become equal to zero meaning aa if equal has become equal to zero and j now. and j now. and j now. size of numbers minus v means size of our array - 1, so what will we do, we will pick only the last value because our starting value is already within its sub-array and if the That Apna J means Apna That Apna J means Apna That Apna J means Apna ending value has ending value has reached the size of Apna array but Apna reached the size of Apna array but Apna starting value is also left so starting value is also left so what will Apna do, Apna will what will Apna do, Apna will take the starting value. Ok then what will Apna find in AA? take the starting value. Ok then what will Apna find in AA? minimum of sabar, it is okay that minimum of sabar, it is okay that whatever is in our minimum is our minimum, our whatever is in our minimum is our minimum, our number of a is minimum or our number number of a is minimum or our number of J is minimum, whatever is the minimum, it will of J is minimum, whatever is the minimum, it will come in our minimum, do not come in the minimum of our sabar. come in our minimum, do not come in the minimum of our sabar. Okay, then we will get our result. What will we see in our result whether our previous result was What will we see in our result whether our previous result was increasing or this formula of ours is increasing or this formula of ours is bigger, whatever is bigger will be included bigger, whatever is bigger will be included in our result and this will happen throughout the in our result and this will happen throughout the morning. morning. morning. return our result, this will be our simple yes it is getting submitted, that yes it is getting submitted, that means it is a completely accurate solution, you can consider it absolutely, means it is a completely accurate solution, you can consider it absolutely, hope hope you must have understood it. you must have understood it. you must have understood it. video, subscribe the channel and if you have any doubt then please mention it in the box, we are always present to solve your doubt, thank you so much thanks for watching, have nice [music] | 2024-03-22 14:49:04 | 1,793 | 1793 || Maximum Score of a Good Subarray || C++ || Leetcode Daily Challenge |
|
JkWDKg_pNME | Hello friends, welcome to the new video, question number 54 Spiral Matrix question number 54 Spiral Matrix is a very famous question, this question is a very famous question, this question is a medium category question, is a medium category question, Spiral Matrix Too, you will also get similar code in the late chord, do one question in ninety percent, both will be one question in ninety percent, both will be made in the video. made in the video. made in the video. *Matrix has been said to have two elements. You have to print all the elements in spiral order. It is okay if you want to print all the limits of the matrix and then it is very easy to print it by applying a loop If you want to print a spiral, If you want to print a spiral, If you want to print a spiral, then take a quick look at then take a quick look at what is the spiral matrix. You are seeing that the what is the spiral matrix. You are seeing that the circle, the circle, the circle is getting smaller and smaller inside, circle, the circle, the circle is getting smaller and smaller inside, this is the spiral matrix, okay, this is another this is the spiral matrix, okay, this is another example of spiral matrix and this example of spiral matrix and this graph is an example of spiral matrix. graph is an example of spiral matrix. graph is an example of spiral matrix. don't waste time, this is a bit boring question but it is a famous question which can be asked in the interview and all these are very common so you will have to do this once. Okay so how to print spiral matrix so if Let's do some subjects and then we will Let's do some subjects and then we will Let's do some subjects and then we will start the food. Okay, so if I start the food. Okay, so if I go spiral, you saw that first go spiral, you saw that first you have to print the first stop, so you have to print the first stop, so in this case, I should print 123, this is easy, in this case, I should print 123, this is easy, even we can think about that and you. even we can think about that and you. even we can think about that and you. also seen that after 36 bomb crops, we are till 3693 are printed in it, then these 6 and 9 till 3693 are printed in it, then these 6 and 9 would like to come down, okay after that we would like to come down, okay after that we came here, now I will go reverse, meaning to came here, now I will go reverse, meaning to make a circle. make a circle. make a circle. I have come to 9 inches, now I will increase by 80 seconds, it is 876, so you will see, now after that I will sit up to complete the circle, then this is 747 and the throw is done, I have printed it, after four, I am now up. I am not going to reach the circle, I have become smaller, first I have done low process, then I am getting right moonlight in seconds, then I will do more sir, then you have made some observation that this disease was being talked about, I was going like this, then I was going like this, then I was going like this, then you must have seen that we are processing this column, you must have seen that we are processing this column, okay then you must have seen that okay then you must have seen that we are processing this column, then we are processing the last diseases, we are processing this column, then we are processing the last diseases, then you must have seen that we then you must have seen that we are processing this column, so this are processing this column, so this are processing this column, so this stop others, rotate columns, then column, so if you have double to access one boil, you have double to access four for loop and you can update five integers of the count, then you This question is not You will be able to do it and this is a very easy question. I have done it three-four times. I have doubts about it. Please do it in August and give a final answer. Let's understand. Let's come to the code. Okay, look. There are five interiors. Tell us yourself. He said So see how So see how So see how you will start, take the new left, this is your left you will start, take the new left, this is your left column, okay, tell him that we column, okay, tell him that we are on the left column, and tell him that we are on the left column, and tell him that we are on the right column, okay, tell him that we are on the right column, okay, tell him that we are this top rope, okay and are this top rope, okay and are this top rope, okay and that we stop this bottom, if I say bottom then either you understand who is being talked about, if the word bottom is coming, that top is big then I am talking about prop rooms and left If you talk, then you say that let's If you talk, then you say that let's If you talk, then you say that let's talk about the columns, this is the left column, this is the talk about the columns, this is the left column, this is the right column in the middle order, so right column in the middle order, so what to do, first we have to print the toppers, what to do, first we have to print the toppers, okay, then we have to print the l column, the right column, okay, then we have to print the l column, the right column, then we have to print the bottom rows, then we have to print the bottom rows, then then then moving around like this and saw the direction, this is our one direction, so if I take this as DJ 120, then you saw that I am coming down, if we call the directions two less, diesel two one. Our third direction is okay, we are going from right to left in the third operation, we are pressing the button, we are going to the long platform to light the light, so the direction is the second, after that you saw that the direction is the third, I accept it as the It is going up to the toppers and it is It is going up to the toppers and it is It is going up to the toppers and it is taking up our left column completely. taking up our left column completely. Okay, so now after being free, we will be roaming again, there will be Okay, so now after being free, we will be roaming again, there will be three of the directions, Ghee will be made every day, three of the directions, Ghee will be made every day, this action will go, the this action will go, the structure will be thick. Have you understood the code of the court? structure will be thick. Have you understood the code of the court? Okay, we will not make the video too long. We will do Okay, we will not make the video too long. We will do this in the court. First of all, we this in the court. First of all, we said that we have * and matrix, so we have to said that we have * and matrix, so we have to find out how many rows are find out how many rows are there in it. So let's do the basic setup. First, there in it. So let's do the basic setup. First, okay, the number and how much is the good column. okay, the number and how much is the good column. okay, the number and how much is the good column. columns would you know how to remove, look at the columns of E0, there will be so many columns in each, so there are three columns of zeros. Okay, these two are finished, do good work, return type our list, don't print it. One way to Make it Make it Make it okay, I would like to name this loot as a list, okay, I would like to name this loot as a list, what is the use, if you see something else, what is the use, if you see something else, okay, I have made the list, okay, okay, I have made the list, okay, this is done, now what to do after that, this is done, now what to do after that, handle the shares of one base, in the beginning handle the shares of one base, in the beginning all these things. all these things. all these things. length of your matrix is basically A, then stop it. If yours is 0, then return your MP list A. There is no need to do any processing. Okay, now I would like to tell you Let's see Let's see Let's see how we will understand the concept of this. how we will understand the concept of this. Now see, if I say that I Now see, if I say that I processed the toppers, then I printed these three, processed the toppers, then I printed these three, then next time when we were then next time when we were coming in the circle, I was not rotating on the toppers again, coming in the circle, I was not rotating on the toppers again, then where did my toppers go? then where did my toppers go? My top disease was gone, we had increased one that My top disease was gone, we had increased one that this process was done, the proper one had come here, in the this process was done, the proper one had come here, in the same way, if this right one was my same way, if this right one was my process, then my right one process, then my right one was come here and in some time you will see that the left one will be was come here and in some time you will see that the left one will be processed. processed. processed. one part will go and at one time the left row will go ahead of it, okay so something like this will keep happening, then we have to stop the processing, okay when our Then if Then if Then if our top goes ahead of our bottom then our top goes ahead of our bottom then this is a condition, you have to walk holding it, you have to this is a condition, you have to walk holding it, you have to remember remember that as long as your left that as long as your left is less than or equal to the right on physical Twitter, your top which is is less than or equal to the right on physical Twitter, your top which is less than or equal to your bottom is fine. less than or equal to your bottom is fine. less than or equal to your bottom is fine. you have to do this, then make a Tushar declaration to make the interior. What will be the left? The left problem will start from the left over. Okay, the left column will start from 0. Okay and we will leave the top top. Where will the right worm come from, what is its length, which is Column is, it will go till our column, but Column is, it will go till our column, but Column is, it will go till our column, but this is one less in zero base indexing. this is one less in zero base indexing. You know, the index on the right side of the You know, the index on the right side of the column will be minus one, in the same way, the top will be column will be minus one, in the same way, the top will be from Pro0, the promise to is the last bottom row, from Pro0, the promise to is the last bottom row, how many will be mine as many as ours. how many will be mine as many as ours. how many will be mine as many as ours. many as we have, that will be the button, this is done, row minus one, okay, that's it, we have done that, now let's take a direction, we have to do it ourselves, this direction is ours, I took the direction from zero, in the beginning, One will go to two, then it will go to free, then it will go to One will go to two, then it will go to free, then it will go to One will go to two, then it will go to free, then it will go to zero. The video will seem a bit boring zero. The video will seem a bit boring and it is a matrix question but once and it is a matrix question but once you have to understand the contact, after doing this, first the you have to understand the contact, after doing this, first the matrix is two same code. Okay, now let's matrix is two same code. Okay, now let's start the court, so let's see start the court, so let's see what to do now. what to do now. what to do now. then the direction of the people, then you do direction one, two, okay, if you want to keep doing it in this way, then do direction, you press two, okay, this is making the structure So keep it So keep it So keep it ready and then start coding. Okay, this is the basic ready and then start coding. Okay, this is the basic installation. Basic shut up. installation. Basic shut up. Now this is the direction and for us, Now this is the direction and for us, your work is done till then. Zero 123 and your work is done till then. Zero 123 and okay and we will print this traction. okay and we will print this traction. Finally, you will make your Finally, you will make your Finally, you will make your answer has come, let's start the directions, process it, then stop the direction, do one process, do darshan, do the process on you, free the direction, press free, turn the direction back to zero, Well, this is also done, if you want to process it, Well, this is also done, if you want to process it, Well, this is also done, if you want to process it, initially you have to print 123, then initially you have to print 123, then you have to print the toppers, but if you you have to print the toppers, but if you change the mood from left to right, then our left change the mood from left to right, then our left or right will work, this thing has to be kept in mind, you will or right will work, this thing has to be kept in mind, you will code it once or twice, it will be remembered. code it once or twice, it will be remembered. code it once or twice, it will be remembered. where will the direction go, it is at zero, first our intermediate will go from left to right and from left to right, okay I am plus plus and after that, what to do, right? You have to extract the value of this matrix and So So So look, the matter of top row is different, we had look, the matter of top row is different, we had printed the toppers but it is a changing printed the toppers but it is a changing tractor, it will keep changing one of our columns tractor, it will keep changing one of our columns and we have put a loop in the column, so it and we have put a loop in the column, so it is okay, so basically I have come here to add it to the list, is okay, so basically I have come here to add it to the list, let's do this. let's do this. let's do this. add all the items in the list, we are sorting out each position but let's add the last one. After doing this Ajay, little did I know that this process was done, we had reduced the toppers to the bottom, so Had done mature had been increased Had done mature had been increased Had done mature had been increased so do that here two increase the toppers increase so do that here two increase the toppers increase plus plus two okay next time now plus plus two okay next time now what to do is to update direction one what to do is to update direction one and how is it going and how is it going that it is direction one so what is there in it that it is direction one so what is there in it from the top from the top from the top processing and right column just remember from where it is coming from. First write that if you are coming from top then okay then you are coming from bottom okay then border is coming from you. And what to do after that, copy it, there is no use of writing forward and if bottom is coming from not stop then the bottom is coming from our top and it is changing daily but if the right column Write the right column. Write the right column. Write the right column. Changes are happening with us every day. Here I have done it. Changes are happening with us every day. Here I have done it. Now what will happen in this right column? Now what will happen in this right column? After it has been processed, do it by reducing it. After it has been processed, do it by reducing it. This is simple. You just have to remember This is simple. You just have to remember what to reduce and what to increase. Then you go next. what to reduce and what to increase. Then you go next. Do nothing much, the Do nothing much, the same question will come, you will be same question will come, you will be asked to write the same code there too, so now you have to asked to write the same code there too, so now you have to process the bottom row, but this time we are moving process the bottom row, but this time we are moving from the right column to the from the right column to the left column, a little left column, a little reverse is happening. reverse is happening. reverse is happening. taken, we process them, let's run the reverse loop, so I was saying, where am I going, from the right column, I am going to the left towards Alam. People - Let's go by the way People - Let's go by the way People - Let's go by the way remember it's ok and ok pick this up and remember it's ok and ok pick this up and what we were doing in this so bottom row we were what we were doing in this so bottom row we were printing and our it's left we were printing and our it's left we were muting so bottom row write first muting so bottom row write first bottom row we were printing ok bottom row we were printing ok bottom row we were printing ok ours, I wrote it in 3, sorry, let's ignore that Kotha Karma direction to 35, we will do a stuff, neither were we taking the right sum, so now we have printed the voters, okay, But this is But this is But this is our direction going from right to left, our direction going from right to left, so it will automatically take the same height, so it will automatically take the same height, select the height and return, the matter is simple, select the height and return, the matter is simple, good bottom process is done, bring the bottom row good bottom process is done, bring the bottom row up here, bring it along with the top, then it means the up here, bring it along with the top, then it means the length of the bottom row. length of the bottom row. length of the bottom row. B minus minus two now let's pick up the last one, what's in the last one, this is the one on the left, is n't it, these are coming up from the bottom, coming towards the top and this left column electronic left column left column Lift it completely, coming from bottom to top and lift the left column completely, then go from bottom to top 12 in reverse, this term is coming from top - - 6 is ok, top is coming from the button, remove this, Two more, we were picking this left column, Two more, we were picking this left column, Two more, we were picking this left column, this is Alam Vijay Kolar, this is this is Alam Vijay Kolar, this is 18, Alam, write it like this, okay and 18, Alam, write it like this, okay and put it here, put it here, okay, it is simple, now in the left column okay, it is simple, now in the left column process, move the left ones forward. process, move the left ones forward. So expand the left column, the work is done, the So expand the left column, the work is done, the structure has been written, it will keep rotating, structure has been written, it will keep rotating, according to me, it is done, I would like to delete all this according to me, it is done, I would like to delete all this and after scanning once, I and after scanning once, I would like to see that something is being scanned, a mistake is being made, would like to see that something is being scanned, a mistake is being made, we have also done the return. we have also done the return. we have also done the return. these many chords separately, here we did not find any semi-problem, all these mistakes, you go, write how much and fat, let's see once more and this 20 so that you will have to write first, Rocky, check and Just set it if you are in matriculation then get the Just set it if you are in matriculation then get the Just set it if you are in matriculation then get the MP list printed there, MP list printed there, no need to do any work and submit it no need to do any work and submit it and see that successful submit is getting accepted and see that successful submit is getting accepted and you can see in the video. and you can see in the video. Subscribe Subscribe to my channel is 966. to my channel is 966. to my channel is 966. cover all the videos and see you | 2024-03-20 10:23:32 | 54 | Spiral Matrix (Leetcode 54) - Medium |
|
MpShbElK3Ls | preparation requested post question is the patient has pieces in which we have the texture that kidney will go and the listing will be as much as it will be that whatever elements it will have all of it, we have a quarter inch of it that happened in special we have a quarter inch of it that happened in special events events Out of that, let us complete that we had some porn and this is the next year, there is someone else in it, like we have to do, like in the middle of this, we have to do, like in the middle of this, she has become special, she has become special, then for that, Russia, like if then for that, Russia, like if on this, we have to pay the gardener on this, we have to pay the gardener and tax. and tax. and tax. we will be at a time because from that and this again so here we have that that only means if we can make changes in it make changes in it that we can depress it with a positive value, that we can depress it with a positive value, then here if then here if then here if is a clash, then Meghvar helps us on the points, if we time on WhatsApp, time on WhatsApp, now how can we increase the equivalent group, we have to give these two in the encounter, This year's This year's This year's spin ball is given, so if we see here, spin ball is given, so if we see here, here it is ABCD, CCTV is here it is ABCD, CCTV is C, request is being made like if we get a simple group, then this is get a simple group, then this is ours ours here. here. here. I robbed you then did I spinjiju special request, his account was Dr. So this can be a special tanning here that sometimes it happens that if we are watching this then at that time we think that let's say A group has been formed, now A group has been formed, now A group has been formed, now a group of this and that two has been formed and in the same way this group has been a group of this and that two has been formed and in the same way this group has been formed, then it will happen at that time that whatever group we then we demanded to decide at that time. then we demanded to decide at that time. If you look here at this If you look here at this and this, it means that some changes would have set an means that some changes would have set an alarm in the group, then at that time alarm in the group, then at that time ours which till now was only ₹ 2 and this was only this, then how much money is there in our things. how much money is there in our things. how much money is there in our things. and it must have been given in whatever will happen, so for that and it must have been given in whatever will happen, so for that I have given an example I have given an example like this, whatever work has to be done for it, like if we It will be It will be It will be that we are monkey size lion left, after that that we are monkey size lion left, after that boss, we have taken ABCD, so boss, we have taken ABCD, so we will change ABCD with the next Justin, we will change ABCD with the next Justin, then first of all we will do what is here and what is from the seat and then check that it is matching. here and join it with all this here, then at the same time Sambandh Ravana will keep checking this entire team and then keep seeing that if this value is being found then we will add it to the group. We are Edition Pyun in this group, We are Edition Pyun in this group, We are Edition Pyun in this group, so it should be so it should be our pimples to such and such groups, our pimples to such and such groups, but now what we will do here is that if but now what we will do here is that if this is what it is, then if we add more of it and whatever we more of it and whatever we do, it will become very big do, it will become very big and subscribe a lot. That if that question has not been asked in Hindi then I have put pistachios for this question, first of all you go there and practice this question, you try to do some project as per your own, what will happen from that that you can get 21 MPs and Let's solve the problem of how to Let's solve the problem of how to Let's solve the problem of how to invest, if you will be able to do that on Android, invest, if you will be able to do that on Android, then in this mind that as we know this group, we have to name it, what we have to do is to remind which value it is and we can do whatever it is. we can do whatever it is. we can do whatever it is. we have and take with it 138 This is a machine, after breaking it, we can see how it is becoming a Chinese group or not, whether it is the President or If you will be able to If you will be able to If you will be able to call then what will they set call then what will they set that suppose we that suppose we take that from the servicing that is ABCD is take that from the servicing that is ABCD is CDAB which is CDAB which is which one is doing this on behind the back appointments, which one is doing this on behind the back appointments, then we will So So So whatever and the goddess and the goddess that is here, the seal and that is here, the seal and that that from the media and Billu and this matter, if we make it a from the media and Billu and this matter, if we make it a fool fool that we have done this and now we, then she will go our our our all of them are the same, then in that condition, whatever will happen in the group, now we have someone here that if there is any rally and in that, we saw that if this video is coming, then we will not add Pumik at that time. That we will get this one, now if we use such Gram Quiz Patience Accepts Gram, then it will give us whatever unique rally we will purpose will have to be purpose will have to be fulfilled and whatever we do and we will If If If you are doing it then you can now make improvements in it like I just said, can we use America for whatever we want to do or can we use it If you If you If you take any particular Singh and send it to Vrindavan take any particular Singh and send it to Vrindavan after setting it up then after setting it up then you you can make any payment, I, your messenger and your can make any payment, I, your messenger and your people, if anyone can add. people, if anyone can add. people, if anyone can add. example, if you use it in this manner at this time, it will save your shopping time, then what will happen according to that, it is time for coating again and our ability will also reduce, so what can we You can't do anything else or you can You can't do anything else or you can You can't do anything else or you can add anything add anything like so like so here you can edit the video as per your requirement. If there is here you can edit the video as per your requirement. If there is any problem inside then we are going to any problem inside then we are going to go ahead and watch it right now, start it, go ahead and watch it right now, start it, still make a moment. still make a moment. your wish and do it in the assembly. So, this is the your wish and do it in the assembly. So, this is the answer to our question and in this we will make a meter answer to our question and in this we will make a meter and inside it we will be and inside it we will be given information string, so that we can match and select the given information string, so that we can match and select the group from it. group from it. group from it. can say set this so and and for that and what we just saw for that time Amit Singh will take more and now posts laugh whatever and posts laugh whatever and posts laugh whatever and tricks and other things in the industry and he has all the control, if we add it then it will be like we saw that and these these people were getting it, so Are using but Are using but Are using but to do this we have created to do this we have created our first our first and use that we have softened the whole hair and vote and here you will be our this will be as unique as those who subscribe to our channel. meet then here many times this happens where many defined s were already there at this time and if we have to do it at that time also then at that time the jhamajham will be now it is complete It may not be enough and will remain ours and it is what it is will remain ours and it is what it is but what I have implemented is but what I have implemented is in a slightly different way. Let's say that what in a slightly different way. Let's say that what we saw in the Pizza a Solution we saw in the Pizza a Solution was that we was that we worked in front of the team and its method. worked in front of the team and its method. worked in front of the team and its method. diabetes, then what will happen if we do person who was getting it done was solving it person who was getting it done was solving it and the one who was doing it for us and and the one who was doing it for us and not by adding it, then we have to subscribe to something. we have to subscribe to something. we have to subscribe to something. only only available, cannot be fulfilled while kissing. The available, cannot be fulfilled while kissing. The cigarette which has to be smoked has to be smoked. At that time, we will use the seat belt, join interior, it is real and make it for us. Instead of regarding that which has been arranged, the Whatever Whatever Whatever things we get and whatever unique things we had as if we who are our country, we will as if we who are our country, we will make it from the canteen and for them make it from the canteen and for them and for them, now we and for them, now we all the people who were all the people who were there in that too. there in that too. reason must have started by subscribing here in that, now as we add the started by subscribing here in that, now as we add the batter to the SIM which is there, anyway batter to the SIM which is there, anyway that chapter's that chapter's increment will be completed from these specific busy life and increment will be completed from these specific busy life and tent. tent. tent. and and now due to being an industry, with shampoo and this will be eliminated, do whatever and there is no need to do it, do whatever and there is no need to do it, Sudarshan, Sudarshan, Sudarshan, if you have any doubt for this question of ours, if you have any doubt for this question of ours, if you liked the video, then like, share with your friends and subscribe to the channel till then with this video. | 2024-03-22 17:44:46 | 893 | 893. Groups of Special-Equivalent Strings | String questions | Coding Interview Questions Series |
|
V0lJzGtiAB8 | Hello hello everybody welcome to my channel today is the day 28th june recording challenge MB today is the day 28th june recording challenge MB problem is per motivation cement members to problem is per motivation cement members to and contains all the total length factory and contains all the total length factory units per month in this listing and having all the per units per month in this listing and having all the per motivation in order to get motivation in order to get the following sequence for any the following sequence for any the following sequence for any lights 12313 2121 to 0217 In between hai front saath par motion song play n is between boys classes in k will be between 2 and cars for example 12323 Lo sorry for them on subscriptions 13152 Video * minister lift quiet * minister lift quiet * minister lift quiet n't Mind Will Get This Shows How Will Solve This Problem Let Me Explain New Fruit Force Approach Sudhir What We Have To Create All The Missions Example Foundation For Any One To Three Layer This And How Will Get Some Will Get This Hai Bhi start from one Bhi start from one Bhi start from one place to another and 120 elected to bat place to another and 120 elected to bat first in the school was elected to the first in the school was elected to the 0230 will give one to three is 10th left with two three 0230 will give one to three is 10th left with two three fatty acid selected soul will fatty acid selected soul will not be selected in the industry not be selected in the industry subscriber tree to avoid you to the Share And Subscribe Similarly Subscribe Like This Shrill 231 Shades One More Three To One Which Shrill 231 Shades One More Three To One Which Missing From This Initiative Which Lasts For This Missing From This Initiative Which Lasts For This Way Also Get All The Formation One Switch Way Also Get All The Formation One Switch The City Of The Initial String The City Of The Initial String Started Between Subscribe The Channel And Started Between Subscribe The Channel And Subscribe The Amazing The Answer Subscribe The Amazing The Answer Subscribe The Amazing The Answer Ki Dot Net Ki Dot Net Aaj Cake Minus One K - Services Morning Later Aaj Cake Minus One K - Services Morning Later Till 19 Minutes Let Me Convenor He The Code Of This Which Is Written Earlier Vikas To Make Short Video I Am Not Fighting Record Short Video I Am Not Fighting Record For This Add Fruit Solutions For Writing This For This Add Fruit Solutions For Writing This Code You Code You Code You problems and not with use this way saw her first created during British numbers from one to one day the result will hold to the number one right this is my channel subscribe And subscribe The Amazing to the result of After the For All Next From Zero to the Standard Size Water Sources of Power Sparing Saudi School Will Be Called in the Village Difficult Character Subscribe and Removed from the subscribe and Share Thank you members Will Work for India But If You See Submit Difficult Submit Difficult Submit Difficult 10th Time 200 Setting Too Much Time Definitely Will Be Time After Being Unfurled The System Limited Vikas Wise Kushwaha Recording David Designs for the Time Complexity of Dissolution Wave Fin 210 One How They Can Optimize Solution 100 210 One How They Can Optimize Solution 100 Such Such Such One Two Three One To Generate December 2016 Subscribe Possible For Motivation Subscribe Possible And Subscribe In The Total Population Will Guide You - 1929 Subscribe 312 Subscribe To Like Baby Can Get No S Person So What We Can We Will Computer's Wherever We Will Computer's Wherever We Will Computer's Wherever We Draw Select From We Shape's Hair We Draw Select From We Shape's Hair 9 4 So Effin's End Which Episode 21f First 9 4 So Effin's End Which Episode 21f First Place And Can Get Maximum Possible For Place And Can Get Maximum Possible For Motivation Subah Means The Best Option For The Motivation Subah Means The Best Option For The Place Will Not Be Able To What We Can Do This And Place Will Not Be Able To What We Can Do This And From From From that and in this will look photo again the two separate from here.the K F103 subscribe The Channel and subscribe the Channel Please subscribe this Hair 216 How Can Calculate Soft Bhi Anjaan Reddy Factorial of All the Number 24 2010 Will Not subscribe this subscribe this subscribe this Video plz simply divide the number with Video plz simply divide the number with that number and - the current index I show the that number and - the current index I show the number of middle number one seems rather than 4000 start with 1212 reply two the software I will start with avv will get rid from k divide factorial of which Subscribe 238 Subscribe Similarly One Remove From The Ko Remove B N X The two Swadesh Civil Remove B N X The two Swadesh Civil Drink After Removing This World Channel Drink After Removing This World Channel Subscribe Now To Receive New Updates Reviews Subscribe Now To Receive New Updates Reviews Subscribe 04 - Special Guest Subscribe 04 - Special Guest Lutti Apne Lutti Apne Pati Voice To This Previous D Pati Voice To This Previous D Ki ho fifth edition shop no this one will v5 Ki ho fifth edition shop no this one will v5 actually so this point you calculations for five se actually so this point you calculations for five se zbar weir graphical 251 from which comes zbar weir graphical 251 from which comes for this calculation in terms of hair for this calculation in terms of hair and cases with festival will always have a and cases with festival will always have a part of three - Vikram for tube well 2031 That Similarly They Will Continue Till And Will Give Them One Dose Motivation For Meditation In This Is Very That Easy Problem But Getting This Idea This Little Tricky Vansh You Have Some Idea Only When You Look So Let's Start Between Optimal Solution Implementation Remedy Share This Code Show What We Do First Will Create Factorial Are Thing New In Top Ten Plus Vwe Elimination Of Vwe Calculate The Real Me2 Vwe Plus I Slept And Fact Of Life Is Equal To Singh Tweet Stream This Singh Tweet Stream This A stream interesting and arrange arrange A stream interesting and arrange arrange from one to and plus one vikas will be one from one to and plus one vikas will be one race in the sense one to two two to two to do subscribe list subscribe channel thank you will need to which will result in [music] in to-do list That Builder Jai Hind Sir Chashmish Ayur Vigyan Distic 9 Bhi Reduce's Scholar And Will Not Follow For Marriage Youth 2n Plus 910 Video Subscribe Divide Divide Factorial Of From List Will Not Remove - What Is The From List Will Not Remove - What Is The In The Story Of In The Story Of In The Story Of 's member will be updated with that one should be given service just a string of this train will have spring is you string of speed2 spring member simple implementation and tried to compile amarkot 123 compiled and expected answer so let's get the accepts so accepts so accepts so complexity of dissolution Sudesh Bhosle and where running the factorial in Dishaon Software's dinner minister but her desires will also be running but if you remember that up and enlisted in law and is contest while removing from the take Open Which Will Take Open Which Will Take Open Which Will Take Off Time And Also Running On Off Time And Also Running On Open 10th Time Complexity Of Functioning Open 10th Time Complexity Of Functioning Of Which Of Which We Square Safe And E Couthing We Square Safe And E Couthing Space Complexity Wishes For Pyun Otherwise Space Complexity Wishes For Pyun Otherwise Subscribe Please Subscribe My Subscribe Please Subscribe My Channel For My Upcoming Videos Channel For My Upcoming Videos Thank You For Watching | 2024-03-20 10:47:19 | 60 | permutation sequence | permutation sequence leetcode | leetcode 60 | medium |
|
Jup8-Q3JEow | hi everyone so today we're going to solve lead code daily challenge problem solve lead code daily challenge problem number number 1071 greatest common division of 1071 greatest common division of strength strength so uh it's a very simple problem uh it so uh it's a very simple problem uh it is marked as easy as well so what we is marked as easy as well so what we have to do is we have to find out the have to do is we have to find out the gcd of two strength and they have given gcd of two strength and they have given a definition of gcd in strings as well a definition of gcd in strings as well uh which basically means the largest uh which basically means the largest string which can produce both string 1 string which can produce both string 1 and string two uh if concatenated and string two uh if concatenated repeatedly okay so basically we'll have repeatedly okay so basically we'll have to find out the same we have to find out to find out the same we have to find out the minimum or the yeah I think the the minimum or the yeah I think the minimum string which can form minimum string which can form the both these uh which can form both the both these uh which can form both these uh strains after repeated these uh strains after repeated concatenation concatenation so it's going to be a really simple one so it's going to be a really simple one to solve um it doesn't need any you know to solve um it doesn't need any you know any as such explanation uh to solve this any as such explanation uh to solve this question so let's let's move right to question so let's let's move right to good solution and what we're going to do good solution and what we're going to do is post things first I'll check if is post things first I'll check if my string one and string two are same if my string one and string two are same if yes then I can return any of these yes then I can return any of these okay okay next condition is I want to check if next condition is I want to check if there is any uh gcd possible or not so there is any uh gcd possible or not so to do that I am I'm checking if I add to do that I am I'm checking if I add a string 1 and string two and do this a string 1 and string two and do this thing in the other order thing in the other order if both both these strings the strings if both both these strings the strings are same then we can say okay uh are same then we can say okay uh P can have a GCB if not P can have a GCB if not if not if not I made this error if not then we will I made this error if not then we will return empty string as our gcd because return empty string as our gcd because then we cannot have a gcd for example then we cannot have a gcd for example if string 1 was if string 1 was lead lead and string two was and string two was code in this case our gcd will be an code in this case our gcd will be an empty string right empty string right plugins so next comes the condition plugins so next comes the condition where I want to just find out the where I want to just find out the maximum length we can have for our uh maximum length we can have for our uh for a gcd or these two string so I'll be for a gcd or these two string so I'll be using the default uh method provided by using the default uh method provided by python to do that so next length is python to do that so next length is equals to PCD of equals to PCD of length of string one length of string one and length of and length of spring 2 so using uh this approach we spring 2 so using uh this approach we will get the index will get the index uh in any of this like you can either uh in any of this like you can either use string one or string two for the use string one or string two for the return purpose return purpose and this back slant will basically and this back slant will basically represent the index uh index till which represent the index uh index till which are gcdas for example a b so we'll get are gcdas for example a b so we'll get one as the max length or uh one as the max length or uh let's say ABC and so on so now what we let's say ABC and so on so now what we have to do is we have to just return the values from string one till our next let's submit the test let's check out let's submit the test let's check out the test cases um the test cases got here let's submit and yeah the solution that accepted and and yeah the solution that accepted and we performed decent like we outperformed we performed decent like we outperformed 79.41 of the submitted Solutions uh last 79.41 of the submitted Solutions uh last time I submitted the same it was around time I submitted the same it was around 95.70 percent 95.70 percent so yeah thanks again guys for watching so yeah thanks again guys for watching on the video and stay tuned for the on the video and stay tuned for the upcoming ones don't forget to subscribe upcoming ones don't forget to subscribe to this channel thank you | 2024-03-25 16:44:31 | 1,071 | Greatest Common Divisor of Strings - Leetcode 1071 | Google Interview Question 🔍 |
|
49OfnqGldko | [Music] and hello so today we are going to do and hello so today we are going to do this problem called this problem called flatten nested list iterator so what we have with this problem is a nested list of integers and each element is either an integer or a list okay um and the user list also can be listed so you can have something like this and then another list inside it and maybe an element here and then some another list and the goal is to implement a nested iterator that has next and hazmat next function this one returns the next integer in the error so let's say we have maybe uh one uh two here uh first we'll return one and then we'll return two and then we'll know whatever is next has next just returns if there is um uh still elements left or not if we are at the end of the hour list or not and the code that will call our function is um result here and while there is a next so call has next we get the next element and then we add it to the list one thing to note here is that before every call to next we do call has next that risk guaranteed by the problem that will help us later in the implementation um yeah so let's take a look at one of the examples they have here um so we have uh this list um for the first one nested list is the first element of the nested list so one and then after that this one and then this one and then this one so you can see it respecting um this is also another interesting example so first this element and then the one in the nested list and then one in the depth three here which is six um so that's the problem um now let's see how we can solve it um so the simplest solution is to just um rub the list the nested let's flatten it in the constructor and then have an index that marks the um the position where we are at for next and each time just get that position and increment it that's the simplest solution although it's not ideal because then we are not implementing a real iterator um so definitely not the recommended one but it's a good place to start okay so let's just see that one and then go from there to the to a real iterator solution um so for that solution we can have um in our init function okay we are going to create an array of that represents the list completely flattened okay so to flatten the list we'll go through the element of the list and for each of them flatten it and then just add the elements in values okay so how do we flatten it um if the element is an integer then we don't need to do anything we just add it to the list but if it's a list then we get all the elements in it and recursively call helper so that if it's an integer we just return it but if it's another list then we iterate again so very simple and then we have the uh a pointer that starts at zero um and for next we get the element increment the pointer and return it and for hazmat we just check if we reach at the end of the completely flattened list um so this one is very simple um however it's not ideal because we already constructed the list we we want to implement a real iterator so let's see how to do that next um one thing to note though is instead of an index here you could use um a stack of the elements and then reverse them and then you can pop each time or you could use a queue and then each time pop from the queue instead of maintaining um an index so that's also a possibility um okay so let's see the um okay so let's see how we can do a um okay so let's see how we can do a solution with an iterative with an solution with an iterative with an iterator here so the idea of this is iterator here so the idea of this is what we want basically from this what we want basically from this solution is first return one then return solution is first return one then return two they return three then four then two they return three then four then five so regardless of the nesting we five so regardless of the nesting we want to return the elements the first want to return the elements the first element right element right so what we can do is just have so what we can do is just have a stack that contains the element a stack that contains the element and each time what we want is the and each time what we want is the environment that we want is at the top environment that we want is at the top of the stack um that's the elements we of the stack um that's the elements we want that's the next element so this is want that's the next element so this is the invariant we are looking for the invariant we are looking for so to do this what we can do is so to do this what we can do is basically add to a stack basically add to a stack this list to reverse it so that one is this list to reverse it so that one is at the top right and so if we do that at the top right and so if we do that what that will mean is this here is the what that will mean is this here is the first in the list this this list here first in the list this this list here right right this is the first element this is the first element um then after that we'll have four then um then after that we'll have four then after that two three after that two three then one so what this allows us to do is then one so what this allows us to do is in next we can just the next function call we can just do this is our stack you can just just do stack pop and return that okay but for our mix function so we okay but for our mix function so we would remove one and we'll return it and would remove one and we'll return it and that's what we expect but for our has that's what we expect but for our has next function remember in the problem next function remember in the problem statement it says before every next we statement it says before every next we call has next so what this would mean is call has next so what this would mean is in has next we need to unwrap this right in has next we need to unwrap this right we need to transform this to be two we need to transform this to be two what's the first element that we should what's the first element that we should have to be 2 3 4 and then this will stay have to be 2 3 4 and then this will stay the same until we get to it so we need the same until we get to it so we need to unwrap each to unwrap each each nested list in has next so that each nested list in has next so that it's in this order it's in this order right the order where when we pop we get right the order where when we pop we get the first element so that's what our has the first element so that's what our has next function will need to do next function will need to do so how can we do that basically uh so we so how can we do that basically uh so we need to just pop need to just pop we need to just check the top of the of we need to just check the top of the of the stack and if it's a notation we the stack and if it's a notation we don't need to do anything like here in don't need to do anything like here in the case of four but if it's a list the case of four but if it's a list we need to do the same thing we did at we need to do the same thing we did at the start which is um add to the stack the start which is um add to the stack basically pop the list itself and add it basically pop the list itself and add it to the stack in reverse order so that to the stack in reverse order so that the first element is at the top in python we can do it like this okay so what our has next function will do is just keeps iterating until it finds an integer because what we want is top of the stack next element and an integer this is what we want and so has next we'll prepare for next to do that and so what we will do here is while we what do we want to do um so we want to get the top element right and if the tab is integer then we can just return it we can just return that we have an element right so we can return true but if the top is not an integer right like in this case it's a list what we want is to pop this and instead enter two and three in our stack right so we can just take the list to reverse it and then add it to the stack and so to do that we have the top that we want to um to add and so we can just take the stack pop the elements out of it and then add it again but reverse it at the top which is two so that would be just uh taking the top so that would be just uh taking the top in reverse it order which is top in reverse it order which is top minus one minus one um um you get the idea so minus one here okay uh one thing here we don't we shouldn't do append we should do extend because we are adding a list in python okay um so this is the the idea but if we end the stack and we didn't find any integer although we kept uh popping let's say for example in a case where we have a stack like this where there is an empty list and an empty list right this can happen with something like this then we won't find them into here then the step would become empty after traversing these two and so we need to return false at the okay okay um um so this is the the simplest idea here at so this is the the simplest idea here at the start we'll need to call tab get the start we'll need to call tab get list together the elements right list together the elements right now you may ask what about the case for now you may ask what about the case for five and six five and six here right here right so what will happen is that what we'll so what will happen is that what we'll add to the stack for this is five first add to the stack for this is five first and then the list six and then the list six um and then the list six and so in the next iteration we will get the elements of the list and then we will add them as just six okay so this will work each time right um yeah so that's the the main idea is to each each time we unwrap the list that we are at and we add it in reverse order to to the stack so that the first element is at the top so that we can pop it in the next function and the invariant we are respecting is that the top of the stack is always a single integer um and it's the next element okay so let's cut this up and make sure it passes test cases um okay so let's put this solution up so the first thing we need to do is to have our initialize our stack and we need to initialize it as we said to the reverse of this nested list so that the first element is at the top uh the second thing we want to do is make our next function just return the top element because we make sure that that top element is um the is the integer um and it's the next integer and this is possible because um in the problem statement we are guaranteed that has next is called before next um and now in our function here we want to iterate while there is a stack one there is a stack we want to um okay so while there is a stack we want to get the top um we want to get the top uh element and then after that we want to check if if it's an integer we want to return if it's an integer we want to return true of course because then we found an true of course because then we found an element element um otherwise um otherwise the top is a list so we want to pop it the top is a list so we want to pop it and then and then enter the element in a reverse order enter the element in a reverse order and so and so to enter them we extend the stack to enter them we extend the stack with the list in with the list in the top right so this will the top right so this will instead of having two 3 in the top we'll instead of having two 3 in the top we'll add add 3 and then 2 after it in the top of the 3 and then 2 after it in the top of the stack stack and then if we weren't able to find any and then if we weren't able to find any integer integer in the stack then we return false in the stack then we return false so let's run this okay um okay so it looks like there is um okay so it looks like there is something out of order this is because something out of order this is because we did not reverse here we need to we did not reverse here we need to reverse so that two for example for this reverse so that two for example for this list we want two to be at the top so if list we want two to be at the top so if we just extend with two three then three we just extend with two three then three will be at the top we want will be at the top we want to do the reverse to add three and then to do the reverse to add three and then two so that two is at the top so that's two so that two is at the top so that's why we need um to reverse the list and this process passes test cases um and this process passes test cases um now with this solution next is of one now with this solution next is of one because we are only doing one pop because we are only doing one pop um and has next is open because we do as um and has next is open because we do as many elements in this stack as the there many elements in this stack as the there are so with the number of elements in are so with the number of elements in the nested list the nested list um okay so this is the one one way to um okay so this is the one one way to solve it another different way to solve solve it another different way to solve it but still in an iterator way is it but still in an iterator way is um to maintain track of the now reverse um to maintain track of the now reverse by just maintaining where we are by just maintaining where we are the position where we are in the the position where we are in the while iterating in a stack so while iterating in a stack so let's see what that will look like let's see what that will look like um okay so in this solution the idea is um okay so in this solution the idea is to maintain to maintain um um is to maintain in this cat is to maintain in this cat um the position so let's say our stack um the position so let's say our stack here um so what we want to do is maintain the list in the position so let's say let's actually make our stack bigger here to understand our solution so in the stack each element will be will have nested the nested list and then the index where that we are traversing so what this would mean is first i would be here and we will put the entire list and the value zero right because i is zero here in the next um iteration i would be here so this is what the list in this stack right so the current list we are looking at that's what would be at the top of the stack so what i mean by that is that um let's copy this here because the first thing we will do is add the list in the stack the entire list right with the position where we are at which is zero okay and so what happened so that so that's what we start with from the initialization now what do we do for next what should we do in the next iteration so what we need to do is get the top of the stack right so that and then return that element and then return that element right if it's an integer we print that right if it's an integer we print that element what we need to do is advance element what we need to do is advance the index right we are here first as the index right we are here first as zero we need to advance the index to one zero we need to advance the index to one so that the next iteration we go to the so that the next iteration we go to the next element next element so so to to do this what we need to do is get to to do this what we need to do is get the top of the stack so to do that we the top of the stack so to do that we just get our nested list just get our nested list in the position in the position and that would be the top of our stack and that would be the top of our stack which is in python just minus one which which is in python just minus one which is the is the element at position n minus one element at position n minus one and then we want so we want to return and then we want so we want to return what's the value the value is the nested what's the value the value is the nested list list at position i right so first it will be at position i right so first it will be position zero position zero will get one and then we will get we will get one and then we will get we need to get the integer because next need to get the integer because next we'll need to always return an integer we'll need to always return an integer so what this would mean is our has necks so what this would mean is our has necks need to maintain that the top need to maintain that the top at the top at the top the element is always an integer the element is always an integer and so here once we return that element and so here once we return that element so this is i actually so this is i actually we need to increment we need to increment this here so what we do is we take the this here so what we do is we take the stack the top of the stack so we say stack the top of the stack so we say stack stack at last position that's the top what we at last position that's the top what we want is to modify this which is at want is to modify this which is at position one position one we want to increment it we want to increment it okay so this is what um okay so this is what um what next does what next does now now we need our hands next to always we need our hands next to always maintain that the maintain that the the element at position i is an integer the element at position i is an integer so how can we implement our has next to so how can we implement our has next to do that do that okay let's explore that so has next um so what what our has next function can do is check the top of the stack again but since we may for example have something like this to enlisted less we need to keep going until we find an integer because we need has next to maintain that the top of the stack at position i is always an integer right so what we do here is we do um um we get the top of the stack we get the top of the stack right position minus one that's the top right position minus one that's the top of the stack and so we will get uh an of the stack and so we will get uh an element we don't know if that element is element we don't know if that element is a list or an integer yet a list or an integer yet but what we want each is to check so but what we want each is to check so let's say we are at we have two three let's say we are at we have two three right and i is at right and i is at we incremented i in next and it's equal we incremented i in next and it's equal to two right to two right that means this list is done right and that means this list is done right and we need to go to the next list so let's we need to go to the next list so let's say we have maybe three say we have maybe three four here five we need to go to this four here five we need to go to this next list so that's why here we check next list so that's why here we check if i is equal to the length of the if i is equal to the length of the element then we want to go to the next list in in what was previously in the stack right so what this would mean is basically we need to pop this out of the stack so let's say we um we added 2 3 to the stack right and then our i is now here so it's bigger than the length of 2 3 that means we need to pop this we need to pop this 2 here and of course add 4 or at the entire list but have i at this or at the entire list but have i at this position right and so what we need to do position right and so what we need to do here is if if this is equal to the length we need to pop the top of the stack because that means that the element is done we finished it reversing that element here okay now otherwise so otherwise we have two cases either so otherwise we have two cases either the top is just an integer four for the top is just an integer four for example and we can just return it example and we can just return it or the top is a list and then we need to expand that list right um so we check um so we check if the element at position i right let's say i for example is here at position 2 we need to check if it is we know that we have an x if it is we know that we have an x element we can just return true and next one just get that we'll just otherwise it's a list right so we'll otherwise it's a list right so we'll need to do is make the top of the stack need to do is make the top of the stack be that list so otherwise it's a list be that list so otherwise it's a list let's say for example for this 5 6 let's say for example for this 5 6 that means we need to open this list and that means we need to open this list and put i at 5 so that next year returns it put i at 5 so that next year returns it and so what we need to do here is append the new list right which is the new list right which is element at position i element at position i we get the list and stop at position zero but before doing that right because we say here we are at this position i and maybe there was an element here once we appended this list we needed the r for the entire list to be incremented as well right and so what this would mean is here we need our stack before adding the element we need to the top of our stack to be implemented for the next time when we pop this list once it's done you want to go to the next element in the rest of the list if that makes sense okay so this is the the main idea maintain the the list we are looking at in the index and then for next get that element at that index and then for has next each time we check if at the end of that sub list go to the next list or the next element in the in the top level list um essentially so yeah this is pretty much it now let's screw it up and make sure it passes our test cases um okay so let's write this solution here so first we need um to have um our stack right so we need to define our stack here which let's say it's equal it starts out with just as we said the nested list at position zero and for next we need to just proper the list from the stack so we need to get the top of the stack incremented and what we need to return is the and what we need to return is the element right element right where we are pointing at at the top where we are pointing at at the top because the top is what the element that because the top is what the element that we need to return next we need to return next and we need to get the integer and we need to get the integer okay okay with hands next we guarantee that this with hands next we guarantee that this will give us an integer so we don't need will give us an integer so we don't need to check to check now for has next what we need to do is now for has next what we need to do is well we have a stack well we have a stack and if we exit and we didn't find an and if we exit and we didn't find an integer then we can return false here we need to check either the list we are looking at ended either the list we are looking at ended and so that means it's equal to the and so that means it's equal to the length length then we pop that list then we pop that list and and the the next thing we traverse would be the the next thing we traverse would be whatever is at the top of the stack whatever is at the top of the stack after after this right and then here otherwise we will check if the element we are looking at is an then we are done you know there is an then we are done you know there is an element so would it be true element so would it be true otherwise we know it's a list otherwise we know it's a list and so we need to do is definitely and so we need to do is definitely append append that list which is basically um just that list which is basically um just elementary list elementary list but we need to specify what is the but we need to specify what is the position which is zero here the start position which is zero here the start position position but we shouldn't also forget to but we shouldn't also forget to increment increment the previous step right the previous step right because um because um but once this one is done we want to go but once this one is done we want to go to the next one if we don't increment we to the next one if we don't increment we will get to the same list and traverse will get to the same list and traverse it again right it again right and so that's pretty much it so let's and so that's pretty much it so let's run this um okay it looks like there is a small issue here um so we pop we check if it's an integer which isn't yeah this is element at position i yeah this is element at position i that's what we that's what we that's what we determined is a list that's what we determined is a list because that's not an integer so it's a because that's not an integer so it's a list okay let's check if it passes test cases and it does um in terms of time complexity here um here we are only doing all one operations so this one is of one here we do at most the number of elements in the stack so it's open um yeah so that's pretty much it for this problem thanks for watching please subscribe and subscribe and see you on | 2024-03-24 10:56:02 | 341 | Leetcode 341: Flatten Nested List Iterator |
|
napcuuYYUYc | Hua Tha Hello Hello Viewers Welcome Back to My Channel Hello Hello Viewers Welcome Back to My Channel Hope You Are Doing Red Brahmin Subscribe Hope You Are Doing Red Brahmin Subscribe My Channel This Please Do Subscribe My My Channel This Please Do Subscribe My Favorite Several Places for Various Categories Such Favorite Several Places for Various Categories Such Problems Iss Defiant Problems Iss Defiant Programming subscribe this Video Please subscribe and subscribe the inform 2all in in in j&k are defined in the fire key j&k are defined in the fire key 111 sexual phase - one b is equal to 111 sexual phase - one b is equal to airtel 156 alarm key not the symbol of airtel 156 alarm key not the symbol of return subscribe this boy dividing return subscribe this boy dividing darkness * and this entry r&b are still there jhal triplet suresh basically jhal triplet suresh basically jhal triplet suresh basically Thing They Do You All The Number Subscribe Our All Elements And Just Completed For Subscribe 12000 12023 40 Subscribe Subscribe 12000 12023 40 Subscribe Sudhir And Sudhir And Ex And Boy And Results Rate 100 Ex And Boy And Results Rate 100 Effective Thursday To Ki And Mexico 2012 Warning Results Active & Active & Active & Tonight 10 2014 Truth Table 0share 0 Tonight 10 2014 Truth Table 0share 0 0share 0 0share Different OK Sona List 0share 0 0share Different OK Sona List Work Through 1000 2000 To To To To To To Gomez - 101 Element 2012 Thursday For Thursday Thursday Thursday Subscribe Now To The Primitive White And Primitive White And Primitive White And Flow Of Often Needs Just One But Dozens We Flow Of Often Needs Just One But Dozens We Importing Ajmer Road Developed B We Want Importing Ajmer Road Developed B We Want To He Google Lens For The To Front Thursday Hello How Many District Let's Be A Hello How Many District Let's Be A Giver Slogan Is The Question Solved Giver Slogan Is The Question Solved Giver Slogan Is The Question Solved The Amazing Exactly What We Call The X Factor Is Nothing But A Call The X Factor Is Nothing But A That In Our Enemy So Android Often That In Our Enemy So Android Often Similar Similar Similar slip services sister name but rather be attend a 200 na velvet rathwa timli the eksar par element sense off kar ki ve gotra udhar restaurant sperm group 2014 Ko Hand While Soaking Uday Trade Will Update Counter Reform Committee Secretary And Protest Actually Hot Movie And Counter Soil 102 Subscribe My He Will Go Through This Subscribe My He Will Go Through This That The Second Part Starting With A That The Second Part Starting With A Refuge And Quick 2020 - 02 End Refuge And Quick 2020 - 02 End Refuge And Quick 2020 - 02 End Three And You Only I One lights S2 Kshatriya And Will Go Back To Our Banner Representation And Work For 800th Ursa And So Will 61st Ursa Subscribe And Subscribe The Video Subscribe And Subscribe The Video then subscribe then subscribe That I will be properly uploaded video very soon That I will be properly uploaded video very soon with better implementation so let's go with better implementation so let's go for entry into Quattro the world for entry into Quattro the world article named Lal Yadav 2018 Sudhir and Obscene to the article named Lal Yadav 2018 Sudhir and Obscene to the number 0001 but not required to the that I am going through 102 and that of first that I am going through 102 and that of first follow-up And Minerals In Electronics follow-up And Minerals In Electronics And To Negative One Should Start With My And To Negative One Should Start With My Electronics On Negative One Should Know I'll Electronics On Negative One Should Know I'll Start From CO2 And Subscribe - Start From CO2 And Subscribe - 110 Adhir They Do The Meaning Of The Record Subscribe And Subscribe 202 Duplex And Heard ODI counter and put ODI counter and put ODI counter and put in their hearts of but still in their hearts of but still continued it's not divided between multiple continued it's not divided between multiple operations of any possible wound taking feedback operations of any possible wound taking feedback red 202 280 12802 to the self closed scene red 202 280 12802 to the self closed scene fluid set fluid set that triplets diet included deposited that triplets diet included deposited solid you want him to go back end solid you want him to go back end solid you want him to go back end Will Improve That Time Complexity While Doing Right Subscribe subscribe and subscribe the Channel and subscribe the Channel Question Express The Current In Next 100 Withdraw Into Doing Right Subscribe subscribe and subscribe the Channel and subscribe the Channel Question Express The Current In Next 100 Withdraw Into Soft Pitch Attraction In This Soft Pitch Attraction In This World Who Were Going To Reach In World Who Were Going To Reach In Electronics Finally Bigg Boss 100 Electronics Finally Bigg Boss 100 Basically This Channel Subscribe Must Basically This Channel Subscribe Must Basically This Channel Subscribe Must soon subscribe The Channel from Sydney with love hua tha from what ever with XX plus one to end rights issues laker swift reader highest number and further from here from reader highest number and further from here from number plus one to end various number plus one to end various platforms basically show words we platforms basically show words we platforms basically show words we from going to land rates will all The Mother After And Give The Total Time The Mother After And Give The Total Time Complexity 542 President My Channel Thank Complexity 542 President My Channel Thank You Are You All Don't Forget To Subscribe And Subscribe To 210 Complexities Content Saluk Ramesh Account Space And Deaf And Cube Algorithm Questions Please Leave Your Comment On Your Read in the Read in the Read in the description and subscribe the Channel description and subscribe the Channel Please subscribe and Share with your Please subscribe and Share with your friends Please Click on the Bell Icon You will be friends Please Click on the Bell Icon You will be notified about my videos Video notified about my videos Video Problem Limitations for improvement in Problem Limitations for improvement in time complexity Subscribe button The middle time complexity Subscribe button The middle problem problem that they have to improve time complexity is in the description that they have to improve time complexity is in the description Security ok thank you Security ok thank you for watching me with another problem very much | 2024-03-21 02:35:17 | 1,442 | Count Triplets That Can Form Two Arrays of Equal XOR(Leetcode 1442) |
|
V9ALFHFL5oQ | welcome ladies and gentlemen boys and girls today we are going to school's girls today we are going to school's problem which is minimum depth of binary problem which is minimum depth of binary so basically this is the binary problem so basically this is the binary problem and it's quite simple as well so what and it's quite simple as well so what the question is saying let's just see the question is saying let's just see the question saying like like i i hope the question saying like like i i hope like from the title only you understand like from the title only you understand what the question is saying but anyways what the question is saying but anyways let's just see the question first given let's just see the question first given a binary find its minimum depth okay the a binary find its minimum depth okay the minimum depth is the number of nodes minimum depth is the number of nodes along the shortest path from the root to along the shortest path from the root to the nearest leaf okay so what is saying the nearest leaf okay so what is saying like the minimum that how we have to like the minimum that how we have to find is from the root to the minimum find is from the root to the minimum leaf okay guys like this one uh let me leaf okay guys like this one uh let me just make this pointer size bigger just make this pointer size bigger little bit little bit okay so from over here to over here like okay so from over here to over here like this we have to find okay okay it is this we have to find okay okay it is different so now the question is like uh different so now the question is like uh okay what approach can we use over here okay what approach can we use over here are we gonna solve this using bfs so it are we gonna solve this using bfs so it will be quite simple to do with that will be quite simple to do with that okay so ladies and gentlemen i hope so okay so ladies and gentlemen i hope so the question is clear and the question is clear and let's see like how we're gonna solve it let's see like how we're gonna solve it and how we're gonna call it i mean okay and how we're gonna call it i mean okay so ladies and gentlemen let's just start so ladies and gentlemen let's just start solving this problem so solving this problem so uh okay so first of all what i will do i uh okay so first of all what i will do i will just give uh two base conditions my will just give uh two base conditions my first base condition will say if my root first base condition will say if my root is null if my root is low then what i is null if my root is low then what i would do i will simply return 0 over would do i will simply return 0 over here y zero because as they have given here y zero because as they have given the int so that's right here we i can't the int so that's right here we i can't think of written force over here okay think of written force over here okay anyways the second condition the base anyways the second condition the base condition is if my root condition is if my root of left is the and my root of light is built as well so that is a gentleman now what is saying like we just got the root only okay so it doesn't have any leaf node so it just has a root only so for that one obviously simply written one over here because you know the only one known as present so what else i have to do nothing okay gentlemen now here the things come now one condition come over here the condition will say let's say like we don't have the uh left left leaf okay we don't have any left path we just have the right path okay so for that what i will do i will just simply say okay if my root dot left is null if my root left is null then do one thing then go for the right one return is minimum depth from this root dot right okay like this and don't forget to add one in this one why plus one because you know we have to uh have this root root value as well so let us say like if we are if we are over here let's just say we are over here and we come over here and then let's say we just go over here again straight forward so this is one and this is two but we have to put this one as well so that's why we are doing plus one because it's already have two no plus one for this one so that it can get three okay gentlemen that's what i'm saying but there's the minimum i'm talking about the minimum one there's the maximum so in this one you know the case is like we don't have the left for right now that's what i'm talking about now similarly i will talk about let's say like we don't have right as well so following in general i also know like you're just like what the chord will be right over here if you don't have the right one if our right is null then i will simply return i will say let's go and find for the left one two dot left and plus one ladies and gentlemen so that's how we are uh solving our problem and finally i have to return back document of minimum of left corner right so what i have to do i will say minimum off uh i have to call the function for this one mainly depth and already enjoyment like i i have to add organization i hope so you forward this thing but we have to add plus one over here as well and ladies and gentlemen that's all our kodi so i hope to the code is if you still you don't understand like what we are doing let me just first of all run it to see any compilation error we are facing over here then i will uh work it through the quota back again okay so ladies and gentlemen these two our base condition this to our base condition okay and in this one like okay let me explain about the base connection the person is like if we if we just get empty empty room therefore that we will simulate zero because there is no no no reason let's say we have some known one over here for that one i just say like okay go for this one so like uh it doesn't have any left it doesn't have any right then just simply uh written the one then we simply did another one now let us see like we don't have the left one in this one we don't have left and left one we'll go for the right one and return the minimum one between the minimum one but let's say uh we don't have right we don't have right we have the only left so the i will simply go for the left and return left plus one that's all ladies and gentlemen we are doing okay uh lastly what i have to do i will simply say okay if we have these two things if we have left and right then do one thing then go for is the minimum one or either on the left either on the right and return it over like in this condition the minimum is this one so we got one over here and i have to add plus one as well because you know the root we have to count the root as well so one plus one will be two so i have to write it two in the final output as you can see in this test case so ladies and gentlemen i hope so this code is clearly like what we are doing over here so ladies and gentlemen let me just submit it and i will uh talk about its time complexity and the space complexity in this one and here we go it is accepting very well so what the time complexity in this one we are doing the time complexity is big off and because for the worst case okay ladies and gentlemen and the space complexity in this one we are dealing with this big of one for the better case but for the worst case it could be big of n minus one okay ladies and gentlemen so let me just put it together for the better one and this is for the first one i hope so ladies and gentlemen this thing is clearly like what i'm doing over here so thank you ladies and gentlemen and if you still have any doubt uh in this problem then just do let me know in the comment section i will definitely want to reach to you and thank you thank you very much ladies and gentlemen for watching this video i will see you the next one till then take care bye bye and i love you guys believe me i | 2024-03-21 10:40:17 | 111 | Minimum Depth of Binary Tree | LEETCODE - 111 | Easy solution |
|
FRWUcc1cX9A | hey hey everybody this is larry this is day eight of the leeco daily day eight of the leeco daily february challenge hit the like button february challenge hit the like button hit the subscribe and join me on this hit the subscribe and join me on this card let me know what you think about card let me know what you think about today's farm which is add digits i am today's farm which is add digits i am still in the city of still in the city of hopefully i'm seeing that a little bit hopefully i'm seeing that a little bit closer uh any uh south american uh closer uh any uh south american uh people want to correct me let me know uh people want to correct me let me know uh maybe it's getting better but yeah uh maybe it's getting better but yeah uh so i'm still just hanging out check out so i'm still just hanging out check out my instagram if you're curious about my instagram if you're curious about what i'm up to um maybe one day i'll what i'm up to um maybe one day i'll post a couple of drone for uh videos post a couple of drone for uh videos here uh if that makes sense but uh but here uh if that makes sense but uh but i'm not gonna use it on add digits what i'm not gonna use it on add digits what is this 258 digits easy okay repeating is this 258 digits easy okay repeating at all digits until the only have one at all digits until the only have one digit and we turn it so yeah so i mean digit and we turn it so yeah so i mean obviously the way to do it is just um obviously the way to do it is just um [Music] [Music] the way to do it is just by you know it's just by assimilating it with loop and requestion and so forth um the the weird thing of course is that there is this follow-up which there is a trick i don't um i don't know if there's uh how do i think about this can i explain this i don't know i'm not gonna lie this is just one of those things that i just remember uh and it does come up a lot in competitive programming though not necessarily interviews per se in that um hopefully this is right otherwise i'm never sad maybe i missed the edge case i think i missed an edge case wait did i okay maybe i'm just thinking of something else wow is that not right is that not right six four five nine six four five oh zero six four five nine six four five oh zero yeah that's right yeah that's right um um if the answer is nine yeah i forgot if the answer is nine yeah i forgot about this case but that's generally the about this case but that's generally the idea idea um why is this well i guess if the answer is nine that's also wrong right uh clearly i actually forgot the other case now that i think about it so maybe we can take this as an opportunity to um to go over it um that said i don't know the follow-up does make it not as easy the easy is if you just simulate it which is doing it one at a but but what is because a what's two plus eight plus five plus six um you know is it always just going to be nine yeah because it's not possible to be zero right so um well it is possible to be zero if it is zero um otherwise okay fine let's just write it out then if number is equal to zero we turn num uh otherwise we turn this unless it's zero then you add nine right um because if this is zero i'll just write it out except try to be clever if digit is equal to zero digit is equal to nine oops return digit right and it's uh it's kind of magical so i don't know how to kind of explain it to be honest uh i mean other than that just comes up a lot in competitive programming so i kind of internalize it uh to be honest um but i also don't know that this would be an interview thing so you could take it as you will maybe it is i i don't know if this is because this is just trivia at a certain point you can definitely prove this uh by kind of playing around with with the nine um and you can actually also if you want play around with non-base 10 numbers right so this this property that i'm doing now only works for base 10 um you can play around with different bases and see why or how it doesn't work and i think that will give you an intuition about how to get around it um but then another way of saying it is kind of you know we have 10 well ten is just um nine plus one right so so in that way you can kind of uh figure out how to um yeah and then all these nines kind of uh take take the essence away from the digits kind of uh i don't know i don't feel like i'm explaining that well so maybe just like explore it yourself ask me in the comments ask me on discord let me know what you think um but yeah that's what i'm gonna have for today and it's supposed to be easy and i kind of showed you the the cool way so i don't think this cool way even though it's cool but it is trivia i don't i don't know that i considered this um you know that seriously what are the hints that they give you yeah okay what are all possible results yeah okay how do they occur periodic or randomly yeah okay oh there's a wikipedia article maybe that oh digit that is the name of things i forgot about this name um but yeah so definitely apparently in the hint you can learn as much as you like so yeah there is some congruence type things but yeah oh i did not submit watch i get wrong on this that'll be funny um but yeah but it is accepted even though it's slower than last time what did i do two years ago a year and a half ago huh okay so i just did a some thing to eat and that was man okay anyway um cool that's all i have for this one let me know what you think uh stay good stay healthy to good mental health and i'll | 2024-03-22 12:15:43 | 258 | 258. Add Digits - Day 8/28 Leetcode February Challenge |
|
8xqZgLYaIpY | hello everyone and welcome to python programming and welcome to python programming practice practice in this episode we're going to be in this episode we're going to be covering lead code number 20 covering lead code number 20 valid parentheses this is marked as an valid parentheses this is marked as an easy problem easy problem we'll start by reading through the we'll start by reading through the problem description and examples problem description and examples so given a string s containing just the so given a string s containing just the characters characters these things the various open and these things the various open and closing closing braces and parentheses determine if the braces and parentheses determine if the input string is valid input string is valid an input string is valid if open an input string is valid if open brackets must be closed by the same type brackets must be closed by the same type of brackets of brackets and open brackets must be closed in the and open brackets must be closed in the correct order correct order example input s is just example input s is just this that's true because there's one this that's true because there's one open parenthesis open parenthesis and one closed parenthesis and it's in and one closed parenthesis and it's in the right order example number two you the right order example number two you pass a string that's this pass a string that's this well that is also true i guess because well that is also true i guess because that is that is valid closings this one is closed valid closings this one is closed immediately immediately this bracket is closed immediately this this bracket is closed immediately this curly brace is closed immediately curly brace is closed immediately those are all properly closed and the those are all properly closed and the third example we have a third example we have a open paren but then a brace a closing open paren but then a brace a closing brace after that that's false because brace after that that's false because that's not the right symbol to close it that's not the right symbol to close it so in this fourth example we have an so in this fourth example we have an open parenthesis open parenthesis and then open brace but then we have a and then open brace but then we have a close parenthesis close parenthesis and a closed brace and these are and a closed brace and these are appearing in the wrong order appearing in the wrong order this open brace needs to be closed this open brace needs to be closed before the outermost parentheses closed before the outermost parentheses closed so this one is false and then the so this one is false and then the last example is just another one that's last example is just another one that's true we have some true we have some opening curly braces opening opening curly braces opening brackets but they're closed in the brackets but they're closed in the proper order so the innermost proper order so the innermost thing needs to be closed first and it is thing needs to be closed first and it is so that one is true so that one is true and then the constraints for this and then the constraints for this problem the length of our input string problem the length of our input string is going to be between is going to be between one and a thousand and then one and a thousand and then the s consists only of the s consists only of parentheses characters so we're not parentheses characters so we're not going to see going to see any weird characters that aren't at any weird characters that aren't at least one of these six things so we least one of these six things so we don't have to don't have to deal with stuff like that so let's start deal with stuff like that so let's start by pulling up a whiteboard by pulling up a whiteboard and see about how we could go up coding and see about how we could go up coding a solution to this a solution to this so i have a potential input string here so i have a potential input string here on this whiteboard on this whiteboard just to think about how to approach this just to think about how to approach this problem and problem and the important thing to realize about the important thing to realize about this problem is that the innermost this problem is that the innermost parentheses always needs to be closed parentheses always needs to be closed first first and there's only three different and there's only three different possibilities possibilities that that could be it would be uh open that that could be it would be uh open and closed paran and closed paran an open enclosed brace or an open and an open enclosed brace or an open and closed closed curly brace those are the only innermost curly brace those are the only innermost things that can exist that are valid things that can exist that are valid so if it's a valid s string of so if it's a valid s string of opening closings these things will have opening closings these things will have to to exist somewhere within the depths of the exist somewhere within the depths of the openings and closings so basically one openings and closings so basically one way we could approach this problem way we could approach this problem is look in our string for is look in our string for any of these three valid closings any of these three valid closings that have to exist somewhere in the that have to exist somewhere in the innermost part innermost part of our parentheses and find that and of our parentheses and find that and just remove just remove it so that basically removes the it so that basically removes the innermost closing innermost closing and then whatever was outside of that and then whatever was outside of that becomes the new innermost thing becomes the new innermost thing and then we just remove that again so and then we just remove that again so for instance if we had this input string for instance if we had this input string we'd say okay let's see if this we'd say okay let's see if this exists in here well it does it exists exists in here well it does it exists right here so we'd want to find that right here so we'd want to find that remove it and then we'd go to a next remove it and then we'd go to a next iteration of a loop and see okay well iteration of a loop and see okay well now now where what are the innermost things and where what are the innermost things and we'll remove that so we'll remove that so now the innermost thing would be this now the innermost thing would be this closing brace but closing brace but if this thing was removed these would be if this thing was removed these would be right next to each other so it would right next to each other so it would just be this just be this and then we would want to remove that and then we would want to remove that and there's actually another one here so and there's actually another one here so we we want to remove that one too and then we want to remove that one too and then we go through a next loop and go through a next loop and at that point the only thing left in at that point the only thing left in this whole string would just be one this whole string would just be one opening and closing paren and we'd opening and closing paren and we'd remove that and at the end of all those remove that and at the end of all those removals removals we just end up with an empty string we just end up with an empty string because because we've successfully gone through and we've successfully gone through and removed removed everything that has a opening and everything that has a opening and closing that's valid closing that's valid so basically all we're going to do in so basically all we're going to do in code here code here is go through our string is go through our string and see if any of these and see if any of these exist within them exist within them and if they do we'll just replace it and if they do we'll just replace it with nothing so replace it with an empty with nothing so replace it with an empty string string and we'll keep doing that until we don't and we'll keep doing that until we don't find find any new things we can replace and if any new things we can replace and if we're left with an empty string then we're left with an empty string then it was valid and if we're left with it was valid and if we're left with something else something else then it was invalid so let's go ahead then it was invalid so let's go ahead and code up this solution and code up this solution so now we are in the code editor here we so now we are in the code editor here we are given are given a function called is valid we're past a a function called is valid we're past a string string s that's what we're going to be s that's what we're going to be operating on to see if it's operating on to see if it's a valid parentheses so we're going to a valid parentheses so we're going to call this method inner call this method inner string replace method string replace method so what we're going to do is we're going so what we're going to do is we're going to have a loop to have a loop keeping track of if we're able to keeping track of if we're able to replace something every time replace something every time and if we're not then we're going to and if we're not then we're going to exit the loop and see if we're left with exit the loop and see if we're left with an empty string or not an empty string or not so we're going to have a variable to so we're going to have a variable to keep track of if we were able to replace keep track of if we were able to replace something something so we'll start off being replace equals so we'll start off being replace equals true true while we're able to replace something and then we need to keep track of if we were able to replace something after this iteration of the loop the length of the string should go down so we'll keep track of the starting length will just be the length at the start of the loop and if this goes down after we try to replace things then we know we are still replacing stuff so the start length is going to be that and then for any valid inner parentheses so inner so for inner in and we just need a list of all of those valid possibilities that we want to replace so they were an opening and closing curly brace and opening and closing parentheses and an opening and closing square bracket we want to essentially try to replace we want to essentially try to replace them them with nothing if they exist that is with nothing if they exist that is removing removing whatever they are as the innermost whatever they are as the innermost opening and closings and getting rid of opening and closings and getting rid of them like we them like we looked at on the whiteboard so s equals looked at on the whiteboard so s equals s dot replace s dot replace uh the inner with nothing so this is uh the inner with nothing so this is just going to go through the whole just going to go through the whole string string see if it can find any positions where see if it can find any positions where these exist because that would be these exist because that would be an innermost opening closing and just an innermost opening closing and just basically stripping them out basically stripping them out so that we can go to the next iteration so that we can go to the next iteration in the loop and then see in the loop and then see whatever was one step out from that whatever was one step out from that we'll strip out after that we'll strip out after that so after doing those strips if so after doing those strips if our start length is still equal to our new length after we strip some stuff well if it's equal to the length still that means we didn't manage to strip anything which means replace is now equal to false and will break out of the loop but if the starting length is different than the current length after trying to strip some things then we know we strip something and we need to go through another iteration of the loop well that shouldn't say right that should say while and so this should go through the string doing all of the strips from the inside to the outside so if we're left with an empty string after this while loop exits that means we stripped out everything in the valid inner to outermost order and it should be a valid parentheses string where passed and if it's anything different then it should be invalid so we're just going to return s equal to empty string so basically if s is equal to the empty string this will be true and if it's not it'll be false so this should be a working solution to the problem here so i'm going to go ahead and click submit let's pull over and see the result of the run here so it did pass in 36 milliseconds faster than about 14 of other python 3 submissions so although it did work and it wasn't too difficult it doesn't seem to be a particularly efficient solution because it's not faster than most of the solutions other people made and there's various reasons that could be i mean we're having to check whether each of these exists in the string over and over again so that's doing quite a few operations and there's probably ways to avoid doing that so let's go back to the whiteboard and think about another possible solution to this problem maybe one that is a little bit faster or better than the one we had just made so the important thing to note here is that anytime we see a closing character it has to close the last opening character that was seen so for instance in this string here we see this first that's opening we see this next that's opening we see this next that's another opening but then we see our first closing character and this closing character has to match whatever the last opening character scene was so when we see this we can check in this little stack we've made here is that there and it is so in this case we'd say okay this does have a matching thing is the last thing we saw then we could remove this from this kind of stack we're making and then say okay what's the next thing okay it's another closing thing uh what is the last thing we've seen on our stack that hasn't been crossed out yet okay it is another closing brace we could cross that off we go to the next thing what's left on our stack it's a closing brace we cross that off etc so instead of kind of replacing things like we did before we could keep track of all the opening characters and then as soon as we see a closing character we can remove the last opening character that we saw using this kind of stack data structure so basically anytime we see an opening character we'll push it onto a stack and then any time we see a closing character we'll try to match it up with whatever the last thing on the stack is and remove that from the stack and after going through the entire string doing that we should be left with an empty string where we were always able to match the closing character whatever it was with the last thing that was on the stack and if that's ever not the case then we know it's not valid and we just immediately return false and a solution using this method should be faster than the one we made first because we're not having to look through the string many different times and trying to see if things exist in it and replace them we're basically just going to have to go through once we'll just loop through the string once and we'll keep track of all the openings and cross off the closings as we see them so that should just be a straight up of n solution instead of something where we're potentially having to search through the string several times so let's go back into the code editor and add this solution as well so we're going to close the last scene opening close the last scene opening symbol with stack symbol with stack because that's an important part of the because that's an important part of the problem so problem so i did go ahead and prepare uh i did go ahead and prepare uh this ahead of time just because i didn't this ahead of time just because i didn't want to type all this out but basically want to type all this out but basically all this is doing is giving us all this is doing is giving us a little dictionary that's mapping each a little dictionary that's mapping each opening character to its closing opening character to its closing character called close map so character called close map so an open paren is mapped to a close an an open paren is mapped to a close an opening opening curly brace to a close etc so we're curly brace to a close etc so we're going to need to use that just to make going to need to use that just to make sure sure we can match things up efficiently and we can match things up efficiently and now we have to now we have to initialize the stack that is going to initialize the stack that is going to keep track of keep track of all of the opening characters we've seen all of the opening characters we've seen in order that we see them in order that we see them so let's call that say opens it'll be so let's call that say opens it'll be start off as an empty list and then as start off as an empty list and then as we see those opening characters we'll we see those opening characters we'll append them onto the list and now all we append them onto the list and now all we have to do is write our single for loop have to do is write our single for loop and go through and implement and go through and implement the logic so for symbol the logic so for symbol in s if the symbol symbol is an opening character which is anything in our close map the keys of the closed map are all the opening characters so if symbol that is a symbol in closemap.keys then we want to put it onto our stack symbol so that's saying anytime we see symbol so that's saying anytime we see an opening character we want to put it an opening character we want to put it onto onto our openings stack or list here our openings stack or list here so now if we didn't see an opening so now if we didn't see an opening character character that means we're seeing a closing that means we're seeing a closing character and we need to handle that character and we need to handle that case case so in that case alif else if so in that case alif else if so if we have a closing character and so if we have a closing character and our opening stack is empty that means our opening stack is empty that means there's nothing in there to close it off there's nothing in there to close it off against against which means we're seeing a closing which means we're seeing a closing character character before we saw the appropriate matching before we saw the appropriate matching open character and if that's the case open character and if that's the case this isn't a valid this isn't a valid parentheses so we just want to say false parentheses so we just want to say false on that so on that so if opens is empty if opens is empty in that case so we're looking at a in that case so we're looking at a closing character but closing character but we don't have anything to match it off we don't have anything to match it off against that's going to be false against that's going to be false now there's another scenario where the now there's another scenario where the closing character we're looking at here closing character we're looking at here might be the wrong thing and we should might be the wrong thing and we should return false return false and that's if it doesn't match up with and that's if it doesn't match up with the last the last opening character that we saw so or opening character that we saw so or if the symbol we are looking at does not if the symbol we are looking at does not match up match up with the last thing that we saw so with the last thing that we saw so our close map the last thing that we saw our close map the last thing that we saw was opens the last thing it opens was opens the last thing it opens which is opens dot pop which is opens dot pop so basically we're treating this list as so basically we're treating this list as a stack a stack so opens.pop is going to take the last so opens.pop is going to take the last opening character that we saw and take opening character that we saw and take it off the end of the list it off the end of the list and we're going to pass it into close and we're going to pass it into close map to find what the appropriate map to find what the appropriate closing character should be so for closing character should be so for instance if the last instance if the last thing we saw was a open parenthesis thing we saw was a open parenthesis we're popping that off of the end we're popping that off of the end and then by passing it into the indexer and then by passing it into the indexer for close map we're saying okay this for close map we're saying okay this should be should be the matching closing character so if our the matching closing character so if our closing character closing character is not equal to that matching closing is not equal to that matching closing character that it should be character that it should be then we know that it matched the wrong then we know that it matched the wrong type of thing type of thing and this is also then an invalid and this is also then an invalid uh sequence and we should return false uh sequence and we should return false so basically so basically if the opens is empty or if the opens is empty or if the closing character doesn't match if the closing character doesn't match the closing character that should be the closing character that should be we need to return false so now this loop we need to return false so now this loop here should be here should be going through the whole string any time going through the whole string any time it it sees an opening character it will put it sees an opening character it will put it in our open stack and anytime it sees a in our open stack and anytime it sees a closing character closing character it will pop off that last opening it will pop off that last opening character we saw character we saw see if it matches up and if it does see if it matches up and if it does it'll continue on to the next iteration it'll continue on to the next iteration if it doesn't it'll just exit and say if it doesn't it'll just exit and say false but false but after this runs through the entire after this runs through the entire string string if we haven't found a situation where we if we haven't found a situation where we didn't match what we wanted to that didn't match what we wanted to that means we means we got through the whole string and didn't got through the whole string and didn't return false yet return false yet so if we get to the end and that's the so if we get to the end and that's the case and we still haven't returned yet case and we still haven't returned yet that means the only other situation that means the only other situation where we might have an where we might have an invalid string is if we had invalid string is if we had more opening characters than closing more opening characters than closing characters characters that would mean that the open stack here that would mean that the open stack here still has some still has some opening characters on it that haven't opening characters on it that haven't been closed yet been closed yet and if that's the case it's going to be and if that's the case it's going to be false so what we can just do false so what we can just do is return well if opens is empty is return well if opens is empty that means all the opening parentheses that means all the opening parentheses were were appropriately closed so basically all appropriately closed so basically all this is saying is this is saying is if we managed to close everything that if we managed to close everything that we opened we opened then we should return true and if we then we should return true and if we didn't manage to close everything that didn't manage to close everything that we open then we open then this will be false oh i noticed a this will be false oh i noticed a problem here we're going to problem here we're going to have to return false not just say false have to return false not just say false so i'm going to go ahead and click so i'm going to go ahead and click submit on this one submit on this one and hopefully there are no issues it is and hopefully there are no issues it is running let's pull over and see the run running let's pull over and see the run so this time we got a speed of 28 so this time we got a speed of 28 milliseconds which is a milliseconds which is a a bit faster than the first attempt and a bit faster than the first attempt and that was faster than 82 that was faster than 82 of other python 3 submissions so i hope of other python 3 submissions so i hope this gave you a couple ideas about how this gave you a couple ideas about how you could approach a problem like this you could approach a problem like this and hopefully also illustrate a bit and hopefully also illustrate a bit about the value of about the value of a stack data structure so something a stack data structure so something where you where you put things in sequentially and then you put things in sequentially and then you take off the last thing that you take off the last thing that you saw first so a last in saw first so a last in first out type data structure can be first out type data structure can be useful in certain applications useful in certain applications so thanks for watching and keep coding so thanks for watching and keep coding you | 2024-03-19 17:01:35 | 20 | Python Programming Practice: LeetCode #20 -- Valid Parentheses |
|
wOHXmV_VIBs | next problem is called set Matrix zeros and in this problem we are given an N times n integer Matrix called Matrix and if an element is zero we have to set the entire row and column to zeros and we have to do it in place so for the for example we have the central zero so we have to make the second row and the second column in a matrix three times three to zeros and as you can see here we did that in the second example we have the zero at the located at the First Column first row so we have to make zero we have to make zeros all the elements that are inside the First Column and inside the first row which we do after the transformation and our second zero is in the first row we already transformed all the all the numbers to zeros in the first row the remaining work is to transform all the elements inside the last column to zeros which we do here um the m and then are just major dimensions and they can range from 1 to 200 and we we have a normal distribution from the for the elements of the math matrix ranging from the minimal integer to the maximum intellectual integer now if we move uh we also have some additional follow-ups uh first is that's a straightforward you so solution using M times n space is probably a bad idea um that means that we would have to basically create a the same uh same Dimension Matrix as as our input as additional space we will try to do it in less space so that's the second follow-up simple Improvement uses M plus n space but it's still not the best solution and our desired solution uses constant space so we will we will know how we will see how can we derive the cost of space solution so here we have an example and this is this is the Matrix for the from the second example from the program statement and as you can see we have here um additional data structure these are basically just arrays um and they are they are of the same so this array is of the same length as the number of columns which is four and this is basically a number of rows which is three in the in our in our example so to get the Matrix to get the desired Matrix transformation we will Traverse The Matrix which is basically M types and time complexity and if we see for example in the first column if we see in the First Column so after returns like this if we see a zero that means that we have to mark the corresponding row and the column that has to be transformed so for example here we have so this can be a Boolean and the default value will be false and you see that our first element is zero so we have to transform we have to say that our first row should be all zeros and also our first column should be all zeros next we go to the element one and in this case it's non-zero element so we still have faults here inside the inside the second column and also we don't change the value for the for the first row because it's set to true then we move to number two we still keep the true be not we do not overwrite the True Value in the first row because we know we have to transform all the elements inside the first row to zeros we just put uh we keep basically the third value because in the input the Mad matrix it's not and then zero it's a non-zero value so we just keep our full swap in this additional data additional array and the last element zero so we have to put true here because we have transformed the last column as well we have to transform all the elements in the last column to zeros as well Now we move to the uh to the next row and as you can see there's no zero elements in both of the rows so this will remain false we don't have to transform the second and the third row and also these values here these false value will not be turned switched to true because as both both of them don't contain the the both both of them don't contain the the only contains the non-zero elements only contains the non-zero elements there's no zeros inside these two there's no zeros inside these two columns now we can use these data columns now we can use these data structures to control structures to control uh the transformation of the Matrix so uh the transformation of the Matrix so basically if we have true here we will basically if we have true here we will Traverse this array and if we have true Traverse this array and if we have true here in our here in our in our input Matrix we will transform in our input Matrix we will transform the whole row the whole row to uh non-zeros to to zeros in this case to uh non-zeros to to zeros in this case so because it's true it will if all of so because it's true it will if all of them will become zeros then we go to the them will become zeros then we go to the second uh element in this controller second uh element in this controller array and it's false so we don't do array and it's false so we don't do anything with the second column same anything with the second column same goes for the third column and for the goes for the third column and for the fourth column we transform everything in fourth column we transform everything in the fourth uh in the in the fourth the fourth uh in the in the fourth column two zeros column two zeros we do the same then traversing this we do the same then traversing this array for each row if it's uh if this array for each row if it's uh if this value is true we transform all the value is true we transform all the values in the input Matrix to zeros values in the input Matrix to zeros here is false so we will just keep the here is false so we will just keep the values as they are and so on values as they are and so on so in this case we would have M plus n so in this case we would have M plus n uh space complexity because we have to uh space complexity because we have to create an array that size of the number create an array that size of the number of columns and also on the rated size of of columns and also on the rated size of the number of rows the number of rows but the thing is we want to reduce this but the thing is we want to reduce this to constant to constant constant space constant space so in this constant space constant space so in this case as if you can notice that our first case as if you can notice that our first our first and let me just quickly switch our first and let me just quickly switch to another color here our first row to another color here our first row and our first column and our first column can serve as these control arrays can serve as these control arrays and what I mean by that we will use the and what I mean by that we will use the input Matrix actually a part of it the input Matrix actually a part of it the first row first row and the first column and the first column to mark that the specific column or a to mark that the specific column or a specific row has to be transformed to specific row has to be transformed to zeros zeros and we will we will do the same and we will we will do the same transformation as we did here so uh we transformation as we did here so uh we will just instead of using true and will just instead of using true and false we will just put zeros inside the false we will just put zeros inside the inside element so for example uh inside element so for example uh here we in the first row we all all of here we in the first row we all all of them will become eventually zeros them will become eventually zeros because we have a zero inside the as a because we have a zero inside the as a first element first element example here example here and and the only thing that left to do here is the only thing that left to do here is to before we use the first row and First to before we use the first row and First Column as the controller arrays is we Column as the controller arrays is we will Traverse it both the First Column will Traverse it both the First Column and first array to check if there are and first array to check if there are zeros inside of it before we do zeros inside of it before we do transformation before we start to insert transformation before we start to insert the zeros and specific columns the zeros and specific columns um or or rows and if we will just have um or or rows and if we will just have two booleans uh the first row has uh has two booleans uh the first row has uh has a zero and the First Column has a zero a zero and the First Column has a zero so we can accordingly transform both the so we can accordingly transform both the the first row and the first column so let's hold this problem using Java program language first we will just for the readability purposes we will Define our Dimensions rows and columns uh then we will declare two booleans uh for um tracking if our first row should also become zeroed and uh if our first column should become zero and that basically means that First Column or the first row contain zero themselves next we will Traverse through the first all the the first uh the first row and if there's any zero inside the first row We Will We Will declare our zero first row uh we will set it to true and the same goes for the columns uh we'll Traverse our first column and if there's a zero in the First Column we will just put the set the zero First Column to to true by doing this after after we are done with reversing the The Matrix we know that if the zero first row is equal to true we know that we have to zero all the elements inside the first row the same goes for the First Column if it's at true we know that we have to zero all the numbers that are inside the first column now we've traversed to The Matrix first iterating through rows it's a standard double double for Loop um and checking if the number in the current number it coordinates I and J is equal to 0 and if it's equal to zero we will set the corresponding Row in the column and we will do this by using our first column and first row so for example if we if we have a zero element inside the second row second column we will we will set 0 to our second element inside our first row and our second element inside our first column so that we know that we have to zero out all the elements that are inside the second column and second row which we actually do inside our next four to four Loops we check we first we Traverse row by row and for each uh for each row uh we check in the First Column if the value is equal to zero if it's equal to zero we have to transform the whole row to zeros we do basically the same now for the columns we to reverse by The Columns and for uh for each um inside each column we check it uh inside our first first row that we have uh a zero value if you have it in that position declares what column which column should be zeroed out and the remaining thing to do is to check if r0 for a show we set to true in which case we zero out the whole row and if our zero First Column if our first column is um uh contains a zero and if it does we just zero out the whole column in this case we are using only the input Matrix itself so the space complexity is constant while we have at most traversal two Matrix which is um basically the product of its Dimensions when it comes from times time time complexity which in this case is just m times n where m is number of rows | 2024-03-20 11:34:24 | 73 | Set Matrix Zeroes - Leetcode 73 |
|
RIMkVshmVLs | Hello hello guys to Ajay, I asked on this occasion that Sachin himself will submit this question, it is a Sachin himself will submit this question, it is a festival whose religion is on this number and festival whose religion is on this number and people ask this question once, this question also for people ask this question once, this question also for a little bit, after this see what problem has to be set here too, a little bit, after this see what problem has to be set here too, then you can understand this thing. then you can understand this thing. Okay, and you add this number, Okay, and you add this number, okay, so like number one number 10, now okay, so like number one number 10, now tell me this, I only know this much information on the number, so to tell me this, I only know this much information on the number, so to use one thing, use one thing, stars are included in the function from the stars are included in the function from the beginning to the end with many numbers. beginning to the end with many numbers. For now, I am in the West, in which For now, I am in the West, in which he has shifted, to tell me he has shifted, to tell me which number, but the which number, but the problem statement in front of me is so big, problem statement in front of me is so big, okay, the problem statement in front of me is so big, from okay, the problem statement in front of me is so big, from one to three one to three to the toilet. to the toilet. to the toilet. gave me the facility to use the day function and that function called gas. If I called him and I asked him, I have not done anything till now, my friend, you did not get 982 I I I asked him did you get it done somewhere in the 90s? He will asked him did you get it done somewhere in the 90s? He will not answer me in true or false. He will not answer me in true or false. He will ask here plus one here - mother these days ask here plus one here - mother these days ask on glass - 140 show some of these albums ask on glass - 140 show some of these albums when he will answer me plus one then he is when he will answer me plus one then he is saying that saying that thinking that it is from my gas number which I have just thinking that it is from my gas number which I have just added to you, then its plus will added to you, then its plus will tell in Mandalgarh only that if you tell in Mandalgarh only that if you click on it, it is higher than my guest number. click on it, it is higher than my guest number. - Mannat, the number he has to pick is - Mannat, the number he has to pick is based on my gas number and if he based on my gas number and if he returns it then I will be happy returns it then I will be happy because the number he has to pick is the same as the one because the number he has to pick is the same as the one I have just dialed. Okay, I have just dialed. Okay, so actually the question remains. so actually the question remains. so actually the question remains. left is that there is such a big problem in front of you, you do the statement on one number, okay that Yadav President will do it, he will say that do it on the number, which number is bigger than yours or - 110 will spoil that page number and If the number is less than 1000 and If the number is less than 1000 and If the number is less than 1000 and will return zero then the number he has to pick is will return zero then the number he has to pick is equal to the office number so earlier that day equal to the office number so earlier that day this is the number which we have given that the gas is bad which will this is the number which we have given that the gas is bad which will return to me, this is the problem return to me, this is the problem state this is the problem because of this I am state this is the problem because of this I am in problem. in problem. in problem. Okay, I do n't need to travel from one to 100 so that I can click and do the driver. Okay, on this day, place him on the gas off number. I I I will sit, whatever he had to pick, it is okay, will sit, whatever he had to pick, it is okay, so I do so I do not need to type from one to thousand, but I will do, not need to type from one to thousand, but I will do, I can do binary search on it, I can do binary search on it, by typing OK by less, we will see these three options, by typing OK by less, we will see these three options, which one I which one I which one I day my Gas Karao number and his pick Ravana number became equal, that day it is very big but if there is any one of these situations, it means when Laxman One One One this greater than gas to pick this greater than job this greater than gas to pick this greater than job also I do gas his own you can understand also I do gas his own you can understand this we understand that cigarette inside we this we understand that cigarette inside we here what he has picked fix smaller than here what he has picked fix smaller than thumb and finally here pick in juice the karma is thumb and finally here pick in juice the karma is equal to that equal to that equal to that these three situations mean taking Edison, if pick and we are equal ahead, then it is very good, if cigarette Annamma is either off, Hello friends, Elephant and I will cut off the points, I will then cut off Vansh Vansh but will not search a bit, get her picked, number if Bigger than toilet vs part Bigger than toilet vs part Bigger than toilet vs part is ok and if the pickup number is smaller than my gas number is ok and if the pickup number is smaller than my gas number then I will cut the right side police and give it on then I will cut the right side police and give it on time in school tiffin, it was just a matter of time in school tiffin, it was just a matter of reading out and applied whether you reading out and applied whether you will set it now it seems will set it now it seems will set it now it seems how you will apply it, there was a little board problem, this too there was butter in front, neither was it as simple as applying chilli once in front, like let's say just tomorrow, I will tell you in these short words that I am going to do nothing, Here, for example, if you and I Here, for example, if you and I Here, for example, if you and I show you a little travel, then show you a little travel, then she is putting a little note on it and she is putting a little note on it and now name it after keeping it as Noida, then I now name it after keeping it as Noida, then I understood, then I would have written it like this, it is a generalized understood, then I would have written it like this, it is a generalized fault, it is okay that I am basically fault, it is okay that I am basically fault, it is okay that I am basically what will happen and how will I know that he decided to use gift to me. Find the function called gas. So he will know how close his pick number was to my number. It Wise Wise Wise that we will make it on one and we will that we will make it on one and we will make it for ₹ 1000, I have written a tremendous letter to you, you will make it for ₹ 1000, I have written a tremendous letter to you, you will understand something, I took it out for the first time, if I say installed, then I took out the understand something, I took it out for the first time, if I say installed, then I took out the name, name, I am guessing this number is I am guessing this number is lagging behind in it, so I took out the minute. lagging behind in it, so I took out the minute. lagging behind in it, so I took out the minute. or in minutes will it take to get your money? Private data is laughing powder type. If you understand then by now we will pass this 518 to gas gas. I was shifted to the accused. When I pass this favorite, what will be my return? I will get The one which is telling me The one which is telling me The one which is telling me that sorry laughed, I will have a liter - - - The that sorry laughed, I will have a liter - - - The temples are telling me that temples are telling me that if I pick her up with my gassed number then it would if I pick her up with my gassed number then it would be better to make her number be better to make her number smaller than mine. number he has picked is small, number he has picked is small, like me, he will make it - 110 - like me, he will make it - 110 - I will say that brother, you will get 500 help, you are I will say that brother, you will get 500 help, you are not going to get anything from phase to 100, by not going to get anything from phase to 100, by picking it and keeping it at minute minus point, by picking it and keeping it at minute minus point, by picking hike. picking hike. picking hike. continue your setting from closed to 489. By calling the same gas after the same guest, half of the problem statement and half of the problem have disappeared just like that, Ok, Ok, Ok, so try traveling on this bike, you will keep getting looted till now, you may not understand but friends, if you had taken it out, you will keep getting looted till now, you may not understand but friends, if you had taken it out, I would have taken it out on the media, it will cost Rs 250, I would have taken it out on the media, it will cost Rs 250, but again get it picked up, the number is but again get it picked up, the number is smaller than the number one, please gas me. smaller than the number one, please gas me. smaller than the number one, please gas me. 110 then I will say again that it is okay, it means that from 250 onwards there is nothing to be found in the point name, pick it up and keep it in your mind, now keep the spark again, okay then interest, this Very good, this is also a Very good, this is also a Very good, this is also a job. Judging this problem statement, job. Judging this problem statement, I will write it quickly for you. Okay, so I will write it quickly for you. Okay, so let's write this quickly. Okay, so let's write this quickly. Okay, so what do I have to take here? He what do I have to take here? He could have done it initially, so keeping it on the people, could have done it initially, so keeping it on the people, Sachin. Sachin. Sachin. doing my work, I am adding this number to know how to do this, remember that now the school has given you the result, so you are asking this, how far is it from her house, she I am this I am this I am this jerk, then you can name it anything, it doesn't matter otherwise, the jerk, then you can name it anything, it doesn't matter otherwise, the midwicket pick which he had midwicket pick which he had picked is exactly the same, so I have picked is exactly the same, so I have guessed which number was to be picked in this, guessed which number was to be picked in this, so I will return the minute we picked this so I will return the minute we picked this number. number. number. then we will choose a direction. If gas fennel I have returned here - do not mean then it meant that pick his worker and use my number which So I write here So I write here So I write here that his picked number is that his picked number is smaller than my gased number, then it means smaller than my gased number, then it means I should continue Sachin on the left side. To I should continue Sachin on the left side. To continue Sachin on the different side, continue Sachin on the different side, keep it at the minimum that brother here is the keep it at the minimum that brother here is the area. area. area. meaning of the next one is, what will be the simple meaning of gas after minute, I will return plus one. Okay, if you don't want to write like this, then write it like Singh Sarpanch as you like. Turn on this clear minute or in the form of plus one. This means that its sold value has increased from my gassed WB, so I should continue Sachin on the right side, people should pick up and keep me, I will be on Mitt Plus One, while doing this, I am sure that from here on From here something or the other will be returned but if this is a claim then I will have to write minus one outside as well. It's okay because it has to be satisfied that my function will always retail. Tell me my answer will be returned from here but still Tuesday If the compiler is fine then If the compiler is fine then If the compiler is fine then run it once and see once it makes profit. So run it once and see once it makes profit. So we have made this number. If his we have made this number. If his pick is equal to our gas then it is great. If pick is equal to our gas then it is great. If his pick is smaller than our gas then let's his pick is smaller than our gas then let's go to the left to search and if go to the left to search and if go to the left to search and if big like us, so right, I will keep searching, it is very good, I would like to run it once, okay, now it seems right, Hmm sir, after understanding one thing, I hope I hope I hope you would have liked this portion, there was nothing, but we will you would have liked this portion, there was nothing, but we will see about it, I see about it, I would like to repeat this further, such questions would like to repeat this further, such questions take more time for God's testing, the take more time for God's testing, the questions are very easy method or but the questions are very easy method or but the statement might be a little bit confusing statement might be a little bit confusing like you here if you pay attention to them. like you here if you pay attention to them. like you here if you pay attention to them. study from, what does minus one represent, what does plus one represent, what does zero represent, then it is possible that you may spend a lot of time in a very easy question, okay, so you will have to have a But Syed, we But Syed, we But Syed, we meet him in this video OK GO meet him in this video OK GO O | 2024-03-24 11:39:14 | 374 | Guess Number Higher or Lower | Leetcode 374 Solution | Searching and Sorting |
|
glfn5nyazgw | hey hey everybody this is larry this is day 12 of the april eco daily challenge day 12 of the april eco daily challenge hit the like button hit the subscribe hit the like button hit the subscribe button join me on discord let me know button join me on discord let me know what you think about today's prom what you think about today's prom today's problem is game of life today's problem is game of life okay okay um um i guess the game of life is pretty i guess the game of life is pretty standard so let's standard so let's take a while to see how everyone else is take a while to see how everyone else is doing uh yeah so there's a this is doing uh yeah so there's a this is monday or tuesday wherever you are i monday or tuesday wherever you are i hope you are having a great week uh hope you are having a great week uh everything's going okay i am everything's going okay i am going to i don't know let me know what going to i don't know let me know what you y'all been you y'all been what movies y'all have been watching what movies y'all have been watching i've been uh going on watching a lot of i've been uh going on watching a lot of movies lately let me know in the movies lately let me know in the comments or discord there's a lot of comments or discord there's a lot of cool smart people hanging out on discord cool smart people hanging out on discord i need to create some i need to create some thing also if you're in new york let me thing also if you're in new york let me know if yeah on discord because i think know if yeah on discord because i think we're trying to get some like hangout or we're trying to get some like hangout or whatever going around um we'll see where whatever going around um we'll see where that goes anyway today's problem is game that goes anyway today's problem is game of life so we know what game of life is of life so we know what game of life is i do if you know then i guess you know i do if you know then i guess you know that's what this is reading and i guess that's what this is reading and i guess it's good it's good um you know uh uh um you know uh uh whatever but let's let's look at the whatever but let's let's look at the follow-ups just because you know this is follow-ups just because you know this is pretty straightforward pretty straightforward could you solve the price solve it in could you solve the price solve it in place place uh remember the board needs to be uh remember the board needs to be updated simultaneously you can update updated simultaneously you can update some cells first and update okay some cells first and update okay and this question to the array in and this question to the array in principle the board is infinite what principle the board is infinite what would cause problems when the act i would cause problems when the act i guess this is just talking about it guess this is just talking about it um yeah i mean i think you can always do um yeah i mean i think you can always do something like something like uh repeat doubling is always a uh repeat doubling is always a an option um i think the thing is that an option um i think the thing is that you're trying to do the math on the you're trying to do the math on the repeat doubling and of course repeat doubling and of course if you do the math um on the repeat if you do the math um on the repeat doubling which is actually comes up in doubling which is actually comes up in hash tables and stuff like this if you hash tables and stuff like this if you ever study it um then you'll know that ever study it um then you'll know that uh maybe repeat doubling is in the but uh maybe repeat doubling is in the but basically once you get to some fill basically once you get to some fill factor in this case you could wait until factor in this case you could wait until it hits the border then you can double it hits the border then you can double it right in that case it's going to be it right in that case it's going to be amortized constant just because you amortized constant just because you can't do the math the same way you do it can't do the math the same way you do it with hash tables i think with hash tables i think that problem we could talk about that if that problem we could talk about that if y'all like but that's basically the idea y'all like but that's basically the idea that i would have there um that i would have there um so in the two dimension maybe that's a so in the two dimension maybe that's a little bit more tricky but i don't little bit more tricky but i don't imagine so imagine so um because i think you could treat the um because i think you could treat the dimensions independently in any case for dimensions independently in any case for in terms of in terms of uh that um of course you can also treat uh that um of course you can also treat maybe sparse arrays or a boss matrix and maybe sparse arrays or a boss matrix and play around with that depending on how play around with that depending on how it goes i don't it goes i don't yeah it may be a little tricky uh the yeah it may be a little tricky uh the second part which i guess we'll try to second part which i guess we'll try to do now is to impress because this is do now is to impress because this is relatively relatively straightforward straightforward um i don't think this would be a medium um i don't think this would be a medium anymore to be honest just because this anymore to be honest just because this problem is very old but um with that problem is very old but um with that said not to say that you know in an said not to say that you know in an interview it would still be okay interview it would still be okay but um but um [Music] [Music] but yeah uh so how would you do this in but yeah uh so how would you do this in place i actually don't know let's see i place i actually don't know let's see i think it's so think it's so there is a cheating way of doing it in there is a cheating way of doing it in place but i don't like it which is just place but i don't like it which is just you know you see that these things are you know you see that these things are ins so you kind of use like the upper ins so you kind of use like the upper bit or maybe use like another bit right bit or maybe use like another bit right off that inch because because an inch off that inch because because an inch could fit 32 bits or whatever so you could fit 32 bits or whatever so you could play around with that idea and could play around with that idea and that'll technically work so that's fine that'll technically work so that's fine maybe but i feel like that's almost maybe but i feel like that's almost cheating and not in the spirit of things cheating and not in the spirit of things um because maybe one of what these are um because maybe one of what these are bullions right so then can you do that bullions right so then can you do that in that way i think in that case in that way i think in that case i would have to look at the rules and i would have to look at the rules and kind of think about it which i haven't kind of think about it which i haven't done yet to be honest uh i hope it's not done yet to be honest uh i hope it's not the the the the upper bit upper bit thing because that's like uh thing because that's like uh i consider almost cheating or it's like i consider almost cheating or it's like it's not that interesting right like you it's not that interesting right like you just use more you use extra space just just use more you use extra space just embed it into the thing or something embed it into the thing or something right um okay so the rule is right um okay so the rule is fewer than two is dead fewer than two is dead um so i guess um so i guess the way that i would think about solving the way that i would think about solving this if you have to update this this if you have to update this simultaneously so to speak simultaneously so to speak is is that um you try to you know it is simultaneous you try to exploit the rules in a way such that it is not simultaneous right maybe it doesn't make sense for the game of life but there are rules where okay you maybe change it to zero because no matter what happens the change to zero will always be true etc right um so yeah so i think i would see it that way and then see if you could figure out some ordering in which you can do it i don't know that i remember my experience of game of life is that i don't think that that's the that's a thing but i could be wrong here um let me see let me i do have to go watch a movie so uh that me that's why i'm asking i'm watching in case you're wondering at home uh everywhere everything everywhere or at once someone like that um it's got great reviews i'm i'm gonna try to catch but but yeah i don't know yeah i don't know um um i mean yeah i i mean yeah i don't know if i know one that isn't like don't know if i know one that isn't like quote-unquote cheating and if we are quote-unquote cheating and if we are going to cheat i don't i don't feel like going to cheat i don't i don't feel like you know like if you're gonna do some you know like if you're gonna do some kind of hacky things like that then kind of hacky things like that then i at least i always opt for making more i at least i always opt for making more beautiful code unless you um beautiful code unless you um need to optimize right like there's no need to optimize right like there's no you shouldn't prematurely optimize you shouldn't prematurely optimize because if you because if you uh like if you like maybe if you're uh like if you like maybe if you're doing like embedded systems or you're doing like embedded systems or you're put putting it in your your handheld put putting it in your your handheld which at least way back when a day like which at least way back when a day like uh maybe that's a thing that you have to uh maybe that's a thing that you have to consider uh like space efficiency like consider uh like space efficiency like programming for nintendo like programming for nintendo like you know 20 years ago or something like you know 20 years ago or something like and yes uh maybe more now 20 years ago and yes uh maybe more now 20 years ago even even um the playstation's already out but you um the playstation's already out but you know i can't do math all the time so um know i can't do math all the time so um yeah yeah uh i don't know i don't think that there uh i don't know i don't think that there is i would be i would be is i would be i would be honestly a little bit kind of surprised honestly a little bit kind of surprised um if um if you can just because and some of this is you can just because and some of this is arrogance in the sense that if if arrogance in the sense that if if there's a way to do that i would have there's a way to do that i would have known already in the sense that i have known already in the sense that i have you know and this is you know and this is maybe you know applied to your career as maybe you know applied to your career as well is that well is that when you have um oh my alarm calls me when you have um oh my alarm calls me hang on hang on um i had to tell my alexa to uh oops now it got triggered again to to turn off my uh my alarm because it just kind of it was to wake me up in case i was taking a nap too long um but in any case um yeah so that's what experience means right is that you know you you have seen it enough and i've seen the game of life a lot of variations a lot of time it comes up on aoc uh the advent of code it comes with a lot of it is a very um you know finite automata type thing where everyone's just very interested in this form and a lot of uh um uh there are a lot of uh what you might call it uh there are a lot of easy computer sciency problems to explore with just like symbol ruleset right which is why it draws a lot of people to it and you should read the wikipedia article um uh by the you know mathematician conway he passed away two years ago i want to say um that was kind of you know sad obviously but um um so yeah so definitely like to that sense and i probably have been very interested in it at some point in the past especially this idea of um you know if you really read deeply into it and you know i encourage people who are interested to do so um there's also like this stuff with respect to roof rooms uh a new kind of mathematics i bring us the book i'm calling it off my head so if i miss uh name some books or whatever leave a comment or google or whatever but yeah so definitely it's just very interesting and my point here is that if i have known it maybe i would have seen it i mean i'm not 100 certain i you know i'm i have a lot of gaps in my knowledge like the the z algorithm from the other day but yeah but that's what i believe so before that said that's just my long way of rationalizing and explaining to you that i am just going to do it with the extra bit the cheating bit um and then um well i'm going to do it in another way right and then i'm going to do it the the the extra space way and then i'm gonna rewrite it so that you can see what it looks like um when you have the cheating bin as you call it um i i quit that but it's not maybe it's fine i don't know okay let's get started let's just go um how many iterations do they want i actually missed that part is it just one state okay so it's just the next state um okay so yeah so you just do next board is equal to uh well let's set it up r is equal to language board c is a link for port of zero uh just making sure that it cannot be zero so okay otherwise you get a whole bounce uh okay so then here we set it to force right so now we're just saying of ic right so now we're just saying of ic board so board so now now we go for x in range of r for y in range we go for x in range of r for y in range of c of c we go maybe do something like we go maybe do something like uh uh you only care about live neighbors in you only care about live neighbors in these rows so maybe we do like if these rows so maybe we do like if count count oops counting of x y oops counting of x y uh or maybe just c is your count of x y uh or maybe just c is your count of x y so then you can do uh and then you could so then you can do uh and then you could do all sorts of permutation meaning if do all sorts of permutation meaning if point point sub c sub c i don't like this one zero thing but it i don't like this one zero thing but it is what it is so because i think that's is what it is so because i think that's i don't know okay uh oops board of x y i don't know okay uh oops board of x y if this is um let's see if this is um let's see fewer than two oh this is one fewer than two oh this is one [Music] [Music] um um okay if this is one i mean this is just okay if this is one i mean this is just really going through the cases right if really going through the cases right if c is fewer c is fewer than two uh next than two uh next for for um um [Music] [Music] x y is equal to force right x y is equal to force right uh yeah uh yeah it it else if c with else if c with uh is between two and three uh is between two and three then next four then next four x y is equal to true and then else i x y is equal to true and then else i mean i mean i i also yeah i just want to be clear i i also yeah i just want to be clear i know that i can rewrite this if know that i can rewrite this if statement in an easier way statement in an easier way or shorter way but i want to be as or shorter way but i want to be as explicit as possible so that is you so explicit as possible so that is you so that when you make a mistake you don't that when you make a mistake you don't have to just debug your have to just debug your your your logic you can just look at the your your logic you can just look at the code and look at how it translates to to code and look at how it translates to to the rules that they give you right so the rules that they give you right so that's basically the idea um okay that's basically the idea um okay otherwise otherwise um okay so that means that this is dead um okay so that means that this is dead if if c c is equal to three next point is equal to three next point let's go to oops let's go to oops true else next port stays true else next port stays dead right dead right and then now at the very end uh and then now at the very end uh we copy it back over right next and i know you can do some stuff but uh yeah but i like to be explicit for this particular example just for illustration there's no return but of course we have to write this count function uh which we uh yeah uh yeah let's see right let's see right um um therefore dx in range of from negative therefore dx in range of from negative one to one of course it's one plus one one to one of course it's one plus one because it's exclusive because it's exclusive and i always find that a little bit and i always find that a little bit awkward but i'm just writing it out so awkward but i'm just writing it out so that you can kind of see what i mean but that you can kind of see what i mean but yeah if dx is equal to zero and d y is yeah if dx is equal to zero and d y is equal to zero we contain u i i sometimes equal to zero we contain u i i sometimes write this differently but today i'm write this differently but today i'm just gonna write it this way so yeah i guess actually i guess one minor optimization i usually write it together but i guess i can do it here and also that if um we have to make sure that this is inbound uh so if not this contain you you might have to need a parenthesis because i'm not sure um and then yeah just for symmetry reasons uh do the same thing here and then if uh okay so total zero zero if a board of right right and then return total so this should be and then return total so this should be okay i hope this is okay because okay i hope this is okay because otherwise it's embarrassing but i mean otherwise it's embarrassing but i mean the idea should be okay it's just that the idea should be okay it's just that might have typos and stuff like that might have typos and stuff like that right right uh yeah so that looks good let's give it uh yeah so that looks good let's give it a submit apparently i did it a submit apparently i did it a couple of years ago so that looks good a couple of years ago so that looks good right so this is gonna be linear time right so this is gonna be linear time linear space um because we look at each linear space um because we look at each cell cell uh maybe uh well let's say 10 times from uh maybe uh well let's say 10 times from left up down left right and stuff like left up down left right and stuff like that um that um and yeah and that should be good and yeah and that should be good right like i mean obviously because we right like i mean obviously because we just got accepted so the way to do it in just got accepted so the way to do it in place and i don't i'm not a fan of this place and i don't i'm not a fan of this maybe we can kind of see if there's any maybe we can kind of see if there's any clever way to do it in place um but the clever way to do it in place um but the way that i would do it is just by way that i would do it is just by instead of having this next sport instead of having this next sport um okay let's just say this is so awkward um let's just say we so now you can you know you can think about a binary bit as as you know a number of base two so then we only care about the current board contains one bit and the most uh least significant bit and then one more in the second one and then we can store the next price here and then afterwards move it to the right so that's basically what we're going to do um we just have to make some changes here we would have to i know that you can use a bitwise i know that you can use a bitwise operation here for operation here for those those smartypants so i learned advanced but um smartypants so i learned advanced but um oops almost had a typo there but i oops almost had a typo there but i wanted to make sure that you know wanted to make sure that you know i just want a mod 2 so that is clearer i just want a mod 2 so that is clearer um and here we also want to um and yeah and that should be maybe good for now uh at least this part but here now we have to set up the next board right so yeah let's just say maybe uh next next space is equal to force and then now we can just convert it here um and this is where um i talked about a little bit about don't repeat yourself and stuff like this that's where this could be helpful by that's where this could be helpful by having a few if statements but but having a few if statements but but that's okay we're going for the most direct code so that now uh before we might have what we in something like this right uh and that'll be fine but of course this doesn't exist anymore so what we have to what we want to do is store it in the upper bits right so then here um oh no not that uh is to go to um so yeah we'll be like we'll keep into deemed with being as explicit as possible but uh well yeah so then we add two if this is the case right um and then at the way n um yeah if this divided by two is equal to one if this divided by two is equal to one um again i'm you know just being very um again i'm you know just being very explicit otherwise it's equal to zero explicit otherwise it's equal to zero let's try that again let's try that again uh again like you know you can use uh again like you know you can use bitwise operations i'm trying to be as bitwise operations i'm trying to be as generic as po well not as generic but i generic as po well not as generic but i think as clear as i can to think as clear as i can to maybe possible newcomers and stuff like maybe possible newcomers and stuff like that let's give it a submit that let's give it a submit should be the same a little bit faster should be the same a little bit faster apparently but uh but yeah uh that's apparently but uh but yeah uh that's pretty much all i have again this is pretty much all i have again this is gonna be linear space and linear time i gonna be linear space and linear time i don't know like i said i don't yeah this don't know like i said i don't yeah this is a little bit awkward so but you can is a little bit awkward so but you can do it if you like is my point what did i do it if you like is my point what did i do in the past why is it faster do in the past why is it faster okay i mean i did i guess i did the same okay i mean i did i guess i did the same thing pretty much i didn't want four thing pretty much i didn't want four opens i think the function cost probably opens i think the function cost probably make it slower but not by that much i make it slower but not by that much i don't care but yeah uh that's all i have don't care but yeah uh that's all i have for today for today game of life game of life um yeah stay good stay healthy to good um yeah stay good stay healthy to good mental health i'll see you later and mental health i'll see you later and take care bye | 2024-03-22 14:20:13 | 289 | 289. Game of Life - Day 12/30 Leetcode April Challenge |
|
P8J1W9xB29Y | hey what's up guys this is john here again again so this time let's take a look at 1697 so this time let's take a look at 1697 checking the existence of edge length checking the existence of edge length limited limited path so i mean this is another path so i mean this is another graph problem i think it's it's quite graph problem i think it's it's quite interesting and you're given like a interesting and you're given like a graph of n nodes and graph of n nodes and in the form of an edge at list in the form of an edge at list which is a uv and distance between this which is a uv and distance between this between those uh two nodes and you're also given like an array of queries so the queries is also like a u and v where you can call it p and q right so u and v and then there's the limits so your task is to determine for each of the queries if there is a path between this p and j so the p and q such that there exists that the path on on each that the path on on each i mean the distance on each of the edge i mean the distance on each of the edge is is strictly less than the limit strictly less than the limit and note that there might there may be and note that there might there may be multiple address between two nodes multiple address between two nodes right so that's the uh basically the uh right so that's the uh basically the uh the description the description and here's one examples here so we have and here's one examples here so we have the three nodes here zero one and two the three nodes here zero one and two and we also have four edges and we also have four edges edges here so four eight and edges here so four eight and from one to zero between one 0 there are from one to zero between one 0 there are two edges two edges so one edge has distance 2 and the other so one edge has distance 2 and the other one has 16. that's why we have a one has 16. that's why we have a two values here and then we have a two values here and then we have a we have two queries so the first one is we have two queries so the first one is from zero to one from zero to one so it's asking us to check so so it's asking us to check so from zero to one the path right the path from zero to one the path right the path from zero to one if there is from zero to one if there is if there exists a path from zero to one if there exists a path from zero to one i mean i mean each edge on on on that i mean i mean each edge on on on that path path is the distance is smaller than two is the distance is smaller than two and the answer is false because because and the answer is false because because the smallest the smallest we can get the smallest path from 0 to 1 we can get the smallest path from 0 to 1 is 2. 2 is not strictly smaller than 2. is 2. 2 is not strictly smaller than 2. so that's why we have fours here and so that's why we have fours here and then the second one is the from 0 to 2 then the second one is the from 0 to 2 from 0 to 2. from 0 to 2. if there's if there's a path whose if there's if there's a path whose uh each edge is smaller than five uh each edge is smaller than five and the answer for this one is yes and the answer for this one is yes because we can because we can have two and four that have two and four that so here here's the path okay and yeah so that's the description and here's another examples here right and then the constraints so the constraint is what is the 10 to the power of 5 the other one is 10 to the power of 5 as well and here there might be multiple addresses between two nodes so that's the so the brutal force way the brutal first so the brutal force way the brutal first way to solve this way to solve this problem is you know for each of the problem is you know for each of the queries queries right so for each of the queries we'll right so for each of the queries we'll try to try to you will try to find the the shortest you will try to find the the shortest path path shortest path between this p and b shortest path between this p and b between is p between is p and and the q and the wow and and the q and the wow and basically it's a just like a a and basically it's a just like a a diagonal diagonal that is through a problem uh solution uh that is through a problem uh solution uh we use die crystal we use die crystal to find a path that can give us the to find a path that can give us the minimum minimum the minimum the minimum uh the minimum the minimum uh the minimum distance on each of the edge the minimum distance on each of the edge and if that one is smaller than the and if that one is smaller than the current limits then we know okay so current limits then we know okay so we will return true in this case for we will return true in this case for this query this query but the problem for that is that since but the problem for that is that since we have a pretty big we have a pretty big uh constraints here so for uh constraints here so for for to loop through each of the queries for to loop through each of the queries we need a we need a on time o in time on time o in time and for the deck the dijkstra right so and for the deck the dijkstra right so the dark throws the dark throws complexity is another end of log complexity is another end of log log e if i'm if i'm not mistaken log e if i'm if i'm not mistaken so where n is the number of nodes and e so where n is the number of nodes and e is the number of edge is the number of edge so in total we have o of n so in total we have o of n square of log square of log log n i think yeah since the address log n i think yeah since the address also can be up to also can be up to 10 to the power of five right so 10 to the power of five right so and this will go to e and that's why actually that's why this one is a it's a hard problem right and and we have to find another you know a common solution for a graph you know a common solution for a graph problem problem if we cannot solve it in a traditional if we cannot solve it in a traditional in a regular way is in a regular way is it's a union find because the union it's a union find because the union finds finds so the union find the time complexity so the union find the time complexity for that you know after the for that you know after the the path compression and some rankings the path compression and some rankings we can consider we can consider uh both the union and fine to be o1 time uh both the union and fine to be o1 time complexity and we just need to find the relations and we just need to find the relations between the unified between the unified uh characteristics and uh characteristics and the queries and the answer for each the queries and the answer for each query if you watch this if you read this thing uh more uh several times you might be able to find that you know actually so so when will we return true right and when will when will we if we are um if we are um if we sort the queries if we sort the queries by the limits okay by the limits okay and let's say we have some queries here and let's say we have some queries here we have queries we have queries from p1 to to q1 right and the limit is s2 and then we have another one that's p2 equals to q2 and the limit is five something like this right and then p3 q3 and so for for two here so for for two here right i mean how can we know if this p1 right i mean how can we know if this p1 q1 2 will will return true so q1 2 will will return true so it will return true if like i said if it will return true if like i said if there there there are like some path that that can there are like some path that that can connect connect oh sorry if there are there are some oh sorry if there are there are some edges that can connect this p1 and edges that can connect this p1 and p2 and whose uh whose uh distance right the big the distance is no bigger than two it's actually small it's strictly smaller than than two right and same thing for this p2 and p uh p2 and q2 so if so we return true for this one if there are some edges that can connect that can connect the p2 and q2 right who's like um so if you can find this if you you can so if you can find this if you you can find if you can find if you can make these observations and now i think make these observations and now i think it's more it's more clear that we just for each of the clear that we just for each of the queries here we just need queries here we just need to try to find some address to try to find some address that whose distance is smaller than the that whose distance is smaller than the current limits current limits and it will try to connect we'll try to and it will try to connect we'll try to connect connect these two nodes together and that's the these two nodes together and that's the perfect perfect a perfect candidate by using the union a perfect candidate by using the union find and now we have i think the solutions becomes much clearer so we sort the course by the by the limits from smallest to the biggest so that we can build the uh the graphs the the graphs uh bottom up and then we will also sort the edges the address list from the smallest distance to the biggest and for each of the queries and since we are need we need to make oh we also need to maintain that in the index for each of the queries that's why uh even though we're sorting by this one but we're still going to maintain the the current the original index so that we can use the index to populate the final answer array so basically for each of the queries here from the smallest to biggest i would use this one as the as the parameters and we use it to find the uh the edges whose distance is smaller than this one and then we would try to union those edges and after that we basically we simply check if this p1 and the q1 is connected if it is then we know okay so we there there has to be a a path that can satisf satisfied this condition and then we and then we return true otherwise right and since we are right and since we are like sorting this this like sorting this this uh queries from smallest to biggest so uh queries from smallest to biggest so whenever we have whenever we have unions sum of the edges here we don't unions sum of the edges here we don't have to go back have to go back to do it because you know uh it does we don't really we don't really care right because we we can we can use as many edges as we we want as long as they are smaller than the current limits so that's why we can just try to union everything that's smaller than than this one and then and we can just keep adding the edges and then yep then there you go so we for each of the one we just use the same logic to check and cool so i will start the implementations cool so i will start the implementations here here i think first i'm going to try to create i think first i'm going to try to create templates for the union find templates for the union find right so for those who still don't know right so for those who still don't know the union fine i recommend you to look the union fine i recommend you to look find some other videos find some other videos that can give you a better explanations that can give you a better explanations about the union find about the union find so here i'm only going to do the so here i'm only going to do the implementations implementations so for union find we we need two so for union find we we need two functions functions methods the first one is to find so the methods the first one is to find so the find is find the the root right so find the the root for the for the current group so the way i'm doing this i'm using a path compression all right so here i'm using recursive call first current one and then we do a find parents x right and in the end i return parents x right and in the end i return the uh the uh the parents so that's that because at the parents so that's that because at the beginning you know the beginning you know every note has has it has itself as every note has has it has itself as served uh as the uh as a parent served uh as the uh as a parent and that's why whenever the parent is and that's why whenever the parent is not the number itself not the number itself and then we know okay so this parent has and then we know okay so this parent has this card number has a different this card number has a different has another route that's why we just has another route that's why we just keep looking keep looking up uh while looking up while looking up up uh while looking up while looking up we also we also uh compress the uh doing the the path uh compress the uh doing the the path compression so that's the find and then we have a unit right so the union is this x and y and we just do a r1 equals to find x right and then r2 equals to find of y and then if r1 is not equal to does not equal to r2 and then we do that the u the unit and here i'm i'm not using the the rank the rankings here i'm just using the the sorry i'm just always assigned this r1 the patterns of r1 to r to us patterns of r2 to r1 okay so that's the uh the templates of the the union find and after that let's just try to sort this two list so the first one is the edge right so for the arch we want to sort by the byte by the distance which is the we need to use a lambda function right so we have a x dot x two right so that's the the third element and then uh we also need to sort the the course by the limits while also maintaining the index that's why i'm going to create a new list of queries and so the first one is the limits and then we have a u we have a v and then we have index and i'm going to do a like loop here for u and v and l right in enumerate of the course p-r-i-s so i'm just using uh like a short versions of the for loop here so i'm just i enumerate the queries including the index itself and i just create a new uh tuple word set a tuple right for each of the the query itself so that i can i can just easily sort by the limits now i can just do a sort and i don't even need to specify the lambda functions because by default it will be sorted by by the first element which is the limit that's why i put the limits at the at the first one all right cool so that's that and now we can just uh now we need the answer right so i mean the answer the answer at the beginning everything is is false right and the uh the length is is the length of the curse oh and that's why we need another we need the m here so i'm going to use since we already have n here i'm using m m is the length of the the chorus right yeah so uh that's that and then we have a four uh the limits uh so i would also the limits uh so i would also spell it out so create limit right and spell it out so create limit right and then we have a u then we have a u we have a v and we have i right in the we have a v and we have i right in the queue queue that's that and so yeah and in the end right once we have the our answers we just need to do a answer.i equals to the uh something right either true or false in in the end and then later on in the end we simply return the answer so the way we're doing this is like i said we have to with the current q limits we'll find the uh the valid adjectives that we can use to we can use to do the unit and the way i'm defining is i'm i'm going to introduce another like edge index of equals to zero at the beginning right and then while the edge index is smaller than the uh the size okay i need another one another length which is the i guess i'll just call it uh edge size maybe that's the length of the edge list so while this one is smaller than this and the edge list of the edge index and number two right is smaller than the q limit now since the add list has three elements and the the index two is the distance we're looking for right and since the the edge list is really sorted by this one that's why i can just loop through from the current index and if it is if the current one is smaller the current distance smaller than the limits i can just do the unit right so the unit is a union our union the address list of which is zero and one which is zero and one right so the zero is the the u and the right so the zero is the the u and the one is the v one is the v so i i just union those two and then so i i just union those two and then after that i just increase the index after that i just increase the index by one since this this add by one since this this add has already been uh union so we don't has already been uh union so we don't have to be have to be we don't have to use it anymore that's we don't have to use it anymore that's why we can just why we can just keep moving the edge index forward cool so and once once this while loop is finished we have uh used all the the valid address we can use to try to connect the current uh queries right and then we can simply check you assign this answers with the find of u equals to find of v so what this one does is basically this is the way we're checking if this the u and v has been connected or you know in another word if the u and v belongs belongs to the same same group right so finally you find u and find v same group here right and then we can same group here right and then we can just we can use the uh we can just uh return true because we know okay so we have already yep i believe that's it yep i believe that's it so let me run the code oops sorry so let me run the code oops sorry invited invited syntax oh no it should be a queries oh yeah queries oh yeah q e r i e s q e r i e s chris okay and okay so it's a it's successful yeah so that's it and so for the time complexity right so you know like i said so the union and the fine we're treating is like a one here so we can just ignore these two parts and so so the most significant uh complexity is this two sortings which is are both unlocked and right because both the address and the queries can be uh up to n length that's why the uh and then here we have a so we have unlock n here here's like but for but here you know since the uh but for but here you know since the uh oh even though we have a while loop here oh even though we have a while loop here but you know but you know we're only going to use the each edge we're only going to use the each edge once once that's why idea so here we're only we're that's why idea so here we're only we're we can also consider we can also consider like like o one right and like like o one right and and then the defined and union are also and then the defined and union are also one one so in total i mean it's a so in total i mean it's a it's a old log it's an unlock and it's a old log it's an unlock and solution for this yeah i guess that's it for this one i think this one is it's very it's very interesting unified solutions and so the the observation you have to be able to make is how can you come how can you con relate or how can you connect the the the answer for each queries with uh some union find uh algorithm and in this case uh it just happens to be uh i mean you just have to uh write it down or and then try to analyze so what does the true mean for each of the queries and so for this one it means that and with this kind of limits can we find some edges that can connect p and j together so that's the that's the definite that's the meaning of the of true for the queries and if you after that i think it shouldn't be that too hard to find a sorting and also this wow this like index thing so you can solve this problem into a log and and yeah i think that's it for and yeah i think that's it for today i guess and thank you so much today i guess and thank you so much for you guys to watch my video and stay for you guys to watch my video and stay tuned tuned see you guys soon bye | 2024-03-20 14:32:53 | 1,697 | LeetCode 1697. Checking Existence of Edge Length Limited Paths |
|
xTdkTJgFa18 | Hello everyone, welcome to D channel, in today's video we are going to solve video we are going to solve problem number 383, whose name is Rasom Knot, problem number 383, whose name is Rasom Knot, which is one of the problems in lead code. This problem is also featured in the list of Challenge for new users, so it is a good one for business. is also featured in the list of Challenge for new users, so it is a good one for business. is also featured in the list of Challenge for new users, so it is a good one for business. is a good exercise then let's solve this question without any delay. Best so what is the question? First of all we so what is the question? First of all we read what is written in it. Given you read what is written in it. Given you string note and magazine return true can be string note and magazine return true can be constructed by using D latest constructed by using D latest from D. from D. from D. letter it in magazine can only be used onesome note Okay so here we will get two strings tension note and magazine magazine whatever letters are there we have to see if the letters of the magazine note can only be used onesome note Let's understand it with an example. There is a letter A in the note and letter B in the magazine. The letter in the magazine is B. We cannot construct A by using B, hence the output falls here. In the example, the letter in Rasan Note is In the example, the letter in Rasan Note is In the example, the letter in Rasan Note is double A and in Magazine the letter is A & B. double A and in Magazine the letter is A & B. So here because we cannot construct the use of one letter, So here because we cannot construct the use of one letter, I have used the latest of Magazine. I have written here I have used the latest of Magazine. I have written here and in Magazine there is so this condition is so this condition is so this condition is then here we have already given the function can construct. If we have to return true or false, then in order to understand, let us Construct OK Construct OK [Music] From the letter, so let us understand the problem a little. Hain I may have given us some letters using the latest of Song Magazine, Han Magazine Main has given here di to di to become sakya ok di to a gaya tension note ka but now we This di cannot be used with any other character which is not a letter. We have to replace it with some other character other than the letter so that when we check it again for the second number, The The The second letter we will give is K, then if we second letter we will give is K, then if we search for K then KV will be here, so we remove K also, the last letter is H, if it is not there then H will not be formed. Okay, if this letter is not present in it, this letter is not present in it, then we will get the then we will get the value of construct here. i.e. if it is i.e. if it is not there not there then there is no need to check it further because if one letter is not formed no need to check it further because if one letter is not formed then the rest of the letters have no meaning because then the rest of the letters have no meaning because tension note cannot be formed now, it cannot be formed tension note cannot be formed now, it cannot be formed It will happen as long as the letters are It will happen as long as the letters are It will happen as long as the letters are continuously found inside this magazine string, that is, the value of our construct is true, what is found will [music] I will again check for the letter I will again check for the letter in the magazine that that letter is in the magazine that that letter is present in the magazine. present in the magazine. present in the magazine. message, so I am check that the Now if this condition is true then I have to calculate the Now if this condition is true then I have to calculate the value of the construct. I have to calculate the Is true i.e. it Is true i.e. it Is true i.e. it can be constructed, if can be constructed, if not then we have to check whether the value of the construct is not present even after checking all the latest of the magazine, it means that we So here I will write So here I will write So here I will write if give give break de loop and here I have to return construct is construct is ok, before this do camera, I will replace the letter with some other character replace it. replace it. replace it. I can break the loop Run Time Fast End [Music] 72.69% Like the Video and Like the Video and Share with Your Friends I'll See You Share with Your Friends I'll See You in the Next Video Keep Learning Keep Going Keep in the Next Video Keep Learning Keep Going Keep Educating Educating Educating | 2024-03-24 11:57:26 | 383 | Ransom Note Solution Explained (LeetCode 383) - C++ |
|
Ok0jYAMnvQI | hey everybody this is Larry I'm doing this problem as part of a contest so this problem as part of a contest so you're gonna watch me live as I go you're gonna watch me live as I go through my darts I'm coding they've been through my darts I'm coding they've been explanation near the end and for more explanation near the end and for more context they'll be a link below on this context they'll be a link below on this actual screencast of the contest how did actual screencast of the contest how did you do let me know you do hit the like you do let me know you do hit the like button either subscribe button and here button either subscribe button and here we go cute were people whose list of favorite companies it's not a subset of another list yeah so this one I think I just was trying to well one was I just want to make sure what they meant by subset I mean I know that some set has a definitive meaning but I feel like it in recent days lead code new codes definitions were an exact so so I just want to make sure and it's not even just equal sometimes different problem centers will have different definitions and and by dad and because subset for a list means something else and here it turns out that it means the proper subset I believe where every item is inside other item or another word maybe even dominated that you can use maybe but in either case I looked at an N is to go to a hundred their 500 company sounds like I'm the nose so right now I'm gonna start implementing the blue force but which is N squared times the number of companies L so N squared times L was always you go to the biggest lists of companies or something like that and that's pretty much what I do I did have a little bit worried with respect to the running time but uh but yeah and I also converted here I was like just double-checking some stuff I was like oh yeah I think at some point pretty soon I converted it from a list I was going to use sorting and a binary search or something like that but I was like okay actually just just convert it to his set yeah so I can wear it to a set which yeah so I can wear it to a set which allows me to do quicker lookups and then allows me to do quicker lookups and then after that I just do a proof for us I after that I just do a proof for us I just wanted to make sure that this works just wanted to make sure that this works that I can create a set that way while I that I can create a set that way while I continue to type so that even look at it continue to type so that even look at it later now I think there was a compile it later now I think there was a compile it just tells me there's a compiler like just tells me there's a compiler like because I have the type one companies because I have the type one companies because I do look at it later and I go because I do look at it later and I go yeah that's fine thanks and now we're yeah that's fine thanks and now we're like okay is not equal to j then we want like okay is not equal to j then we want to check whether the person is strictly to check whether the person is strictly person I see list of companies is person I see list of companies is strictly inside person J's company and I strictly inside person J's company and I was like okay I spent I end up spending was like okay I spent I end up spending about five minutes on this farm my about five minutes on this farm my plight could have should have done it plight could have should have done it faster but oh yeah that's pretty much what I'm implementing you know I never looking back it seems like I'm really slow but for some reason because I think I was still very so doing this time I didn't know if I was thinking like it do I need an optimization and I think near this time I was like okay if I need an optimization I'll just do it later like I would take a risk on a five-minute penalty because sometimes it is what it is if it doesn't tell me stuff that if every item is found and we want to set far as you go to true and also I did a little bit of a micro optimization so I don't know why I voted this way I think I was just washing a little bit mentally instead of just waiting quick Chris that's nice entry what it does but yeah but now it's saying now if if we don't find a case where someone totally likes all your companies and more we added to in a way that is the result and we just couldn't earn the I yeah that's pretty much it I when I don't know submit even though I probably could have tested the stress tested a little bit more that's cute Bowie people whose list of favorite companies is not exceptional but not less so I've like could have done this one faster but I think I just wasn't sure if a man like Bob was upset and I was it was it I don't I was a little bit skeptical about this one in terms of running time so basically what I did was proof for us it's n square and then for I is not yeah yeah so for n square you for every I you compare it to a J and then see if everything in I is in J or not in J well we've there's a one case where yeah if I if all of I is in all of J then then that means that I gets dominated yep otherwise if you cannot find it instant that's the case then we add to index I was I I actually had a little bit I was a little bit scared about the running time but I think I miss better constrains now that no there's 500 companies right yeah so I you said to make the lookups easier [Music] but but yeah although I did proof force and Q or N squared times L for Elvis to number of companies so so I definitely wasn't confident about this one in terms of wedding time I was thinking about maybe I have to end at the way least can convert from string to like an inch or something like that but it worked okay so maybe the test case week but I'm not sure because I do have some early termination but it's still not yeah after actually break on here I don't know why I didn't break on here either but yeah oh boy I mean this is just | 2024-03-21 02:44:30 | 1,452 | 1452. People Whose List of Favorite Companies Is Not a Subset of Another List (Leetcode Medium) |
|
BS3ce52jU8I | Hello Hello Everyone Welcome to Difficult Channel Subscribe To A Situation Has Done Game Liquid 174 Is Hotspot Of Birth And Its Very Interesting Problem Problem Must Subscribe Must Subscribe School School Width Minimum Amount Power S Key Settings Operation Electronic Example Dheer Vo Grade - - - - to subscribe name list 174 Pomegranate for this they celebrated the birth anniversary of Mahatma notification electra n f and and important pastries the power of and important pastries the power of united in itself was beyond and Video united in itself was beyond and Video then to subscribe our 200 Just Remember This Point Which Will Help Us A Lot In Coming Up With Android App The Lips Reduce Problem To Various Subscribe School Subscribe Our Subscribe subscribe to [Music] subscribe our K switch off K switch off K switch off minus to Subscribe Subscribe Subscribe Our Robert Mix It Aur Tulsi 12345 A Plus Movement In One Side Reaction And A Plus Movement In One Side Reaction And Nights To Give Way To Power At The Center Nights To Give Way To Power At The Center Subscribe Button Point When there is skin problem the lessons you learn light settings mist power servi to subscribe our 204 equal to band se minimum power eight subscribe subscribe for - 121 for - 121 a piya to more rhythmic 12182 in power minus a piya to more rhythmic 12182 in power minus plus to make attractive one and how much plus to make attractive one and how much not do not do subscribe I hope you understand all these taste that you 100 gram paneer that you 100 gram paneer version am trying to bed DPR 1005 version am trying to bed DPR 1005 minimum amount of power The Video then subscribe to the Page that and have increased the time in both Amit And All The Three Do Subscribe That That Androided For 20 Serving Slide 214 Using Androided For 20 Serving Slide 214 Using Arduino Code That Makes Sharp Arduino Code That Makes Sharp Difficult Difficult Subscribe My Channel [ Subscribe To Member This point is well because it is difficult computed while going from Directions from one of the Thursday Thursday Subscribe Apart from School College Died On Tel Half - 5 Minutes Of Power The Apart from School College Died On Tel Half - 5 Minutes Of Power The Means Of Much Power Deficit Which Gives The Night At This Means Of Much Power Deficit Which Gives The Night At This Point And Then Point And Then One Plus Subscribe To Are In A Big Question That Power Tariff In Greater Than or Equal to One 100 subscribe this that from Naav Lips Fielder Se Control and that from Naav Lips Fielder Se Control and Getting from Extreme Right Volume Getting from Extreme Right Volume Withdraw from Difficulties and 430 subscribe Video subscribe to that from five minutes of power bank that from five minutes of power bank account se FD account se FD account se FD sirf Video give subscribe subscribe and and subscribe the subscribe the that 510 great leap years this period total power that 510 great leap years this period total power subscribe 919 subscribe and artificial night yes benefits of rights took place me knowledge compute dress power need for this particular entry and the volume - stand For student in five minutes of power in this particular direction so much power should give water cooler that December - 5 - 151 - - 05 200 minimum of fifteen units of power after becoming to the night and from this particular to left moving in this particular direction Plate computers for the direction that here a place zoom the night is moving destroy i want minimum one enough power to maintain for this is the means off subscribe this moving crowd yielded at this i one minus minus 10 current affairs - one minus minus 10 current affairs - 10th class 11th hai 10th class 11th hai to to Is this night is moving in this particular direction Is this night is moving in this particular direction Hasp Our Video Night Will Have Enough Power Hotspot Regular Unit Dhundh I Let Continuous Next Idiom Is I Let Continuous Next Idiom Is a Big Salute This Political Social and Components a Big Salute This Political Social and Components - Five - Five Salute For This Point Se Left You To Cash Subscribe Yo Yo 1992 Sub - 5 A Pick From 16th Is This Night Is Movie In This Particular Direction How Much Power Window Is One - Pickup Sex On 8 - 22nd Either to give this might seem enough Either to give this might seem enough Either to give this might seem enough power and power and 16513 16513 subscribe to 6 subscribe to 6 a plate central police have rich a plate central police have rich vibrations vibrations subscribe from within dubai settings for this particular sale wishes for power and suddenly coming from subscribe to this means That Will Give A Minimum Of Two That Will Give A Minimum Of Two That Will Give A Minimum Of Two Years Before Death Sentence Him Zoom Years Before Death Sentence Him Zoom Standing At This Particular Standing At This Particular Political Political Leaders Like Subscribe For More Subscribe For More Video Subscribe - - - - Play List Vasool Decade Ke Liye Tumor Moving Play List Vasool Decade Ke Liye Tumor Moving From From A Half Cell Towards The Lower End Its - A Half Cell Towards The Lower End Its - Android Android Android subscribe this Video not support to a day or two options available a day or two options available here they can do in this particular direction here they can do in this particular direction and twenty minutes of power and and twenty minutes of power and banking Govind spot production and give banking Govind spot production and give five minutes of power which is very much liked so subscribe my channel to Speed Come in Slightly's Season's to Speed Come in Slightly's Season's Final Decision Salary Flu White Point Final Decision Salary Flu White Point Solution Festival Ki Solution Festival Ki A 247 Liquid - To Do Must Subscribe A 247 Liquid - To Do Must Subscribe Tubelight and To-Do List During Tubelight and To-Do List During Five Eight Tips Field Friend Pass 1.5 Inch to Channel - - 2 - - 2 The President The President The Fear Of Going Towards Right Bank The Fear Of Going Towards Right Bank Address Political Rally Minimum Us Emphasize Address Political Rally Minimum Us Emphasize Power This Matter Power This Matter By Into Broad Gauge By Into Broad Gauge And Power Loom Celebs By Subscribing Subscribing Nav Vihg Complete Fielding And Nav Vihg Complete Fielding And That A Dimple The Power Volume Un Davidson That A Dimple The Power Volume Un Davidson Confusion Left Don't Worry Everything With Confusion Left Don't Worry Everything With Little Clear In The Solar System Points Little Clear In The Solar System Points 158 Next Point To Variables Eminem For Calculating Rule And Columns Of Subscribe Loot Indiscriminate Harvesting Strong Plus One In Recent subscribe and and subscribe the Channel Please subscribe subscribe subscribe this hai adarwise loot lo daily requested video ki adarwise also sign board and air disorder computer from this equation and considered enough now live school on school on Thursday that and within ther power minimum one minute but please this is particular in recent years of | 2024-03-21 14:10:28 | 174 | Dungeon Game | Leetcode 174 | Live coding session 🔥🔥🔥 |
|
X-kwLgPQO4g | hi everyone once again welcome to my channel and today again we are solving channel and today again we are solving another problem from lit code top another problem from lit code top interview question list and the problem interview question list and the problem is reverse integer so i always recommend is reverse integer so i always recommend everyone to solve the top interview everyone to solve the top interview question list first if you are preparing question list first if you are preparing for interviews so that list has almost for interviews so that list has almost around 146 around 146 problems and i have published around 90 problems and i have published around 90 problem video solution and created a problem video solution and created a dedicated playlist for that you can dedicated playlist for that you can check out and try to solve as many as check out and try to solve as many as possible because these all problem will possible because these all problem will cover all the data structures basic cover all the data structures basic concept and idea once you have know the concept and idea once you have know the basic concept and able to solve these basic concept and able to solve these problems then you can solve any problem problems then you can solve any problem by practice and practice so the let's by practice and practice so the let's focus on this problem so in this problem focus on this problem so in this problem we are given a 32-bit integer we are given a 32-bit integer x and we need to return x and we need to return its digits reverse so we need to reverse its digits reverse so we need to reverse its digits if reversing s causes the its digits if reversing s causes the value to go outside the sine 32 bit value to go outside the sine 32 bit integer range integer range like this is the range of sine 32 bit like this is the range of sine 32 bit minus 2 power 31 to 2 power 31 minus 1 minus 2 power 31 to 2 power 31 minus 1 then we need to return in case of over then we need to return in case of over or under flow or under flow and assume that the environ does not and assume that the environ does not allow you to store 62 4-bit integer sign allow you to store 62 4-bit integer sign or unsigned so this is very important or unsigned so this is very important constraint because of this constraint constraint because of this constraint this problem is little tricky though this problem is little tricky though this problem is marked as a easy inlet this problem is marked as a easy inlet code while i can say it's not that easy code while i can say it's not that easy if with this constraint so how to solve if with this constraint so how to solve this kind of problem so let's see the this kind of problem so let's see the example here it is given x is 1 2 3 and example here it is given x is 1 2 3 and we need to reverse is 3 to 1 so how to we need to reverse is 3 to 1 so how to solve this problem so this problem can solve this problem so this problem can be reversed like integer can also be be reversed like integer can also be reversed in same way as that the string reversed in same way as that the string we do reverse while we need to we do reverse while we need to find out the like significant disease so find out the like significant disease so for this example in 1 2 3 so first we for this example in 1 2 3 so first we need to reverse it so for reversing we need to reverse it so for reversing we need to know what is the last digit in need to know what is the last digit in this so how to find the last digit of a this so how to find the last digit of a number so for finding the last most number so for finding the last most digit of a number we do modulo y 10 so digit of a number we do modulo y 10 so once we do modulo by 10 we will get 3 as once we do modulo by 10 we will get 3 as the last digits the last digits from this 3 so the we will also from this 3 so the we will also initialize our reverse integer that is initialize our reverse integer that is from 0 and once we get the digit the from 0 and once we get the digit the last digit what we will do we will take last digit what we will do we will take reverse multiplied by 10 plus the digit reverse multiplied by 10 plus the digit we got from the modulo so this is 3 so we got from the modulo so this is 3 so this reverse now it become 3 this reverse now it become 3 now now once we got this digit does it matter in once we got this digit does it matter in other further cases no so we need to other further cases no so we need to just forget out so for that what we need just forget out so for that what we need to do we need to basically trim this to do we need to basically trim this last mode this is as we already use in last mode this is as we already use in our river so for removing the last mode our river so for removing the last mode digit what we do we will take 1 2 3 and digit what we do we will take 1 2 3 and divide it by 10 and this division we divide it by 10 and this division we will do integral division so in python will do integral division so in python you need to use the double slice that you need to use the double slice that will gives you integral so once we do will gives you integral so once we do this we will get over here 12 so once we this we will get over here 12 so once we got so now our reverse is 3 at this got so now our reverse is 3 at this stage and number is left 12 so we will stage and number is left 12 so we will apply the same steps again in 12 so this apply the same steps again in 12 so this will become 3 into 10 plus 2 so 2 we get will become 3 into 10 plus 2 so 2 we get from by modding 12 mod 10 we will get from by modding 12 mod 10 we will get the 2. so this is what this number the 2. so this is what this number reverse will become over here 32 and reverse will become over here 32 and after dividing 12 by 10 this will become after dividing 12 by 10 this will become 1 then we will again repeat the same 1 then we will again repeat the same step and finally we will get 3 2 1 as step and finally we will get 3 2 1 as the reverse which is answer over here so the reverse which is answer over here so this is how we can solve this is how we can solve and reverse the number and reverse the number but but we need to take care the special cases we need to take care the special cases the special case when we are reversing the special case when we are reversing and our integer crossing the into max so and our integer crossing the into max so i have written down over here these i have written down over here these values of 2 power 31 and 2 power 31 values of 2 power 31 and 2 power 31 minus 1. so the min value and the max minus 1. so the min value and the max value of integer value of integer so so for example let's say we got let's take for example let's say we got let's take this this first positive side part if we got a first positive side part if we got a number something like 7 4 6 number something like 7 4 6 3 3 7 4 6 3 7 4 6 3 and then 8 4 7 4 1 2 and then 8 4 7 4 1 2 so this kind of number if we got so if so this kind of number if we got so if we try to reverse it this reverse will we try to reverse it this reverse will work too that is fine then 1 then 4 then work too that is fine then 1 then 4 then 7 then 7 then 4 then 8 then 3 then 6 then 4 then 8 then 3 then 6 then 4 but at this point if we take this 4 but at this point if we take this so far it is fine as this number is ah so far it is fine as this number is ah in the range is still in the range so we in the range is still in the range so we can return the reverse easy but what if can return the reverse easy but what if this number something else like more this number something else like more than 7 if it is 8 let's say let me than 7 if it is 8 let's say let me change the pan here so if it is 8 change the pan here so if it is 8 then if we try to put over here 8 that then if we try to put over here 8 that is this whole number is this whole number y including 8 is greater than y including 8 is greater than is greater than is greater than or equals to the river integer max so or equals to the river integer max so into max it greater than equals to into into max it greater than equals to into max that is the case which this is max that is the case which this is getting overflow so how to find this getting overflow so how to find this kind of number kind of number so before that like when we are so before that like when we are taking this like multiplying so as so taking this like multiplying so as so far till this place so let me change far till this place so let me change again panning here again panning here so till this place till this place we so till this place till this place we are okay this is our reverse so far now are okay this is our reverse so far now when we are adding another digit so this when we are adding another digit so this is the another digit so when we are is the another digit so when we are adding another disease first we are adding another disease first we are multiplying by 10 so with this 10 we multiplying by 10 so with this 10 we need to check if it is not crossing if need to check if it is not crossing if it is crossing by multiplying 10 that it is crossing by multiplying 10 that means it is overflow so we will check if means it is overflow so we will check if our reverse is greater than our reverse is greater than into max so let me just write as max into max so let me just write as max value by 10 if it is that means it is value by 10 if it is that means it is overflow case so we will straightforward overflow case so we will straightforward return 0 another case reverse can be return 0 another case reverse can be equals to this max equals to this max y 10 in that case we also need to check y 10 in that case we also need to check the digit the digit we got by the 10 the digit the digit we got by the 10 modulo if it is greater than modulo if it is greater than max max mod 10 the last digit in our max value mod 10 the last digit in our max value so mod time if it is greater than it is so mod time if it is greater than it is also a case of overflow we will return 0 also a case of overflow we will return 0 here same we will apply for the here same we will apply for the negative part so negative part what we negative part so negative part what we will do if reverse will do if reverse is greater than if reverse is greater is greater than if reverse is greater than the than the ah ah if reverse is greater than min min by 10 that is fine we will return 0 and if reverse is great if reverse is equals to mean by 10 then we need to compare digit if digit is greater than the min y mean modulo 10 if it is the case then again it is a under flow case so we will return over 0 in this case so this is the or condition so this is the idea you can try to pause the video and try to implement the code by yourself first if you can able to because every step i already covered so here the coding part you can see so basically yeah in ah maximum like into minimum value we need to compare left i think my bad i x compared with the greater than instead of greater it will be less than as we are getting sign so this is the case so here this is the code so we declared first reverse variable then we are iterating until our x is not zero then we first got the digit the last modes digit in x by taking modulo with 10 and then remove trim that digit by dividing by 10 once we got the digit we will check if current reverse is greater than into like max y 10 or if equal and the digit is greater than modulo value 10 then we will return straight forward 0 this is the crossing the into max and this is the left side of the into minimum otherwise we will update our reverse y with the current digit like previous value into 10 plus the current digit once we done at the end we will return the reverse is the reverse of x so let's try to compile i have already written few test cases let me create the negative test case boundary as well so let mark it as 9 and it is negative so let us run first this code at this code already i tested so it will work definitely so there is a is not a valid type of integer so yeah i am giving the wrong integer as it this is not possible so instead of this i should give the reverse of let me make it 1 over here and take something 7 here i guess so let's see if it work otherwise we will remove the test case ah yeah that's like is not valid integer it is already overflowing as we can only pass the 32 bit 30 integer values for x so let's try to compile again the negative part is also crossing so let us remove this extra test cases better to do with the default test cases first and you can see it's getting compiled for all the test cases let's try to submit the code and this got accepted let me show you the submission so it got accepted with the 100 percent acceptance rate so that's it so the time complexity of this solution as you can see say the number of digit in x that is for example it is constant actually so the maximum there can be a 10 digit in 32 bit uh signed number so the time complexity of the solution of one and space complexity is also over one so if you like this solution hit the like button and subscribe to my channel and also try to do solve other problem from top interview question list that is very important when you if you are preparing for your upcoming interviews thanks for | 2024-03-18 11:52:43 | 7 | Reverse Integer | LeetCode 7 | Top Interview | Facebook Google Apple Amazon |
|
l4Vgncyezd4 | Soon [Music] A A Ho to [Music] A A Ho to Ajay, you all are doing great, my name is Yatha Batra and today we will clear the simple simple question and the name of this question is Intersection of Two Years so as you Yes, this is a recent Yes, this is a recent Yes, this is a recent question of 359 intersection of toe question of 359 intersection of toe that if this question is latest then it is ok, I that if this question is latest then it is ok, I will follow it by asking a simple question which is called will follow it by asking a simple question which is called And Not Done, I could have used order from you here also And Not Done, I could have used order from you here also but in other hotels, so use it. but in other hotels, so use it. but in other hotels, so use it. doing this because according to Kareena, door or frustration does not become explosive, I get the reference from a little inverter, it is my own mood, so you can do it for anyone, make me also in the mood that I am an undertaker, We will have to We will have to make a map by one Saxena, we will have to make a map on our right, we will have to make an unmute map, so here you can see that I am famous, this is the dress and input, when you ask this question, the plate will not be taken for coffee, it will be And by inputting this hair fall, And by inputting this hair fall, And by inputting this hair fall, all these less auction of clans game are all these less auction of clans game are in that person's burial, so in that person's burial, so first of all, we will need you, the most important is that first of all, we will need you, the most important is that we will have to make each and every point and one, we will have to we will have to make each and every point and one, we will have to make a castle, okay so make a castle, okay so make a castle, okay so and always make and award that illegal chilli spelling is a little, here you have to give in unwanted that you statement plate, then you will definitely have to give its data is mixed and that you give the So the So the So the proof, I keep its name, I keep the hash, proof, I keep its name, I keep the hash, you can keep anything, you can keep anything, working in 10 bracelets from, working in 10 bracelets from, create a person from which I have create a person from which I have countless sitting in this function, so in this function, the countless sitting in this function, so in this function, the return we give you is tight, it is better. return we give you is tight, it is better. return we give you is tight, it is better. therefore die and food will have to make a doctor ignorance is time n template so here you have to give in and I fry it output we are getting sugar cleared that we have so far we just And we have And we have And we have given it to you, now the logic has come to the fore, it is known that the given it to you, now the logic has come to the fore, it is known that the first number one is cashew nuts, so whatever you say to first number one is cashew nuts, so whatever you say to him, him, we will put all your performance we will put all your performance in our opinion and in our opinion and along with it, we will also put his work so that we along with it, we will also put his work so that we Whenever we dross the setting Reddy, then Whenever we dross the setting Reddy, then Agneepath comment of making electronic is Agneepath comment of making electronic is not zero then when should I print it, if neither is zero then let's get it done not zero then when should I print it, if neither is zero then let's get it done ok then next fast ok then next fast approaching then I said today we will see then approaching then I said today we will see then Prabhat Singh two hosts first think this Prabhat Singh two hosts first think this tractor hermitage tractor hermitage tractor hermitage ringtone a wick in the arid zone use officer okay swar me tangari to sort we can also take a simple step loop control usually gives our one some more specific functions usually here democracy We We We don't even have prostate people in this class, so I will don't even have prostate people in this class, so I will put the clip on the maximum. Agreed, there the put the clip on the maximum. Agreed, there the modes and lums are this. This person's name is modes and lums are this. This person's name is Akshay's. Like, if I press it at home, there is Akshay's. Like, if I press it at home, there is a service and function in it which is a service and function in it which is Most of that we are the provider with you Most of that we are the provider with you so this is what we did now all this is good if so this is what we did now all this is good if I explained it to you in the video don't think this is I explained it to you in the video don't think this is straight appointed we are the loved one straight appointed we are the loved one and here we are taking care of our fine and and here we are taking care of our fine and now let us increment it means genuine now let us increment it means genuine Treatment Ghrit Incremented that the understanding is that if there is Treatment Ghrit Incremented that the understanding is that if there is no element in the map, then no element in the map, then first of all we come up with one and because first of all we come up with one and because what happens in the gap in tomato is that if we do what happens in the gap in tomato is that if we do not have the element printed then it is not have the element printed then it is decided and with it the person who decided and with it the person who decided and with it the person who her dowry comes, then you can see that if any element is going out first, then in the meeting held to investigate it, that feeling has been done in these comments, now the work will go after that, so in the episode, we will talk about our It is important that in it It is important that in it It is important that in it we can store the current of elements in our cities, we can store the current of elements in our cities, how many times this element has appeared in this array, later we will see its time complexity later we will see its time complexity proof, because we are a proof, because we are a Shaktiman, we are very powerful, so name school Shaktiman, we are very powerful, so name school options and options and options and help face of I Plus Plus is clear that we are the setting and network families. If this laziness of ours is there, then hello, I am here, okay, equal equal means elastic qualities are due, then it should be a gimmick, there is that I should do something about this enrollment, I should do something about this enrollment, I should do something about this enrollment, now the doctor has told you that it has a function, now the doctor has told you that it has a function, till the ask, it works like a daughter inside till the ask, it works like a daughter inside and if there is a fog in the food hotspot of the patient, and if there is a fog in the food hotspot of the patient, then we can see it like this, its name is then we can see it like this, its name is now now hello hello very good, here we have given you a better As I have discussed earlier also As I have discussed earlier also that Jaisalmer gets the element and we will make that Jaisalmer gets the element and we will make it command zero, Fakir should it command zero, Fakir should not be printed again and then it does not be printed again and then it does not come in our output tractor, so here we can say this not come in our output tractor, so here we can say this and in this and in this and in this click values equal to Shiva, okay friend, I would like you to ask the element in person, whose law is not this, initially like he asked an element, his 5th and took water, our own I must have removed it and now we will I must have removed it and now we will I must have removed it and now we will return it Fennel that everything should run fine 34 return it Fennel that everything should run fine 34 and I have not made any mistake so let's see so and I have not made any mistake so let's see so first let's run this cord so here we have named it line 0 so here we have named it line 0 Almost this was the top, man, Almost this was the top, man, okay, you will quote the run of it, the anniversary updates are 198, its for millisecond, let's submit it, so it is like I have to submit the calories but the expenditure, so then it got submitted and I am sure Implementation is done, I have Implementation is done, I have Implementation is done, I have understood that how we understood that how we can do it, there are many methods on this, can do it, there are many methods on this, you can do it 2.4 Myth TV, in that first of all you can do it 2.4 Myth TV, in that first of all you will have to do shopping, then why do you will have to do shopping, then why do you have to use pointer method, you you have to use pointer method, you can use it from side also in that can use it from side also in that can use it from side also in that make two sets, you have to get only the unique elements printed here, okay, or you can do it with smell, I have taken the specific one only, now you can do it with water also, Yudhishthir, is it clear to you? Om Om, this is Swapn abhi problem Swapn abhi problem Swapn abhi problem meet me coffee with you like this video meet me coffee with you like this video if you have learned something from this then please if you have learned something from this then please support me work bangla film video and support me work bangla film video and sharing and subscribe my channel vikas sharing and subscribe my channel vikas in such problems shampoo hair for weeks in such problems shampoo hair for weeks that you have to alarm quality interview that you have to alarm quality interview for relation for relation for relation in data structure of its problems or you want to spend money in quantity programming time 10 subscribe my channel that a little while videos and updates thank you so much | 2024-03-24 11:14:06 | 349 | Intersection of two Arrays Explained | LeetCode-349 Problem | Coding with Yathaarth |
|
93oRB1eawiA | hey how are you doing guys it's hilah bella here i recording stuff on hilah bella here i recording stuff on youtube chat description for all my youtube chat description for all my information i do all information i do all liquor problems uh make sure you liquor problems uh make sure you subscribe to the channel give me a big subscribe to the channel give me a big thumbs up to support it and this thumbs up to support it and this is called complex number multiplication is called complex number multiplication um given two strings representing two um given two strings representing two complex numbers complex numbers uh you need to return a string uh you need to return a string representing their multiplication note representing their multiplication note the base i raised to the power of 2 is the base i raised to the power of 2 is equal to -1 equal to -1 according to the definition let's look according to the definition let's look at this example at this example we can see that there are two real we can see that there are two real numbers numbers and uh the imaginary and uh the imaginary unit which is uh the imaginary number unit which is uh the imaginary number uh is the solution uh is the solution to to [Music] a quadratic equation right so we return this output you can see these steps right here you convert it to the form of 0 plus 2 i here uh it's the same the input strings will not have extra playing uh the input strings will be given in the form of a plus bi where the integer a and b will both belong to the range of minus 100 100 and the output should be also well um there is a formula um well um there is a formula um a plus b i a plus b i multiplied by uh c multiplied by uh c plus d i is equal to plus d i is equal to ac minus uh ac minus uh b d uh b d uh multiply not multiply plus multiply not multiply plus uh a d plus uh a d plus uh b c uh b c and multiplied by i and multiplied by i yeah um let's say yeah um let's say we got a b c d we got a b c d indices 0 1 2 and 3. uh go ahead all you need is a an array of the type integer then we create a stream of uh their concatenation this both these two strings a plus b ah dot split at you know two backslashes at you know two backslashes and we say uh and we say uh plus or i plus or i you could notice from the description you could notice from the description this problem this problem right here right then um after after that you should call map to integer in order to get uh this value in initial representation uh you use this method reference integer parse integer and you say to array together to put that to add that to add those uh parts to that array yeah um finally you return array at zero which is a right you need to look at this part right here ac minus bd plus ad plus bc uh multiplied by i at you know we can see well we'll look at a which is a which is at zero so array at zero multiply by array at c which is two array at array at b which is 1 multiplied by b which is 1 multiplied by array uh array uh b d d which is three b d d which is three right and plus um you could also notice that from the description of this problem right uh the first real number then the plus then the second real number and i that what we are doing here plus uh the second real number which is uh array at zero uh multiply by d which is array at three uh plus array at [Music] one multiply by array air c which is true and you need to add you need to add i at the end yeah and we can yeah seems good let's run this code there we go success um there we go success um yeah thank you guys for watching leave yeah thank you guys for watching leave your comments below i want to know what your comments below i want to know what you think you think follow me on social medias follow me on follow me on social medias follow me on instagram add me on snapchat uh instagram add me on snapchat uh give me big thumbs up to support my give me big thumbs up to support my channel channel uh as i said before uh as i said before uh leave your comments below if you need uh leave your comments below if you need some help right any help you need just some help right any help you need just leave your comments below leave your comments below or just contact me directly and or just contact me directly and uh i'll see you next time uh i'll see you next time thank you bye | 2024-03-20 10:27:59 | 537 | LeetCode 537. Complex Number Multiplication Solution Explained - Java |
|
B5y7giz9I24 | hello hello hello hi guys good morning welcome back to a new video in this welcome back to a new video in this video Problem path Crossing and the video Problem path Crossing and the special part in this video is how to special part in this video is how to optimize the complexity without changing optimize the complexity without changing anything but only changing the data anything but only changing the data structure we will see this kind of structure we will see this kind of problem uh it has been asked by Amazon problem uh it has been asked by Amazon in the last one two years and it just in the last one two years and it just says that uh we have a string path which says that uh we have a string path which says that I my path of he can be north says that I my path of he can be north south east west and each like each of south east west and each like each of this character represent moving one unit this character represent moving one unit one unit in that specific Direction nor one unit in that specific Direction nor south east or west now I start from the south east or west now I start from the origin itself I just have to let know origin itself I just have to let know that I have to return true if the path that I have to return true if the path crosses itself which means I come onto crosses itself which means I come onto an existing point from where I have an existing point from where I have traveled as in if you take this example traveled as in if you take this example north east south so one unit North 1 north east south so one unit North 1 unit East one unit South but you see I unit East one unit South but you see I did not cross any paths so my ANS did not cross any paths so my ANS obvious B any points my answer is false obvious B any points my answer is false here you will see I'm seeing here you will see I'm seeing Northeast Northeast South South West Northeast Northeast South South West West with this West thing I reached to a West with this West thing I reached to a point which I had already see or already point which I had already see or already traveled because I traveled I started traveled because I traveled I started from 0 comma 0 then I went to 0a 1 then from 0 comma 0 then I went to 0a 1 then I went to 1A 1 then I went to 1 comma 0 I went to 1A 1 then I went to 1 comma 0 then from this 1 comma 0 I came to 0a 0 then from this 1 comma 0 I came to 0a 0 back which was already VIs Point does back which was already VIs Point does I'll say that in this itself I have seen I'll say that in this itself I have seen a point which was already there so I a point which was already there so I return a true so it's as simple as that return a true so it's as simple as that uh what you can do is you know that you uh what you can do is you know that you have these two as a coordinates X comma have these two as a coordinates X comma y if you encounter a character as n what y if you encounter a character as n what you will do is you will increase your y you will do is you will increase your y by one if you encounter if you are X by one if you encounter if you are X comma y if you encountered n it will comma y if you encountered n it will increase to X comma y + 1 which you can increase to X comma y + 1 which you can also see now if you have X comma y if also see now if you have X comma y if you encountered a East then what you saw you encountered a East then what you saw that simply your X will increase so it that simply your X will increase so it will be x + 1 comma y if you had X comma will be x + 1 comma y if you had X comma y if you encountered a South what you y if you encountered a South what you saw that your y will decrease so XA y - saw that your y will decrease so XA y - 1 if you had X comma Y and you 1 if you had X comma Y and you encountered a vest what you saw your x encountered a vest what you saw your x value got decreased so it is X -1a Y so value got decreased so it is X -1a Y so it is just that in these directions I it is just that in these directions I have to keep on moving my coordinates have to keep on moving my coordinates and as soon as I repeat any of these and as soon as I repeat any of these basically as soon as I repeat any of the basically as soon as I repeat any of the coordinates already and now when I say coordinates already and now when I say repeat I mean if I have already visited repeat I mean if I have already visited that now visited okay how will you that now visited okay how will you maintain the visited you can keep maintain the visited you can keep anything a map a unordered map for sure anything a map a unordered map for sure you also know that map's complexity is you also know that map's complexity is in login while unordered map complexity in login while unordered map complexity is just n so you will try to take is just n so you will try to take unordered map right all or you can also unordered map right all or you can also take a set also unordered map or take a set also unordered map or unordered set unordered set so with this unordered set unordered set so with this you can easily solve this now with this you can easily solve this now with this case as you can see that you have to case as you can see that you have to take these two coordinates take these two coordinates simultaneously so you have to take the simultaneously so you have to take the pair of X comma y to see okay if this pair of X comma y to see okay if this pair is already in my set or not so if pair is already in my set or not so if if if the key is not a proper thing as if if the key is not a proper thing as in if the key is actually a pair right in if the key is actually a pair right so you will have to write your own hash so you will have to write your own hash for that if you want to use an unordered for that if you want to use an unordered map so one way is if you have because map so one way is if you have because see if you had a simple and integer then see if you had a simple and integer then you can easily write an unordered set you can easily write an unordered set for it unordered set for it if you had for it unordered set for it if you had an integer you could have easily written an integer you could have easily written an unordered set if you had a string you an unordered set if you had a string you could have written the uned set if you could have written the uned set if you had a float double anything if you had had a float double anything if you had you would have written the uned set for you would have written the uned set for it but you cannot write unordered set it but you cannot write unordered set for a pair of int comma int you cannot for a pair of int comma int you cannot write this you cannot write this kind of write this you cannot write this kind of complex input in your unordered set if complex input in your unordered set if you want right you will have to Define you want right you will have to Define your own hash for it which is kind of your own hash for it which is kind of hard because it can have collisions and hard because it can have collisions and stuff so rather what we can do is we can stuff so rather what we can do is we can convert this particular pairer to a convert this particular pairer to a string or to maybe one integer this one string or to maybe one integer this one integer is again converting being like integer is again converting being like again converted to one integer is again converted to one integer is complex so what we will do is we'll complex so what we will do is we'll convert this pair of in comma in to one convert this pair of in comma in to one string now how to do that as simple as string now how to do that as simple as that we know that pair of int comma int that we know that pair of int comma int is actually nothing but X comma y that is actually nothing but X comma y that is what we wanted to store in our hash is what we wanted to store in our hash set right just convert and say okay set right just convert and say okay convert this integer X to a string X add convert this integer X to a string X add any delimeter add any any and I say when any delimeter add any any and I say when I say any you can add any delimeter you I say any you can add any delimeter you can add your name also as a delimer here can add your name also as a delimer here let's say for example I add a comma as a let's say for example I add a comma as a delimer and then I'll add a string as a delimer and then I'll add a string as a y so this will become x x comma y x y so this will become x x comma y x comma y ultimately will become a string comma y ultimately will become a string which will for sure be just mapping this which will for sure be just mapping this which means I'll just convert this x which means I'll just convert this x comma y integer as a pair of integers to comma y integer as a pair of integers to a string X comma Y and then I will use a string X comma Y and then I will use this in my hash unordered set un now this in my hash unordered set un now I'll write unordered set of this I'll write unordered set of this particular string and then I'll keep the particular string and then I'll keep the track of this particular unordered set track of this particular unordered set and see if any element I encounter and see if any element I encounter repeats any element repeats then for repeats any element repeats then for sure I return return a true so let's sure I return return a true so let's quickly code this up it's going to be quickly code this up it's going to be pretty simple again firstly I'll show pretty simple again firstly I'll show you that how we'll do it by simple pair you that how we'll do it by simple pair and then we'll just transform that and then we'll just transform that simple pair to our actual answer by simple pair to our actual answer by optimizing it so as we know that we are optimizing it so as we know that we are using pair so we will have to have to using pair so we will have to have to use a set so here I use a set because I use a set so here I use a set because I am using a pair and I initially starting am using a pair and I initially starting from a z comma 0 so I'll just insert 0a from a z comma 0 so I'll just insert 0a 0 in my set itself now when this portion 0 in my set itself now when this portion is done I know I have to DET all the is done I know I have to DET all the characters of my path right all the of characters of my path right all the of my path now if the path as we saw if the my path now if the path as we saw if the path is an N then my only y coordinate path is an N then my only y coordinate will increase nothing but like exactly will increase nothing but like exactly same as what we saw here if it is this same as what we saw here if it is this only Y coordinates else if if my C only Y coordinates else if if my C is south then my y coordinate will is south then my y coordinate will decrease else if uh if my C Is East then decrease else if uh if my C Is East then my x coordinate will increase else if it my x coordinate will increase else if it is west my x coordinate will decrease is west my x coordinate will decrease now with this my X and Y coordinates are now with this my X and Y coordinates are decreasing and increasing now I'll just decreasing and increasing now I'll just check if that XY pair which is the new check if that XY pair which is the new XY y pair if that XY pair I have found XY y pair if that XY pair I have found again which means it is um like not like again which means it is um like not like if it is not equal to if it is not equal to s.n which means I have found this so s.n which means I have found this so sorry bro uh you can easily return sorry bro uh you can easily return return a true here itself because you return a true here itself because you have found it okay that's great um and have found it okay that's great um and if not then uh simply you can just if not then uh simply you can just insert that pair in your set because it insert that pair in your set because it will help you uh later on in future will help you uh later on in future ultimately if anyhow you cannot able to ultimately if anyhow you cannot able to return return of false here itself so return return of false here itself so you will see it will run but you will you will see it will run but you will see the time complexity for this is see the time complexity for this is going to be n log and space is for sure going to be n log and space is for sure o ofn because you are using a set but o ofn because you are using a set but the time complexity is going to be o of the time complexity is going to be o of analog in now to optimize this what we analog in now to optimize this what we will do is we will rather use an will do is we will rather use an unordered set unordered set now here unordered set unordered set now here instead of pair we will use a strain instead of pair we will use a strain again we did not not optimize any logic again we did not not optimize any logic we just optim we just modifying the data we just optim we just modifying the data structure used so we'll just do s do structure used so we'll just do s do insert now here to S do insert um what I insert now here to S do insert um what I can do is I can just insert a 0 comma 0 can do is I can just insert a 0 comma 0 like this now if it is I'll just simply like this now if it is I'll just simply increase my these values now I'll just increase my these values now I'll just check uh like I'll just say uh string um check uh like I'll just say uh string um cord now I just say that I converted cord now I just say that I converted that string to a Cod so I'll just say that string to a Cod so I'll just say two string uh two string to a value u x two string uh two string to a value u x plus I just add a comma and then plus plus I just add a comma and then plus I'll just say two string value y now I I'll just say two string value y now I converted this coordinate to a cord I converted this coordinate to a cord I just check now this coordinate if that just check now this coordinate if that coordinate is in simply do this and if coordinate is in simply do this and if not then simply insert it else now with not then simply insert it else now with this you'll see that your time this you'll see that your time complexity has decreased to O of n complexity has decreased to O of n rather o of n log by just simple rather o of n log by just simple transforming your input to a string transforming your input to a string input so yeah that's how you can solve input so yeah that's how you can solve this this goodbye bye-bye | 2024-03-21 11:04:06 | 1,496 | 1496. Path Crossing | Amazon | Unordered vs Ordered Data Structure |
|
cY478B89ds4 | hey guys persistent programmer here and today we're gonna do another week cool today we're gonna do another week cool question check if it is a straight line question check if it is a straight line okay so let's look at this problem okay so let's look at this problem statement and understand what the statement and understand what the question is asking you are given an question is asking you are given an array coordinates with coordinate I array coordinates with coordinate I equals XY where X Y represents a equals XY where X Y represents a coordinate of a point check if these coordinate of a point check if these points make a straight line in the XY points make a straight line in the XY plane so what the question is basically plane so what the question is basically saying is that we're giving a saying is that we're giving a coordinates 2d matrix and in this matrix coordinates 2d matrix and in this matrix the first position is the x coordinate the first position is the x coordinate and the second position is the y and the second position is the y coordinate so if I were to draw this out coordinate so if I were to draw this out in a graph so you see the one two so in a graph so you see the one two so that means that the x coordinate here that means that the x coordinate here this is the x so the x coordinate here this is the x so the x coordinate here is 1 and the y coordinate is 2 so that's is 1 and the y coordinate is 2 so that's what the question means and what they're what the question means and what they're asking us to find is if this grabs out a asking us to find is if this grabs out a straight line then we need to return straight line then we need to return true so our output should be boolean so true so our output should be boolean so boolean true otherwise if it doesn't boolean true otherwise if it doesn't make a straight line then we need to make a straight line then we need to return false ok let's look at some return false ok let's look at some strategies we can use to solve this strategies we can use to solve this problem great so we need to make two problem great so we need to make two observations to solve this problem so observations to solve this problem so the first observation is if I'm given the first observation is if I'm given two points the line between those two two points the line between those two points is always going to be straight so points is always going to be straight so if I'm gonna given two points so if I if I'm gonna given two points so if I only have these two and that's my input only have these two and that's my input I can simply say that I need to return I can simply say that I need to return true because if we draw a line between true because if we draw a line between any two points there it's always going any two points there it's always going to be a straight line okay and the to be a straight line okay and the second thing we need to observe is our second thing we need to observe is our slope so let's do a review of what our slope so let's do a review of what our slope means and how that relates to this slope means and how that relates to this problem so the slope is rise over run so problem so the slope is rise over run so what this means is our y2 minus y1 so what this means is our y2 minus y1 so this is this is said this is y1 and then this is X 2 and said this is y1 and then this is X 2 and this is y 2 so we need to take the this is y 2 so we need to take the difference of y2 and y1 and we'll take difference of y2 and y1 and we'll take the difference of X 2 and X 1 all right the difference of X 2 and X 1 all right so what does this get that give us so 3 so what does this get that give us so 3 minus 2 is 1 and 2 minus 1 is 1 so our minus 2 is 1 and 2 minus 1 is 1 so our slope is 1/4 for this these two points slope is 1/4 for this these two points these first two points right so my slope these first two points right so my slope is 1 here now what do i what do I need is 1 here now what do i what do I need to ensure to find that my slope at each to ensure to find that my slope at each point is also going to be the same so if point is also going to be the same so if our slope is the same that means the our slope is the same that means the growth of this line is the same which growth of this line is the same which means it is a straight line and we can means it is a straight line and we can apply this concept to figure out whether apply this concept to figure out whether it's a straight line or not so let me it's a straight line or not so let me give an example of how we can compare give an example of how we can compare this to another point and find out if this to another point and find out if the slope is the same or not so let's the slope is the same or not so let's say we have our initial X&Y here x1 and say we have our initial X&Y here x1 and y1 right and we're comparing it to the y1 right and we're comparing it to the last point so 6 & 7 here right so we can last point so 6 & 7 here right so we can say that this is the new Y then call say that this is the new Y then call this a new Y and this can be new X so this a new Y and this can be new X so we'll do 7 minus 2 which is 5 and we'll we'll do 7 minus 2 which is 5 and we'll choose 6 minus 1 which is also 5 and choose 6 minus 1 which is also 5 and this 5 over 5 is 1 so again you can see this 5 over 5 is 1 so again you can see that our initial slope is equal to our that our initial slope is equal to our slope at any other point in this grid so slope at any other point in this grid so that's what tala tells us that yes this that's what tala tells us that yes this line is straight because the rate of line is straight because the rate of growth is the same now let's take a case growth is the same now let's take a case where this slope is not the same so where this slope is not the same so let's say I had a point here so 7 7 let's say I had a point here so 7 7 right so instead of six seven let's say right so instead of six seven let's say I had seven seven here right so the I had seven seven here right so the new X is 7 and my new y is 7 now we do 7 new X is 7 and my new y is 7 now we do 7 minus 2 which is 5 and then 7 minus 1 minus 2 which is 5 and then 7 minus 1 which is 6 so this is not equal to our which is 6 so this is not equal to our initial slope which is 1 right so in initial slope which is 1 right so in this case the answer would be false so this case the answer would be false so if you understand these two concepts and if you understand these two concepts and how to apply them then the code is how to apply them then the code is pretty straightforward ok so to review pretty straightforward ok so to review the solution the time for this would be the solution the time for this would be all offenses we're iterating over the all offenses we're iterating over the coordinate and the space sorry the space coordinate and the space sorry the space is actually off 1 we're not creating any is actually off 1 we're not creating any auxiliary space we're just doing in auxiliary space we're just doing in place operations here so the spaces of 1 place operations here so the spaces of 1 yeah and 2 yeah and 2 the first thing we need to do to solve the first thing we need to do to solve this problem is to get the initial scope this problem is to get the initial scope with slope which we did so that's a 1 with slope which we did so that's a 1 and we need to compare if the next and we need to compare if the next slopes are equal to our first slope and slopes are equal to our first slope and if that's the case then we just return if that's the case then we just return true otherwise we return false true otherwise we return false ok so if this makes sense let's look at ok so if this makes sense let's look at the code and I will provide two the code and I will provide two different solutions that I wrote to different solutions that I wrote to solve this problem great so I'm back in solve this problem great so I'm back in the code and I will start off with the the code and I will start off with the solution I wrote first before making solution I wrote first before making this a shorter solution so the run times this a shorter solution so the run times aren't the same it's just a matter of aren't the same it's just a matter of organization so the first thing I did is organization so the first thing I did is grab my first x and y and then the grab my first x and y and then the second x and y from the second row in second x and y from the second row in our coordinate so that's why this is a 1 our coordinate so that's why this is a 1 here and then I'm just getting the rise here and then I'm just getting the rise on the run so this is the Delta Y and on the run so this is the Delta Y and the Delta X and I wrote a function to the Delta X and I wrote a function to get the slope so let's say in its slope get the slope so let's say in its slope gets us our initial slope and then the gets us our initial slope and then the next thing I'm doing is getting the new next thing I'm doing is getting the new X&Y coordinates and I'm just comparing X&Y coordinates and I'm just comparing if those new coordinates are equal to my if those new coordinates are equal to my initial slope or not so initial slope or not so so I'm getting the new slow by by so I'm getting the new slow by by plugging in the new coordinates and what plugging in the new coordinates and what I'm doing is I'm just returning false if I'm doing is I'm just returning false if the initial scope slope is not equal to the initial scope slope is not equal to the new slope so that's what is going on the new slope so that's what is going on here and if everything else passes then here and if everything else passes then just return true and then this is my get just return true and then this is my get slope function and the reason I did this slope function and the reason I did this if statement is because I noticed that if statement is because I noticed that if you divide by zero you get a runtime if you divide by zero you get a runtime error because you can't divide by zero error because you can't divide by zero so that's why if the run is zero right so that's why if the run is zero right so you need to handle that case so this so you need to handle that case so this is sort of exception handling okay so is sort of exception handling okay so this is the second solution that I wrote this is the second solution that I wrote after looking at some of the other after looking at some of the other solutions only code and what I realized solutions only code and what I realized is instead of dividing the Delta Y and is instead of dividing the Delta Y and Delta X what we can just do is cross Delta X what we can just do is cross multiply so if this is our slope multiply so if this is our slope function what we can do is just multiply function what we can do is just multiply our Delta Y with our new X so just using our Delta Y with our new X so just using that we can avoid dealing with the that we can avoid dealing with the exceptions when our denominator is zero exceptions when our denominator is zero in this case and so that's a much in this case and so that's a much shorter solution and that's the second shorter solution and that's the second solution that I wrote for this problem solution that I wrote for this problem so all the other parts are the same so so all the other parts are the same so this statement is just comparing again this statement is just comparing again it's the same idea if our slopes are the it's the same idea if our slopes are the same or not because to check it's the same or not because to check it's the same thing as checking this as doing the same thing as checking this as doing the cross multiplication and checking cross multiplication and checking whether they're equal or not so that's whether they're equal or not so that's the only difference in this solution I the only difference in this solution I hope you enjoyed this video if you like hope you enjoyed this video if you like my videos please subscribe to my channel my videos please subscribe to my channel alright happy coding guys | 2024-03-19 11:57:16 | 1,232 | Check If It Is a Straight Line - 1232 Leetcode Python |
|
63BsBwShv2E | Hello Hello Everyone, today we are going to discuss whose Pran Math problem is Remove whose Pran Math problem is Remove Duplicates Transport Play List. There are two Duplicates Transport Play List. There are two problems with this problem that we have been shortlisted problems with this problem that we have been shortlisted and hence we are removing whatever and hence we are removing whatever duplicate number is there on it. duplicate number is there on it. Like here it is Like here it is 12345 You can see it here See this 12345 You can see it here See this and two more times Had to fix It and two more times Had to fix It has president similar for breast So has president similar for breast So what do I have to do I have to remove both of them what do I have to do I have to remove both of them Ok Ok 12512 Udayveer and sewerage connection 12512 Udayveer and sewerage connection is fixed And time is fixed And time is fixed And time what we have to do is only to admit and space, we do not have to use any express in this proposal, in the arm hole, we have to do this problem, let's see the crunch of MP3 problem, how to But first of all, But first of all, But first of all, what do we do, let's create 19, okay, it what do we do, let's create 19, okay, it corrects zero oil, we add corrects zero oil, we add vitamin and stomach to it, okay, vitamin and stomach to it, okay, we tell him to come quickly, we tell him to come quickly, okay, and one more point, okay, and one more point, okay, this okay, this okay, this and this is my love okay this we add to this his name indicates the accused now what do we do ghee now goes to school here we will see this subscribe us this is the first one in your Subscribe the hair and if it is both feathers which are not subscribed to both, feathers which are not subscribed to both, if it is equal then we have to cook it till if it is equal then we have to cook it till both of them are unique. Okay and as these will be recorded, both of them are unique. Okay and as these will be recorded, we will bring our previous one and we will bring our previous one and test it. test it. We need to be arrogant and mysterious. Okay, We need to be arrogant and mysterious. Okay, what did we say, but the game and Let's Play what did we say, but the game and Let's Play List is 2. Okay, if these two are List is 2. Okay, if these two are four, let's see who is there and who is not, then four, let's see who is there and who is not, then what will we do? what will we do? what will we do? now it will be mine and these two, now it will be mine and these two, then we have seen the trees and traffic and then we have seen the trees and traffic and what else is equal, so we will click but we will what else is equal, so we will click but we will take the bigger one, then we will mix the gas with the cricket take the bigger one, then we will mix the gas with the cricket and we will mix the same request, and we will mix the same request, okay okay okay need 6 and it is a tight Mexico, is it okay, let's take a bath, don't touch the previous ones, just by increasing the dough, people have claimed that they should look at it again or it is helpful for If it is If it is If it is not there then what will we do to the previous? Those who are not there then what will we do to the previous? Those who are not there will like and comment on it. Where is it? We will see that this is not in the hit list. We will see that this is not in the hit list. Okay, so what will we do now? We will Okay, so what will we do now? We will qualify the previous and oil. Here once again I give here again that hair and devil are equal, so we will take it till it becomes who, so we have taken it, we have taken it forward, we have taken it on this, now I one of this one and this one is I one of this one and this one is I one of this one and this one is not equal in terms of vision so what we will do is not equal in terms of vision so what we will do is take it one step further i.e. take it one step further i.e. how do you do reverse up and dynasty has come to this okay how do you do reverse up and dynasty has come to this okay coming to this okay so just now we coming to this okay so just now we saw here saw here saw here do, if you had this pizza bread previous now, then what will we do, free mode, start Bluetooth, scold them till this period, what will we do with the point or shadow also, one strip of After that, After that, After that, what will we get next, we will get the tap, it is help channel, what will we get next, we will get the tap, it is help channel, okay, so it was here, then check that okay, so it was here, then check that this liquid is not their channel, okay, this liquid is not their channel, okay, then we will check this half more, hair and hair then we will check this half more, hair and hair tablet, what is this, check in before this movie. tablet, what is this, check in before this movie. tablet, what is this, check in before this movie. not in the hit list to do, then if there is a request, it will be done there, okay, so now let's see how mine is, Jio is there, want is there, and only yours is okay and we were in written, what will we do without If there is chilli then Dominica has If there is chilli then Dominica has If there is chilli then Dominica has tested it, we will press this point tested it, we will press this point which will turn it all which will turn it all yours will go to the moon from here. Okay, yours will go to the moon from here. Okay, so come on, if you have the so come on, if you have the problem of having an accident, then either you have to problem of having an accident, then either you have to limit it towards the deposit and move it back. limit it towards the deposit and move it back. limit it towards the deposit and move it back. just because see so here there is an organization called attack deleted which is a judgment player to appointed update to Harold okay so here what we make kidney note made okay as I said What is the pass 120 and head What is the pass 120 and head What is the pass 120 and head is attached with this, what will happen with this, our land and is attached with this, what will happen with this, our land and stomach gets filled and the product has created a share i.e. stomach gets filled and the product has created a share i.e. inch pot chamber of such, inch pot chamber of such, then he said this and we then he said this and we point, the name is serious which we point, the name is serious which we A which indicates leadership to DAV, A which indicates leadership to DAV, it was necessary but this is also clear to me, it was necessary but this is also clear to me, okay and here I saw health, keep okay and here I saw health, keep running it till you remove it, now running it till you remove it, now here we are seeing cricket next here we are seeing cricket next dot is not installed on the back. dot is not installed on the back. dot is not installed on the back. if this is the bell icon thing is needed and the help chart if it has both of these then give us an increase then okay from there the alarm tomorrow until it happens at all so So, So, So, let's increase this video, there will be such a result that there will be no pimples let's increase this video, there will be such a result that there will be no pimples at all, there will be no pimples at all, by at all, there will be no pimples at all, by doing the same, you can do this chart, not doing the same, you can do this chart, not with the condition of which department, is it okay, as if I have gone with the condition of which department, is it okay, as if I have gone here, I felt that now I am worried, here, I felt that now I am worried, okay? okay? okay? till the time Amit got both of these, it was lost to me, hence the last condition will stop and here the computer period played equal to test i.e. Safari was my point, if now we will connect it. With and then we have this closed loop condition of moving our forward now we increased the game here last updated and these two murders are equal while on will remain on then will remain closed till the fog if you quantum enlarge the game This This This check itself has become modern on youth, check itself has become modern on youth, then it will go to the quarter with free apps, then it will go to the quarter with free apps, which is now the first previous till the get quantum science which is now the first previous till the get quantum science chapter, this hour will be free chapter, this hour will be free spread, it is okay and this you will spread, it is okay and this you will come to this okay, so the salary is that when come to this okay, so the salary is that when Ours will be equal, okay Jamshed and the Ours will be equal, okay Jamshed and the website has taken such a turn, so website has taken such a turn, so cook them till the time called for and then cook them till the time called for and then remove the pin point and mix remove the pin point and mix it, if it does not happen at all it, if it does not happen at all in this piece as we will see here. in this piece as we will see here. in this piece as we will see here. if this is the end, I am Golu and this and this is our I call you, then what do we have to do, we have to move the previous quantum worship and the hairs also, okay, time's clear all, today I am delisting you remember. Because I was appointed as a teacher in Delhi, I was representing and you don't remember that you have to recharge the destination. It's a wonder, any doubt has been cleared, we have returned. Please share this side, you will | 2024-03-20 12:21:10 | 82 | 82. Remove Duplicates from Sorted List II | Leetcode Problem | Leetcode Solution | Linkedlist | |
|
p0wmkvWY_uE | hey everybody this is Larry this is when I'm going to prompt I sell for the PI I'm going to prompt I sell for the PI weekly contest 29 I'm gonna put the weekly contest 29 I'm gonna put the explanation in the beginning and then explanation in the beginning and then I'm gonna do the live coding of it I'm gonna do the live coding of it afterwards let me know what you think afterwards let me know what you think about this format I'm still playing with about this format I'm still playing with it and here we hey everybody so for this it and here we hey everybody so for this problem I actually ended up be recording problem I actually ended up be recording it because initially I thought that the it because initially I thought that the greedy solution worked and that's what I greedy solution worked and that's what I did turn the contest I turns out that did turn the contest I turns out that greeted does not work and there was a greeted does not work and there was a case that I'll show later on yeah so case that I'll show later on yeah so well that's kind of a weird constraint I well that's kind of a weird constraint I think for this problem because and is think for this problem because and is you get a 15 so it it borderlines does you get a 15 so it it borderlines does not one fast enough but a Python you not one fast enough but a Python you have to make a the number of have to make a the number of optimizations to get it to work in optimizations to get it to work in Python instead and if you watch the Python instead and if you watch the contest video I actually go into this contest video I actually go into this incorrectly but and there are a lot of incorrectly but and there are a lot of people in which we read the solutions people in which we read the solutions especially in Python they did that they especially in Python they did that they did it with greedy and I'll show the did it with greedy and I'll show the case where their bricks in a bit but case where their bricks in a bit but basically the idea here is what a basically the idea here is what a correct solution is to use dynamic correct solution is to use dynamic programming and what can't dynamic programming and what can't dynamic programming a sort of a brute-force programming a sort of a brute-force bitmask bit said dynamic programming bitmask bit said dynamic programming what's a bit said right so bit set is what's a bit said right so bit set is that say you have a number between 1 to that say you have a number between 1 to n oh yeah and n elements right and you n oh yeah and n elements right and you took them I labeled 1 to N and then now took them I labeled 1 to N and then now for each subset you can just say for for each subset you can just say for example 1 2 5 6 7 maybe just then to example 1 2 5 6 7 maybe just then to represent this numbers of binary well represent this numbers of binary well it's the first number in the set yes it's the first number in the set yes there's a second I'm on the side yes there's a second I'm on the side yes it's a third I'm gonna set no yes for it's a third I'm gonna set no yes for for no for five years for six and semi for no for five years for six and semi so this is the binary representation of so this is the binary representation of the set and then now then their the set and then now then their explanation on how to solve this is okay explanation on how to solve this is okay well first you start with every number well first you start with every number so let's say n is equal to seven again so let's say n is equal to seven again so now you have so now you start with so now you have so now you start with disparate set it can contains every disparate set it can contains every number number from one to seven right and now you try from one to seven right and now you try let's just say for example this is case let's just say for example this is case you got to wait so then now we we start you got to wait so then now we we start by trying okay this the F of n where or by trying okay this the F of n where or F of the spit mask how many what is the F of the spit mask how many what is the minimum number of semesters that it minimum number of semesters that it takes to take all these courses well it takes to take all these courses well it is just equal to the minimum number of is just equal to the minimum number of taking the first two classes one and two taking the first two classes one and two plus one right if so this is taking plus one right if so this is taking classes one and two if possible in the classes one and two if possible in the first semester right and or you can also first semester right and or you can also take maybe one n classes one end to it take maybe one n classes one end to it right no copy and paste no Polizzi and right no copy and paste no Polizzi and maybe one and four right but again this maybe one and four right but again this is only where as possible so this is how is only where as possible so this is how we do the big mask one and you do that we do the big mask one and you do that recursively by saying okay well let's recursively by saying okay well let's say grab this one and this one is good say grab this one and this one is good right let's say we're here and well what right let's say we're here and well what is the one is the min of this minimum is the one is the min of this minimum min semester for this well it's just you min semester for this well it's just you go to all of well for K is you go to let go to all of well for K is you go to let you say you know the first two class you say you know the first two class plus one right which is taking classes plus one right which is taking classes two and three if possible in this two and three if possible in this current semester right and again we current semester right and again we thought that dotted and that's how you thought that dotted and that's how you do the recursion all the way back down do the recursion all the way back down to zero is your base case meaning and to zero is your base case meaning and this is always zero seven zeros no this is always zero seven zeros no crisis yay and and that is just equal to crisis yay and and that is just equal to 0 right so f of 0 as you see because 0 right so f of 0 as you see because when you have normal class of stuff you when you have normal class of stuff you don't have to take a semester so that's don't have to take a semester so that's kind of the recurrence but of course kind of the recurrence but of course that is easier said than done because a that is easier said than done because a lot of the hard time especially with lot of the hard time especially with this particular problem was figuring out this particular problem was figuring out how how to do this effectively how how to do this effectively and there are a bit of bitmask solutions and there are a bit of bitmask solutions I have to code here basically what I did I have to code here basically what I did was that I have a prerequisite we label was that I have a prerequisite we label this a little bit and it's a pretty this a little bit and it's a pretty tricky actually which is why I found I tricky actually which is why I found I didn't do it this way during the contest didn't do it this way during the contest but basically the idea is that okay for but basically the idea is that okay for each for each possible subset and I use each for each possible subset and I use this this is a really hard notation to this this is a really hard notation to understand in a sense that like it's not understand in a sense that like it's not a common thing but it basically it gets a common thing but it basically it gets a subset of a subset so it allows you to a subset of a subset so it allows you to do it 3 to the end times and then for do it 3 to the end times and then for each of these so this is a candidate for each of these so this is a candidate for four okay that lets know for J it's a four okay that lets know for J it's a bit mask so for example in this case I bit mask so for example in this case I just go so let's say in the stuff in the just go so let's say in the stuff in the beginning right let's just take this one beginning right let's just take this one right so let's say we're here i as you right so let's say we're here i as you go to this thing this is you go to I and go to this thing this is you go to I and J is just okay j-just rise every J is just okay j-just rise every possibility that's a subset of T's possibility that's a subset of T's meaning that no try you know try J goes meaning that no try you know try J goes to you know although one one one one one to you know although one one one one one and it tries to do oh one one one I'm 0 and it tries to do oh one one one I'm 0 J is equal to Rho 1 1 1 0 1 and and so J is equal to Rho 1 1 1 0 1 and and so forth forth dot that die and it tries these and then dot that die and it tries these and then it just checks a couple of things the it just checks a couple of things the first one is that well the number of first one is that well the number of digits that you're trying has to be less digits that you're trying has to be less than K because that's the number of than K because that's the number of classes we're taking J is the a bit mask classes we're taking J is the a bit mask of all the classes we're taking right in of all the classes we're taking right in this case is 5 so no good this is for no this case is 5 so no good this is for no good so far away and now let's say we go good so far away and now let's say we go to you know some some ends on which to to you know some some ends on which to there is there is mask of K is less than two so this time mask of K is less than two so this time okay it's good but you know you won't okay it's good but you know you won't can only take classes that does have can only take classes that does have prerequisites so what I did is okay so I prerequisites so what I did is okay so I look at for this bit if this bit if we look at for this bit if this bit if we wanted to take this class this is what K wanted to take this class this is what K is we want to take the cave class the is we want to take the cave class the cave class has a prerequisite yeah so if cave class has a prerequisite yeah so if this is kind of hard that's why I'm this is kind of hard that's why I'm struggling a little bit to explain struggling a little bit to explain because it also took me a while but if because it also took me a while but if this prerequisite of this class which is this prerequisite of this class which is a bit mask so here we set up for we set a bit mask so here we set up for we set up a bit mask for each K the up a bit mask for each K the prerequisite of that class so that means prerequisite of that class so that means that for example for the probably if for that for example for the probably if for a prereq of GUI yes big it's off by one a prereq of GUI yes big it's off by one a little bit depending how you want to a little bit depending how you want to count it index let's say put this one it count it index let's say put this one it is three and if this three is you go to is three and if this three is you go to you know that's let's say it could be you know that's let's say it could be any number of things but let's say it any number of things but let's say it requires the first two class well the requires the first two class well the first two class is good so you're doing first two class is good so you're doing and bit on it and they and end up an N and bit on it and they and end up an N bit of it should be zero away but if for bit of it should be zero away but if for whatever reason that's a you have any whatever reason that's a you have any other cousin in between if the current I other cousin in between if the current I has these classes that means we haven't has these classes that means we haven't taken those classes yet and if that taken those classes yet and if that intersection is greater than one or if intersection is greater than one or if the intersection is not zero the intersection is not zero then then you cannot take the I've then then you cannot take the I've caused and because you can't take the ID caused and because you can't take the ID class we just set this as a not real class we just set this as a not real candidate and that's basically the candidate and that's basically the dynamic programming recurrence and then dynamic programming recurrence and then here is just okay if if again if the here is just okay if if again if the count is less than teed I named it t count is less than teed I named it t because I used two K here but if we can because I used two K here but if we can take less than T number of classes the take less than T number of classes the semester and all the prerequisites are semester and all the prerequisites are met we just do the min which is which is met we just do the min which is which is this this I mind this xrj just removes the J from I mind this xrj just removes the J from the eye and then you do that plus 1 the eye and then you do that plus 1 which is the recurrence that we talked which is the recurrence that we talked about earlier again this is really hard about earlier again this is really hard really tricky to get bright and a couple really tricky to get bright and a couple of optimizations here and here and the of optimizations here and here and the counting you could do with some index counting you could do with some index and in Python you have to make an and in Python you have to make an additional optimization in which instead additional optimization in which instead of doing it this way you pre choose the of doing it this way you pre choose the K so that you only count the case that K so that you only count the case that are possible I don't want to get into it are possible I don't want to get into it that much but know that is kind of that much but know that is kind of tricky to get right alex has a good tricky to get right alex has a good solution on that will be select to that solution on that will be select to that and yeah that's what I have for the and yeah that's what I have for the solution if you're wondering why the solution if you're wondering why the greedy doesn't work greedy doesn't work let me show up show a graph so this is let me show up show a graph so this is what I drew ah this doesn't work because what I drew ah this doesn't work because for a graph like this if you look at the for a graph like this if you look at the first if you just do greedy then if you first if you just do greedy then if you do greedy but maybe just do regular do greedy but maybe just do regular greedy by in degree there are a lot of greedy by in degree there are a lot of ways that this could be wrong because ways that this could be wrong because and death as well because they have the and death as well because they have the same thing but let's say UK is you go to same thing but let's say UK is you go to two way if K is you go to your first two two way if K is you go to your first two nodes may be here right these two nodes nodes may be here right these two nodes and then your second and your first and then your second and your first semester you take those two notes your semester you take those two notes your second semester you take this node and second semester you take this node and then your third semester you take this then your third semester you take this node and then the fourth semester you node and then the fourth semester you take this node right so that's four but take this node right so that's four but if you do it smartly for example you do if you do it smartly for example you do first semester you do these two nodes first semester you do these two nodes and then the second semester you take I and then the second semester you take I can't do it quite usually but for a can't do it quite usually but for a second semester you took you take this second semester you took you take this node and this node and then the third node and this node and then the third semester you take this node you're you semester you take this node you're you only need to do in three nodes or three only need to do in three nodes or three semesters let me cover it in so that semesters let me cover it in so that it's a little bit clearer so these two it's a little bit clearer so these two are the same the yellow ones are the are the same the yellow ones are the same semester way so in that case open same semester way so in that case open depth and otherwise this is the wrong depth and otherwise this is the wrong solution so yeah so that's why query solution so yeah so that's why query doesn't work and doesn't work and when I did turn the contest to be honest when I did turn the contest to be honest so some of my commentary maybe in Quebec so some of my commentary maybe in Quebec on that but you know you'd learn and you on that but you know you'd learn and you keep growing and that's what I'm trying keep growing and that's what I'm trying to do to do I think the annoying part is knowing I think the annoying part is knowing that I did it why I had to my idea but I that I did it why I had to my idea but I just didn't think that the optimizations just didn't think that the optimizations would help that much would help that much I guess the test cases were very I guess the test cases were very borderline on tasks on timing I think if borderline on tasks on timing I think if they said until you go to like 12 or they said until you go to like 12 or something like this we would make it a something like this we would make it a lot easier just not even that much lot easier just not even that much easier there compliment ation would have easier there compliment ation would have been exactly the same but the whining been exactly the same but the whining time complexity would have been much time complexity would have been much slightly easier to optimize but also you slightly easier to optimize but also you just won't run into all these time limit just won't run into all these time limit addition because you could prove with addition because you could prove with math that these optimizations would make math that these optimizations would make it fit really easily where we're in this it fit really easily where we're in this case you need to be in C++ or Java or case you need to be in C++ or Java or something like that to make it fast something like that to make it fast enough in Python you need another enough in Python you need another optimization which is kind of is that my optimization which is kind of is that my I implemented in a couple of ways maybe I implemented in a couple of ways maybe you could do it in Python if you do a you could do it in Python if you do a lot of other optimizations but oh yeah lot of other optimizations but oh yeah but that's what I have with this but that's what I have with this explanation with this problem let me explanation with this problem let me know what you think I'm going to do the know what you think I'm going to do the life you know recording of this life you know recording of this afterwards but keep the mindless afterwards but keep the mindless explanation anyway mm-hmm no cost to explanation anyway mm-hmm no cost to parallel cause to queue for so yeah what parallel cause to queue for so yeah what is this to say about this one so this is this to say about this one so this one when I first read this I was like one when I first read this I was like okay I I think I understand the problem okay I I think I understand the problem and yeah and I scroll down I was like and yeah and I scroll down I was like okay I when I fixed saw this I didn't okay I when I fixed saw this I didn't know I mean I didn't know how to solve know I mean I didn't know how to solve it per se I was like okay this makes it per se I was like okay this makes sense this is just standard you can only sense this is just standard you can only take up two K classes a semester okay take up two K classes a semester okay then when I saw n is equal to 15 then when I saw n is equal to 15 frankly I was fooled so well point farm frankly I was fooled so well point farm said I thought n is good 15 I thought said I thought n is good 15 I thought that I could do proof force so it turns that I could do proof force so it turns out that there's roughly speaking a tree out that there's roughly speaking a tree to the end roof was sorry that well to the end roof was sorry that well proof works with dynamic programming it proof works with dynamic programming it masks and there's a three to the end masks and there's a three to the end solution solution or do it to the old way to the end times or do it to the old way to the end times and or something like that but something and or something like that but something that is essentially not fast enough but that is essentially not fast enough but barely not that or a fuse barely not barely not that or a fuse barely not fast enough so I did that for about an fast enough so I did that for about an hour and you're watching this there'll hour and you're watching this there'll be a link below I would skip ahead to be a link below I would skip ahead to the greedy part of the solution and I'll the greedy part of the solution and I'll explain the greedy part as well explain the greedy part as well yeah clicked on the button click on the yeah clicked on the button click on the button below Stillwell bit one in the same time yeah I worry about let's struggle the libel prevailing let's struggle the libel prevailing today it's fast enough though touching to toe should be longer young nice one never go oh wow now he's having a day made the same mistake a couple of times now that was the worst case actually good that was the worst case actually good yes that's fair enough yes that's fair enough how do you do it then oh I must be how do you do it then oh I must be missing something obvious well a lot of missing something obvious well a lot of people got sick so I guess I'm just people got sick so I guess I'm just having one of those days we're missing having one of those days we're missing the obvious maybe I do need more sleep [Music] now let's try greedy I guess I know why would even get a team that's the part I welcome back so for this poem for right welcome back so for this poem for right now to be honest even for the last five now to be honest even for the last five to ten minutes I was just really to ten minutes I was just really thinking about it can be really can it thinking about it can be really can it well n is equal to 15 like they wouldn't well n is equal to 15 like they wouldn't give a greedy problem with and as you go give a greedy problem with and as you go to 15 right so that that was my like to 15 right so that that was my like like I was I was out of ideas I just like I was I was out of ideas I just couldn't think of anything else because couldn't think of anything else because I was like okay if it's not brute force I was like okay if it's not brute force it has to be greedy or some sort of it has to be greedy or some sort of greedy but I just couldn't I was like 15 greedy but I just couldn't I was like 15 and it's you go to 15 this is you know and it's you go to 15 this is you know this has to be before us right so I did this has to be before us right so I did really spend a long time convinced that really spend a long time convinced that it was not greedy because of any secret it was not greedy because of any secret of 13 I don't maybe there's some clever of 13 I don't maybe there's some clever 2 to the 15 solution of something but 2 to the 15 solution of something but but after an hour I'm trying to figure but after an hour I'm trying to figure out dynamic programming and booth force out dynamic programming and booth force and something like that I was like okay and something like that I was like okay look Larry you ran out of ideas you look Larry you ran out of ideas you don't I mean it you just don't have don't I mean it you just don't have anything else right like like if greedy anything else right like like if greedy doesn't work fine but you should at doesn't work fine but you should at least try greedy because it might work least try greedy because it might work and and then you tried everything right and and then you tried everything right and I already at this point you might and I already at this point you might not have seen me code everything but I not have seen me code everything but I was in my head I tried it like one hour was in my head I tried it like one hour like different things to kind of get it like different things to kind of get it to work and and I couldn't get it so to work and and I couldn't get it so after that I did greedy algorithm and I after that I did greedy algorithm and I explained this idolater before in the explained this idolater before in the explanation portion but basically explanation portion but basically the greedy part comes from figuring out the greedy part comes from figuring out that okay given the longest path of a that okay given the longest path of a course or like a given the longest path course or like a given the longest path of this graph that will always be at of this graph that will always be at least a minimum length way but we can't least a minimum length way but we can't like that is the smallest minimum length like that is the smallest minimum length of minimum semesters so I was like okay of minimum semesters so I was like okay well I guess we could just greedy on well I guess we could just greedy on that because we always want to take the that because we always want to take the longest path or the node that lot leads longest path or the node that lot leads to the longest path be that that's part to the longest path be that that's part of a longest path because why not right of a longest path because why not right because you have to take that class because you have to take that class before all the classes that depends on before all the classes that depends on it on this longest path so basically it on this longest path so basically that's what I did I did help a little that's what I did I did help a little bit I am economy on getting the longest bit I am economy on getting the longest path as you see in this function path as you see in this function actually maybe I forgot actually I guess actually maybe I forgot actually I guess there's a depth per search you didn't there's a depth per search you didn't need to you didn't need to cache it I need to you didn't need to cache it I didn't I think I just forgot to cash it didn't I think I just forgot to cash it because I thought that I would just cash because I thought that I would just cash it so actually I'm glad that uh whoops I it so actually I'm glad that uh whoops I only noticed this now so an explanation only noticed this now so an explanation portion I actually forgot about this but portion I actually forgot about this but but but yeah so so that actually made it but but yeah so so that actually made it to complexity a lot more expensive but to complexity a lot more expensive but somehow it's still passed so I'm happy somehow it's still passed so I'm happy about that but yeah so given so I was about that but yeah so given so I was just thinking a little bit of what do I just thinking a little bit of what do I need to sort it by do I need to sort by need to sort it by do I need to sort by the out degrees I was like no I mean I the out degrees I was like no I mean I not really because you if the out degree not really because you if the out degree it's like given if a node has multiple it's like given if a node has multiple or like a lot of out degrees you still or like a lot of out degrees you still have to clear it in some order because have to clear it in some order because the longest path is to think that the longest path is to think that matters the most matters the most so what I do now is that for every class so what I do now is that for every class that we can take we sorted by the that we can take we sorted by the longest path by putting in a priority longest path by putting in a priority queue and then we just take the top K queue and then we just take the top K elements every time up to priority queue elements every time up to priority queue so that basically we're taking K courses so that basically we're taking K courses or uptick a courses every time and then or uptick a courses every time and then every time we take those K courses we we every time we take those K courses we we free up new courses free up new courses we can take and this is very sick we can take and this is very sick topological SOI but I actually didn't topological SOI but I actually didn't know that you could do greedy this way know that you could do greedy this way so I'm happy to can learn about this so I'm happy to can learn about this today because I really thought that it today because I really thought that it has to be dynamic programming or good has to be dynamic programming or good for us maybe I just haven't thought for us maybe I just haven't thought about this farm in a long time about this farm in a long time topological SOI I'll be on the bare topological SOI I'll be on the bare minimum so I'm happy to kind of be minimum so I'm happy to kind of be reminded about this yeah at this way reminded about this yeah at this way moment I was like okay do I need another moment I was like okay do I need another key to figure out what to sort this by I key to figure out what to sort this by I was like now actually put a heap I just was like now actually put a heap I just need the longest path I think for what I need the longest path I think for what I said about the outdegree earlier and said about the outdegree earlier and then now we take every we just go then now we take every we just go through the entire list and and yeah and through the entire list and and yeah and we just take K courses at a time yeah but yeah but that's pretty much all I have to be honest yeah because as soon as I did this I click Submit and it worked and I stopped thinking about it I was very sad but yeah still it is what it is yeah let me know what you think how do you did on this problem how do you do on this contest well I guess the other guy is still talking or going to talk so listen | 2024-03-21 11:00:09 | 1,494 | 1494. Parallel Courses II (Leetcode Hard) |