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
|
---|---|---|---|---|---|
Fi8285s8214 | hello hello hello hi guys good morning welcome back to the new video in this we welcome back to the new video in this we going to see a problem maximum going to see a problem maximum difference between node and difference between node and ancestors and uh this problem is asked ancestors and uh this problem is asked by Amazon Google and Facebook in last by Amazon Google and Facebook in last one year so in the last 6 months it has one year so in the last 6 months it has not been that frequent but in the last not been that frequent but in the last one year it has been let's see what the one year it has been let's see what the problem says the problem says that we problem says the problem says that we are given the root for sure if we are are given the root for sure if we are having a binary tree or a tree we are having a binary tree or a tree we are usually only the root itself because usually only the root itself because from there we can easily start from there we can easily start traversing we find we have to find the traversing we find we have to find the maximum value V which means V is nothing maximum value V which means V is nothing but we have two different nodes A and B but we have two different nodes A and B then it's the difference value absolute then it's the difference value absolute again that's absolute this is a modulus again that's absolute this is a modulus which represents the absolute difference which represents the absolute difference value between A and B so for sure if we value between A and B so for sure if we want this V to be maximum again we want want this V to be maximum again we want this V which which is the absolute this V which which is the absolute difference between a and b value we want difference between a and b value we want this value to be maximum V value to this value to be maximum V value to maximum so what we can do is we can just maximum so what we can do is we can just take this as the maximum value we can take this as the maximum value we can take this B as the minimum value if this take this B as the minimum value if this is maximum if this is minimum of the is maximum if this is minimum of the entire tree then for sure I can easily entire tree then for sure I can easily say that uh my V will be say that uh my V will be maximum so it just says that uh now um maximum so it just says that uh now um how this A and B are defined it is how this A and B are defined it is saying that node a is an ancestor of saying that node a is an ancestor of node B oh so a should be the parent of node B oh so a should be the parent of node B if either any child of a is equal node B if either any child of a is equal to b or any child of a is an ancestor of to b or any child of a is an ancestor of B so child of a is equal to b or any B so child of a is equal to b or any child of child of a is an ancestor of B basically like a is an ancestor of B basically like let's say if I have a c which is an let's say if I have a c which is an ancestor of B so with that also so I can ancestor of B so with that also so I can easily say that okay it's true it is easily say that okay it's true it is true now the first question which you true now the first question which you might say is B you told that this a might say is B you told that this a value needs to be maximum and B value value needs to be maximum and B value needs to be minimum so shall I say that needs to be minimum so shall I say that I will take my ancestor as the maximum I will take my ancestor as the maximum value and the current node as the value and the current node as the minimum value are you seeing this to minimum value are you seeing this to take which means are you seeing that take which means are you seeing that let's say if I am here so 8 will be for let's say if I am here so 8 will be for sure it needs to maximum right so eight sure it needs to maximum right so eight will be big and 14 will be small but it will be big and 14 will be small but it is not small so this will not form a is not small so this will not form a ancestor pair which means it is not ancestor pair which means it is not maximum than it is not more than this 8 maximum than it is not more than this 8 is not more than 14 so it should not is not more than 14 so it should not form this pair but no I'll say it's form this pair but no I'll say it's absolute value so I can write the same absolute value so I can write the same thing also as B minus a which means for thing also as B minus a which means for sure this can be a maximum value this sure this can be a maximum value this can be a minimum value right so any node can be a minimum value right so any node any node again a need to exist of B that any node again a need to exist of B that is true which means A and B only needs is true which means A and B only needs to be two different node in the level to be two different node in the level obviously in the path of the tree from obviously in the path of the tree from root to node like root to the leaf node root to node like root to the leaf node A and B should be there either a here or A and B should be there either a here or B here or a here or B here it can be B here or a here or B here it can be like this so if we go back and see in like this so if we go back and see in this example that this is one path which this example that this is one path which we can have this is Again One path which we can have this is Again One path which we can have and again from root to we can have and again from root to ancestor this is again next PATH which ancestor this is again next PATH which we can have we can have this is again next part which we can this is again next part which we can have so basically out of all these four have so basically out of all these four parts I have to get in that okay what parts I have to get in that okay what can be the maximum value of a minus B can be the maximum value of a minus B and again I just wanted to maximize my a and again I just wanted to maximize my a and minimize my B and again that can be and minimize my B and again that can be any node any node a can be any node it's any node any node a can be any node it's just that it has to be a different node just that it has to be a different node than that of my B node okay now uh by than that of my B node okay now uh by why is that different needed because you why is that different needed because you saw that if it is a same then for sure saw that if it is a same then for sure the answer would actually be a zero so the answer would actually be a zero so we just wanted that to maximize it we we just wanted that to maximize it we want to have these as a different node want to have these as a different node itself so what I and by this you can see itself so what I and by this you can see okay a was actually A8 and B was okay a was actually A8 and B was actually a one which will give you the actually a one which will give you the maximum difference which is actually a maximum difference which is actually a seven and that's how you can simply seven and that's how you can simply solve this now coming on that how we can solve this now coming on that how we can do it as we saw that we'll just keep do it as we saw that we'll just keep track of the maximum and the minimum track of the maximum and the minimum value along a path as we go on from root value along a path as we go on from root to all the leaves so I can Simple Start to all the leaves so I can Simple Start From The Root which means I'll simply From The Root which means I'll simply okay right now the maximum value is okay right now the maximum value is eight minimum value is eight and then eight minimum value is eight and then I'll go on to my leaf node okay sorry I I'll go on to my leaf node okay sorry I I'll go on to my next nodes and again I'll go on to my next nodes and again that's a simple DFS DFS travel which I that's a simple DFS DFS travel which I can do I can just simply call for left can do I can just simply call for left and right and asking for what is the and right and asking for what is the maximum difference which you can give so maximum difference which you can give so what he will do is while going down he what he will do is while going down he will update his maximum and minimum will update his maximum and minimum value okay he'll update maximum which is value okay he'll update maximum which is actually it will still remain eight actually it will still remain eight minimum will update it to three okay he minimum will update it to three okay he go down then he will update the maximum go down then he will update the maximum maximum two maximum is still same maximum two maximum is still same minimum becomes one now he'll go down oh minimum becomes one now he'll go down oh it has become null now when it becomes it has become null now when it becomes null I should okay my entire path has null I should okay my entire path has been traversed when it becomes null been traversed when it becomes null which means okay my entire from root to which means okay my entire from root to Leaf which means all these things are Leaf which means all these things are actually traversed when all this is actually traversed when all this is traversed now you should find out okay traversed now you should find out okay what is the maximum value as you want what is the maximum value as you want your V was absolute of a minus B Now your V was absolute of a minus B Now find out what is the maximum value of V find out what is the maximum value of V so he will say the maximum value of V is so he will say the maximum value of V is 8 - 1 because uptil so far I have 8 - 1 because uptil so far I have updated both my maximum and the minimum updated both my maximum and the minimum values with the corresponding maximum values with the corresponding maximum and the minimum so I have I I know okay and the minimum so I have I I know okay what is the maximum value or the maximum what is the maximum value or the maximum difference value here so I'll update difference value here so I'll update this and I'll I'll get a 7 so now what this and I'll I'll get a 7 so now what will happen is he will simply return will happen is he will simply return this number 77 Now by why is this this number 77 Now by why is this returned can't we simply updated returned can't we simply updated globally yeah you can uh globally have a globally yeah you can uh globally have a variable called as answer which you can variable called as answer which you can update it every time you reaches you you update it every time you reaches you you reach a null node so that is also what reach a null node so that is also what you can do by why can't I update it you can do by why can't I update it every step which means Here Also let's every step which means Here Also let's say you came in here let's say I update say you came in here let's say I update here firstly my answer I update here here firstly my answer I update here also my answer I update here also my also my answer I update here also my answer and then at n also my answer yeah answer and then at n also my answer yeah you can do that also that also is very you can do that also that also is very much okay it's just that that will be much okay it's just that that will be much more redundant because for sure in much more redundant because for sure in this path you would have grabbed what is this path you would have grabbed what is the maximum maximum value and what's the the maximum maximum value and what's the minimum minimum value for sure so minimum minimum value for sure so ultimately you can check in the itself ultimately you can check in the itself so that's uh much more easy for you to so that's uh much more easy for you to check now okay we'll we'll do the same check now okay we'll we'll do the same thing for this path so when it was thing for this path so when it was traversing down it had got its maximum traversing down it had got its maximum minimum like this now when it will go it minimum like this now when it will go it has traversed here it has returned him has traversed here it has returned him the answer as seven now he will go down the answer as seven now he will go down and he will say okay I'll update my and he will say okay I'll update my maximum and minimum values okay maximum maximum and minimum values okay maximum will not be a because it is8 and 6 is will not be a because it is8 and 6 is less than 8 and again minum is less than less than 8 and again minum is less than six also again Maxim minimum will still six also again Maxim minimum will still remain same so he will also compute the remain same so he will also compute the answer because next value is n he will answer because next value is n he will also compute the answer because same way also compute the answer because same way he'll also go down again he'll compute he'll also go down again he'll compute the answer both will compute the answer the answer both will compute the answer as current existing answer is equals to as current existing answer is equals to maximum of answer comma uh this value maximum of answer comma uh this value which is here it has competed 8 - 3 5 so which is here it has competed 8 - 3 5 so now they can simply return this value so now they can simply return this value so uh from my answer which means from my uh from my answer which means from my left portion I'll get in as a value of left portion I'll get in as a value of five but for sure I'll have the maximum five but for sure I'll have the maximum value in my answer so I can again there value in my answer so I can again there are multiple ways to solve it you can are multiple ways to solve it you can also initialize globally and also you also initialize globally and also you can update it locally right so he will can update it locally right so he will say Okay maximum answer will actually be say Okay maximum answer will actually be a seven from left side now the same way a seven from left side now the same way maximum value minimum value is 88 maximum value minimum value is 88 maximum value is updated to 10 Again maximum value is updated to 10 Again maximum value updated to 14 maximum upd maximum value updated to 14 maximum upd to uh still remain at 14 because value to uh still remain at 14 because value is 13 now I will compute my answer so it is 13 now I will compute my answer so it will be 14 - 8 which actually six but will be 14 - 8 which actually six but still you will see that okay it will still you will see that okay it will return six return six so from right I'll return six return six so from right I'll get a six from left I'll get a seven get a six from left I'll get a seven maximum value from left is like maximum maximum value from left is like maximum value from left is seven from right is value from left is seven from right is actually a six so for sure I'll take a actually a six so for sure I'll take a maximum which is left from right like maximum which is left from right like from left and from right so I'll get a from left and from right so I'll get a seven as the maximum value from Total so seven as the maximum value from Total so that is how I can simply get my answer that is how I can simply get my answer and this was the answer for me so if you and this was the answer for me so if you go on the code it's as simple as that go on the code it's as simple as that firstly if my base case if my root is firstly if my base case if my root is null then I'll simply return return a null then I'll simply return return a zero because for sure I cannot now I'll zero because for sure I cannot now I'll simply have a function called as maxti simply have a function called as maxti is it's just a recursive function I'll is it's just a recursive function I'll call a root I'll give the I'll give the call a root I'll give the I'll give the current node value which is the current current node value which is the current see I have to maintain my current Max see I have to maintain my current Max and my current minan so I'm just doing and my current minan so I'm just doing that while maintaining by going down that while maintaining by going down itself in the tree I'm maintaining that itself in the tree I'm maintaining that so um I as soon as I land onto this Max so um I as soon as I land onto this Max diff function which is the same function diff function which is the same function right here first base case is okay if I right here first base case is okay if I have reached the null as I showed you I have reached the null as I showed you I should have to return the maximum minus should have to return the maximum minus minimum value as you saw that when I minimum value as you saw that when I have reached the null I was Computing have reached the null I was Computing this maximum this maximum minus this this maximum this maximum minus this minimum value and this is what I got as minimum value and this is what I got as the answer now when this portion is done the answer now when this portion is done I will go and find my maximum Val which I will go and find my maximum Val which is maximum of this maximum current value is maximum of this maximum current value and the node value but just maximizing and the node value but just maximizing my maximum value just minimizing my my maximum value just minimizing my minimum value and then both values I minimum value and then both values I have I simply call my Max for lifti have I simply call my Max for lifti which means calling for left and passing which means calling for left and passing in the maximum minimum value and same in the maximum minimum value and same for the max right diff which means for the max right diff which means calling for the right and passing the calling for the right and passing the maximum minimum value now when I have maximum minimum value now when I have the maximum from the left and maximum the maximum from the left and maximum from the right I'll simply take the from the right I'll simply take the maximum to return to my final answer as maximum to return to my final answer as you saw when I have maximum from the you saw when I have maximum from the left maximum from the right and I'll left maximum from the right and I'll simply take the maximum of both of them simply take the maximum of both of them to return in the final answer and that's to return in the final answer and that's what I am doing right here and that's what I am doing right here and that's how you can simply solve it in O of n how you can simply solve it in O of n time and O of n space because o of n time and O of n space because o of n time because you are traversing on all time because you are traversing on all the nodes of the tree and O of n space the nodes of the tree and O of n space because in worse case your recursive because in worse case your recursive stack can be a screw tree and that can stack can be a screw tree and that can go very deep which means just like this go very deep which means just like this a straight A straight kind of a tree and a straight A straight kind of a tree and that's how you can simply solve it so I that's how you can simply solve it so I hope that you guys got this bir care hope that you guys got this bir care bye-bye | 2024-03-25 15:11:17 | 1,026 | 1026. Maximum Difference Between Node and Ancestor | Amazon | Google | Meta |
|
roR6fG_X7Ns | hey hey everybody this is Larry this is the seventh day of the legal daily the seventh day of the legal daily challenge of the year or the sixth day challenge of the year or the sixth day out no let me now look at this uh hit out no let me now look at this uh 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 problem I'm gonna think about today's problem I'm gonna just see if there any bonus coins nope just see if there any bonus coins nope uh yeah uh yeah um today's prime is gas station so let's um today's prime is gas station so let's take a look take a look um and I am doing this a little bit um and I am doing this a little bit earlier in my night so I am going to do earlier in my night so I am going to do a bonus problem so definitely hit the a bonus problem so definitely hit the power alerts or whatever and then we'll power alerts or whatever and then we'll do one more time together if you feel do one more time together if you feel like this was too easy for you like this was too easy for you um and there will be one prompt that I um and there will be one prompt that I haven't seen before even though I don't haven't seen before even though I don't remember most problems but you know who remember most problems but you know who knows but inside the subconscious who knows but inside the subconscious who knows how those things work all right knows how those things work all right let's take a look today's Farm is let's take a look today's Farm is 134 gas stations or the end gas stations 134 gas stations or the end gas stations on a circular route on a circular route where the amount of gas is gas supply where the amount of gas is gas supply you have an unlimited gas tank that you have an unlimited gas tank that costs of course of I to travel from the costs of course of I to travel from the eye station to the next station you eye station to the next station you begin to drive an empty tank at one of begin to drive an empty tank at one of the gas stations given two images away the gas stations given two images away gas and costs return the starting gas gas and costs return the starting gas stations index if you can travel around stations index if you can travel around the circuit once in a clockwise the circuit once in a clockwise Direction otherwise we turn negative one foreign okay oh it's guaranteed to be unique okay I was gonna be like huh can you just do it for me everybody but yeah um what is does that mean so basically gas means that it costs oh no wait what is oh that's basically how much you get and then it costs that much um to get to the next one so in theory okay so the station three index three you fill up with oh this one index three and zero index is always weird when they say it like that but uh yeah so you start at four you use one and then you go five and you need to do two okay I think I got it now so the first thing to do is that we can do with a circular thing for this particular case we only need to go um we only need to circle around once so what that means is that and in this case there are constraints that they tell you for example that it's going to be unique and so forth so you can uh one kind of uh um I don't know if it's called I don't know if it's a hack but the way that I do it is basically doubled it away right um something like this away something like this away um you can think about wrapping around um you can think about wrapping around once just as you think about like for example you want to go from three all the way back to one you could also just think about it this way instead of doing physically manually running around and it'll make the map slightly easier maybe I don't know usually it does make the coding a little bit easier otherwise we wouldn't do it so okay so let's see so let's just say what current is your zero start is equal to negative I mean it doesn't really matter but also zero and then now we say n is equal length of gas uh and then now for for I in range of n we have g c maybe it's equal to gas up I COS of I every pie crust I never for enumerate okay fine let's do it with a numeral uh so we have something like that what uh so we have something like that what and then basically currently we we fill up right I guess just Gene we fill up and then we it takes us uh cost to go to the next one right and then now if current is less than I just want to make sure I'm off by One I just want to make sure I'm off by One cases that's what I'm reading on cases that's what I'm reading on um basically for example four then you um basically for example four then you use one and then you four by five and that's roughly why maybe maybe I'm off by one let's see um so if coin is equal zero then that means that the current one ended and then here we say start is equal to I and then here we say start is equal to I maybe or I plus one maybe I don't know maybe or I plus one maybe I don't know else else if if else then we just continue but we also else then we just continue but we also want to do a check where if want to do a check where if I minus start is greater than or you go I minus start is greater than or you go to n and this has to be the original N I to n and this has to be the original N I suppose then we can return I or we can recommend return start then we return negative one afterwards I think this is roughly right but I feel because basically you try to start at because basically you try to start at one it fails one it fails immediately and they've tried to decide immediately and they've tried to decide to segment of fails immediately and then to segment of fails immediately and then so that third one also fails immediately so that third one also fails immediately then four why isn't that working so four one five why isn't that working so four one five two two two and let's just print it out it's okay oh I am done I forgot to restart it to zero I was wondering why um almost like the other thing okay I've been making a lot of silly mistakes lately but this one's okay all right so let's give it a hmm I'm trying to think of it so I mean I think the the hardest point for me to explain this particular part is the one where um can you get to well no no okay so this is why this is up uh good in the sense that like you know one question that you might have is like well if you get to zero or if you get to negative at you know let's say you have five you know let's say you have five elements a b c d e or whatever let's say elements a b c d e or whatever let's say you got the negative here right you got the negative here right well yeah yeah let's say you got the well yeah yeah let's say you got the negative here negative here um and You Begin this segment you know um and You Begin this segment you know from ABC from ABC say right say right um um why do we reset a d and not at you know why do we reset a d and not at you know maybe B right so that may be one thing maybe B right so that may be one thing that you may ask but the the thing is that you may ask but the the thing is that we know that because that we know that because the pre um the pre um the precondition or the invariant of the precondition or the invariant of this thing is that going into C it was this thing is that going into C it was positive right or zero so that means positive right or zero so that means that going into c that going into c um it has a greater like has a positive um it has a greater like has a positive impact right meaning that okay with with impact right meaning that okay with with the and you know we we don't even have the and you know we we don't even have to I mean I know that we're talking to I mean I know that we're talking about adding and then subtracting so you about adding and then subtracting so you can think about as a deltoid away but can think about as a deltoid away but that means that if a plus b is going to that means that if a plus b is going to be be greater than zero greater than zero um um let's take a a really you know obvious let's take a a really you know obvious case where a plus b b is equal to case where a plus b b is equal to billion right so if it goes to a billion billion right so if it goes to a billion it adds to the negative value of c and it adds to the negative value of c and it goes to negative zero that means that it goes to negative zero that means that even if you take away the contribution even if you take away the contribution of a of a which by default also is going to be which by default also is going to be greater than zero B plus C is also going greater than zero B plus C is also going to be less than zero right so that's why to be less than zero right so that's why you're able to kind of reset it and set you're able to kind of reset it and set it at zero starting from D now going it at zero starting from D now going forward because we know that c is a very forward because we know that c is a very negative impact on the answer negative impact on the answer um okay I think now I believe that and um okay I think now I believe that and then now I can maybe submit and then now I can maybe submit and hopefully I don't make a silly mistake hopefully I don't make a silly mistake sweet uh 10 12 streak sweet uh 10 12 streak um yeah that's pretty much it this is um yeah that's pretty much it this is going to be linear time linear space going to be linear time linear space hope I don't have to explain it that hope I don't have to explain it that much uh why much uh why um the linear space well um the linear space well it's linear time and then your space it's linear time and then your space because we double the space uh the way because we double the space uh the way that I did it here but of course if you that I did it here but of course if you are very careful you can do this in all are very careful you can do this in all one space basically the same idea but one space basically the same idea but you know a little bit more careful like you know a little bit more careful like yeah I mean yeah you could just set like yeah I mean yeah you could just set like G as for example you can maybe just do G as for example you can maybe just do like a GC as you go to uh gasup I dot like a GC as you go to uh gasup I dot add or something like that right and add or something like that right and then of course you have to want to fold then of course you have to want to fold it twice or something but anyway so you could get this in constant uh space but yeah that's all I have for this one uh uh that's pretty much it let me know what you think stay good stay healthy do good mental health have a great weekend everybody I'll see you soon and take | 2024-03-21 12:05:20 | 134 | 134. Gas Station - Day 7/31 Leetcode January Challenge |
|
4jWjKrrDts8 | guys anyone ask you what is your path in life what is your aim in life do you life what is your aim in life do you have to clear your path right so that's have to clear your path right so that's a question this is in this question you a question this is in this question you will just play with the dot double dot will just play with the dot double dot and double slash if there is single dot and double slash if there is single dot in the string you will go to the current in the string you will go to the current directory if there is double you have to directory if there is double you have to move up double slash means single and move up double slash means single and anything other than that you have to anything other than that you have to consider it as a directory name here are consider it as a directory name here are the examples you are removing this you the examples you are removing this you are removing this you are removing this are removing this you are removing this and this right and and this right and let's go to solution solution is very let's go to solution solution is very simple we will just use a stack and you simple we will just use a stack and you will split the path with the use of will split the path with the use of flash so first slash Traverse okay every flash so first slash Traverse okay every element in the path and then there are element in the path and then there are two statements so the first statement two statements so the first statement will come to else if because if the will come to else if because if the element is not in any three of these element is not in any three of these then you will directly append the then you will directly append the element to the stack stating it as a element to the stack stating it as a directory now if it's very simple if the directory now if it's very simple if the stack is not empty and the element is stack is not empty and the element is equal to double dot then we'll simply equal to double dot then we'll simply pop at the last we'll just append the pop at the last we'll just append the result with the Slash and that's what result with the Slash and that's what I'm | 2024-03-20 11:28:02 | 71 | #LeetCode #71 #Simplify #Path #English |
|
0tantogp8fc | hi all welcome to learn code repeat so today we will be looking at day 11 of today we will be looking at day 11 of the october lead code challenge the name the october lead code challenge the name of the problem is remove duplicate of the problem is remove duplicate letters letters there are two problems in lead code one there are two problems in lead code one is three one six and the other is one is three one six and the other is one zero eight one zero eight one both are of similar type so let us look both are of similar type so let us look into the problem so problem states given into the problem so problem states given a string s a string s remove duplicate letters so that every remove duplicate letters so that every letter appears only once letter appears only once you must make sure your result is the you must make sure your result is the smallest in lexicographical order among smallest in lexicographical order among all possible results so this sentence all possible results so this sentence you must make sure your result is the you must make sure your result is the smallest in lexicographical order among smallest in lexicographical order among all possible results its kind of a all possible results its kind of a confusing statement but will look into confusing statement but will look into this with an example this with an example so here so here for example one it states that input is for example one it states that input is bc abc bc abc now among this the unique characters now among this the unique characters right are a b and c right right are a b and c right and and in lexicographical order that means the in lexicographical order that means the sorted order of sorted order of ascending characters right it will be a ascending characters right it will be a b and c so that's the output here abc b and c so that's the output here abc and the other input is this will look and the other input is this will look into this example into this example but before that the constraints that but before that the constraints that have been provided is s dot length is have been provided is s dot length is greater than or equal to 1 and less than greater than or equal to 1 and less than equal to 10 raised to 4 and s consists equal to 10 raised to 4 and s consists of lowercase english letters so let us of lowercase english letters so let us look into example 2. look into example 2. so here in this example right we have c so here in this example right we have c b a c dc right so the unique letters are b a c dc right so the unique letters are a b c and d these are the unique a b c and d these are the unique characters right characters right now here now here when they say lexicographical order when they say lexicographical order writer they mean that writer they mean that the output should be such that the the output should be such that the character order in the string should not character order in the string should not change so here change so here the character is a is appearing here the character is a is appearing here right it should not change at the same right it should not change at the same time we should select unique characters time we should select unique characters in our output such that in our output such that the smallest in lexicographical order the smallest in lexicographical order should be selected first right what i should be selected first right what i mean by that is now here in the string mean by that is now here in the string right if i do not change the order but right if i do not change the order but still i want to select all the unique still i want to select all the unique characters right what are the different characters right what are the different outputs that i can get outputs that i can get so here one is c so here one is c p a p a and then there is d and then there is d so here so here if i select this red that means c b a if i select this red that means c b a and then here d because c was already and then here d because c was already selected so i won't select again selected so i won't select again again c b c it was already selected here again c b c it was already selected here so i won't select again so when i select so i won't select again so when i select d d and this is the same sequence of order and this is the same sequence of order in the string as well right c appears in the string as well right c appears first then b then a and then first then b then a and then d appears right so this is one sequence d appears right so this is one sequence and we are including all the four and we are including all the four letters that is there in the string s letters that is there in the string s right all the four unique letters we are right all the four unique letters we are including here including here the second sequence that we can have is the second sequence that we can have is i can select b here and then a then c and then d right this is second sequence and the third sequence is if i ignore c and b then i can select a then c d and b right the fourth one i can do is i can select a d c b and the fifth one can be a d b c right so i selected a d b c so in all this if you see i have made sure that there are only unique letters and all the unique letters are included in this right now among this results right which one is the lexicographical order the most lexico graphical order that means the smallest character should appear first and then the next largest and then the next largest so which gives us the best lexicographical order right so here obviously since a appears first c and b we cannot take this into account because a is the best lexicographical order that we can have among these three right if you see after a we have c here and here after a we have d right now c comes before d so i cannot use this now between this 3 and 5 right a c d b and here a d b c so obviously c comes before d so we cannot use this as well so this will be the final output that i need to select and that is what here they are expecting acdb okay so now let us look into the logic how we can build this right so what we can do is we can go through this string and since we want to get the unique characters right at the same time we want to keep the lexicographical order right so when we go through the string right if you want to skip a particular string right i can only skip it if i know there are multiple different occurrences later on in the string so for example if i am going from left to right here right and let us say i want to skip c i do not want to consider c here now then i can only skip c if i know that c is available later on in the string otherwise i cannot write so first step will be to know that right we need to know the how many numbers of that letter is present in the string right so first step will be i will build a frequency map ok first is frequency map i will build so once i build this frequency map so i will go through c so i know that for c there is one two three four there are four c's for b there is one two there are two b's and for a there is one a and then we have d there is one b ok so once i have the frequency map then i can go through the string and build the final output string right and during that process i can check whether the previous one that i added is greater than the new character what i mean by that is let check this right if i am going through the string from left to right right so let us assume that i include c in my final result right then i go to b i will check whether my current character is less than my last character in the result so my previous character or the last character in the result was c now c is greater than b that means my current character is less than my character in the result right now i can start my result with this current character which is b only if i ignore c okay and i can ignore c only if i know that c appears later on in the string right so for that i will check my frequency map okay i will check if i can decrement the count and still it will be greater than zero so i will decrement the count by one and still it is greater than zero so from the result i will remove the last entry and add my current character which is now b current character is b okay now i will move to the next character which is a okay now here if i see i can only include a if my previous result is less than my current character okay now here a is not less than b so i need to remove b now i can remove b if i know my frequency map if i decrement the value it is still greater than zero so if i decrement it will become one it is still greater than zero so i can remove this b and i can keep my result as a okay so the steps that i am doing here is add the letter in result and check if last character is so my last character should be less than current care in my let's say string is s so in measuring s so last character of result should be so last character in result is less than current character if not remove the last character of the result if the last character appears later on in the string that will come to know using the frequency map here right ok so let us say we added now a and then again we get a c my next current counter is at c i will check whether i need to add c right i'll check whether c is less than my last character its it is not so i can directly add c without removing the last character now before adding c right i also need to make sure that whether that character is already present in the resultant because i need to form a unique result right so for checking that i can have like similar to frequency map i can have a unique set or a unique array since it is given that its only 26 characters so i can use a boolean array to check if current character is added already so if current character is already added then i can directly skip it else i can add the current character so since c was not added i will add the c now then i will go to the next character which is d again d is greater than c so i do not need to remove anything i can directly add d and also d is not already added in the boolean array so i will add d so here as and when i am adding to the result right this is my result string so as then when i am adding a character to the result string i will also add the same character to my boolean array ok and similarly when i am removing any characters i will also mark that character in my boolean array as false okay that i have already removed i am not using it so here now we have added a c d now again c comes in my current character is c i will check in my boolean array that c is already present so i will skip that c now my current character is b okay i will check in my boolean error that b is not present then i will check whether my b is greater than d which is the last letter of the result it is not greater than d then i need to remove the last character provided there is more occurrence of the last character in the shrink later on in the string and that we can check if we decrement the value and the value is greater than zero so here the last character is d if i decrement the value of d here it is not greater than zero so we cannot remove this value ok so since this value cannot be removed we will keep this value as is and we will add the current character here as is okay so we will add ac db and then i will move to the next character now next character is c c was already there in the result so i will ignore this so that way my final result is ac db which is same as this okay so for doing this operation right we were removing the last character and then we were adding right so the data structure that supports this in a o of one time right is either you can use a linked list or you can use a stack right so if for example if you are using linked list you just need to remove the last character from the list that is of one operation right so if you see we are going through all the characters of the string array so that is o of n time and the additional space that we are taking is for the boolean array and for the frequency map right so in worst case that also will be o of n so we are taking off n time and o of n space here so that will be the complexity so let us code this logic that we have here and while going through the code i will again explain the steps that we performed here so that way you will be able to relate this logic with the code logic easily let us look into the code so the first step we had was building the frequency map so for that i will define int array since we know there are only 26 characters lowercase characters so i can define a in frequency array of 26 characters so i will go through each and every character in s and build the frequency map so what i am doing here is i am incrementing the value of the frequency array for that particular character position minus a so if the character is for example c so it will be c minus ascii code of a so here ascii code of small c is 99 and ascii code of small a is 97 so it will be 99 minus 97 that will give us 2 so at index two it will increment the value ok so c will be index two because it is the third character and since we are using zero index so it will be index two ok so that way we are building the frequency map here so once we build the frequency map we will go over again in a for loop through this letters and we will need a boolean array to check whether the characters were already added we will need a linked list to form the final result so first we will decrement the frequency of this character so as and when we are going through each character we will also decrement the frequency so whether we are using it or not we are already passing through that character so that frequency of that particular character needs to be decremented from the frequency map right frequency of ch minus minus so i am decrementing the frequency now i will check whether the character was already added so by default since its a boolean array by default the values will be false and i will make it true only when i am adding that character to the result right so here if it is already added then i can continue with the next character now i need to check whether this current character is less than the last character in my result list right so i'll check if my result or get lost the last character of the result if that is greater than my current character and if i have more of the current character later on in the string right so that we can only check from frequency map so the current frequency is greater than 0 for that particular character so that means the current character appears later on in the string as well in that case we can remove the last character from my result right so in this case i can directly do result dot remove last okay now since i am removing this last i also need to make sure that this added is turned back to false right so i will also do is added so result remove last will not only remove the element but it also returns the element that is removed so i can use this as is and say that this is false so this will also remove it and also make it false in the is added array okay now here this can only happen if the result is not empty right so we have to add that check as well that result is m t should be false okay now here if i remove the last element right what if the second last element so after removing the last element the new last element is also greater than c in that case also we have to do the same step again right so here sort of if it should be y that means we have to do the same step again and again until my last element in the result is less than the current c h and also provided the frequency of the ch is still greater than zero only then i can afford to remove that character okay actually i am removing this large character right so i need to check the frequency of the last character not the frequency of current character c h is the current character so here it should be frequency of get lost so i can only remove that last character if the frequency of that particular character is greater than 0 that means that character is appearing later on in the string so i can remove it now okay so once i do this after that i can add the current character in my result and since i am adding the current character i need to update the is added for the current character so once i do this in the for loop the remaining result will have the unique character set so at the end i can directly form the string from the remaining result here what i can do with a string builder and then go over the linked list so while result dot node is strp dot append strp dot append i will do a result dot i will do a result dot remove first so i am removing the first element from the result and adding it into the string builder so i am doing this until my result is not empty and at the end i can return so let us run this code and the code is accepted and the code is accepted and as i said the time complexity of and as i said the time complexity of this will be o of n and the space this will be o of n and the space complexity since we are using o of n complexity since we are using o of n space so the space complexity is also o space so the space complexity is also o of n of n i hope you like this video please do hit i hope you like this video please do hit the like button and do subscribe to the the like button and do subscribe to the channel for future such videos thank you | 2024-03-24 10:22:19 | 316 | Remove Duplicate Letters | LeetCode 316 & 1081 | October LeetCode Challenge | Day 11 |
|
vdJDIMdSihE | foreign [Applause] code called validate binary search tree it is a medium let's get right into it given the root of a binary tree determine if it is a valid binary search tree a valid BST is defined as follows the left subtree of a node contains only nodes with keys less than the node's key the right subtree of a node contains only nodes with keys greater than the nodes keep both the left and right subtrees must also be binary search trees so we have sort of this recursive definition here and if we go to example one we have the root node two the left child one and right child three and here we output true because the left is less than the root and the right is greater than the root and notice here it says less than or greater than it needs to be strictly less than or strictly greater than it can't be equal to and example two we have one five three four six the left child is less than the root so that is valid but the right four should have been greater than five but it is less than it so we output false now this is actually pretty simple and straightforward as long as we know what a binary search tree exactly is so if you know what binary search is this is very similar to that so in a binary search I would have say the following ordered array with indices going from 0 to 10 which means I know I have 11 elements and what I want to do for this is look for say a Target so I'm looking for 11 performing a binary search the first thing I do is I split that array straight down the middle so this is where I would be splitting and I would compare that value with my own I know that mine is greater than the value that I see here so I need to look in the right half that is where my values would be so when I take this half and I split once again right down the middle and I compare once again the value that I'm seeing with the value I have mine is less than the middle so I now need to look into the left of this new hat so what I'm doing is the balance are getting smaller and smaller every single time and that's exactly what we're going to do with the binary search tree it's the same concept instead of an array we have a tree and instead of splitting at the midpoints we sort of split up roots and we're guaranteed that everything to the right of our root node has to be greater than it and everything to the left has to be less than it now let's take a look at an example with an actual troop so I have a tree here and I want to fill out values to make it valid so for my very first Top Root node what values can I put in here there's no restriction so my range can be from negative Infinity so negative Infinity all the way to positive Infinity there is no bound no restriction for my first root note so negative Infinity all the way to positive Infinity say I go with 10. so this is my root node this means that my right child has to be greater than 10 so it can go from 10 all the way to infinity and same thing for my left which would range from negative Infinity so negative Infinity to 10. it has to be less than 10. so what values can I actually pick anything greater than 10 say I go with 20 and anything less than 10 say I go with 4. these are within bounds so they are valid now for the right child of 20. we're going to have a tighter bound this time around because not only does it have to be greater than 10. it now also has to be greater than 20. so here it needs to be from 20 all the way to Infinity these are the values that I can pick between so I'm going to say this is 40. what about my left child the left child of 20 has to be less than its root so it needs to be less than 20. but remember this all was the right subtree of 10. so it needs to be greater than 10 but less than 20. so the bounds are going to go from 10 to 20 and of course this is non-inclusive so these are what my bounds are I can pick between I'm gonna go with say 12. and same on the left side right the bounds over here would be from 4 because it is the right child it needs to be greater than four but it still needs to be less than 10 it's still Bound by the parents right bound as well so we're just making it tighter instead of going from negative Infinity to 10 it now goes from 4 to 10. so 4 to 10 let's say we go with 6. and same thing over here the bound instead of being from negative Infinity to 10 it is the left child of four so it needs to be from negative Infinity to four and say we go with two so these are my values and Bounds let me also write these out okay so I just went ahead and rewrote all of the values with the bounds in place now let's take a really quick recap at the top we have our root node 10 that falls between negative Infinity to positive Infinity so no real bound there the right child of 10 we know has to be greater than 10. these bounds are not inclusive so it needs to be greater than 10 and it can go as high as possible and 20 is valid it is greater than 10. 10's left child needs to be less than 10 so that is our bound and 4 is valid now 20s right child not only does it need to be greater than 10 it also needs to be greater than our own root value than 20 is a value so it needs to be greater than 20 and it is 40 is greater than 20. so this is valid as well now 20s left child it needs to be less than 20 because it is the left child but it needs to take into account its own bounds that it gets from 20. it needs to be greater than 10 but less than 20. and 12 Falls within that range so it is good as well now 4 is right again it needs to be greater than 4 it is the right child but it is coming from its own bound which needs to be less than 10 right this whole thing is a left subtree of 10 so it needs to be between this range this bound and 6 Falls between that so it is valid as well and over here Four's left child it needs to be less than 10 but also less than four so the total Bound for that becomes less than four which it is 2 is less than four so this whole tree is valid now what do we notice here right every time we have a child it's taking the root node as one of its bounds so the right child of 10 needs to be greater than 10. the right child has its node parent node as it's left about the left child has the parents node as its right bound and again here right the right child of 20. has 20 as it's left bounding to be greater than 20 and the left child of 20 has 20 as its right bound it can only be as big as 20. same thing here we have a root note of four and if you are the right child four is your left bound you have to be greater than four and if you're the right child four is your right bound you need to be less than four so what we're going to do is I'm gonna iterate through our entire tree in order to check validity we're going to be passing in our root value as one of those bounds and keep the other bounds as is because that's the only one we're getting tighter on and we're going to do this for every single node all the way down and if at any point we break that bound we know we need to return false if we've gone through the entire thing and everything is valid then we would return true that this whole tree is valid so let's go ahead and total this up then run through a super quick example now this is a binary search tree and four trees the best way usually to iterate through is to use a recursive DFS approach so to do that I'm actually going to write a helper function first so this is going to be my helper and I'm going to take in my route and what else do I want to take in I want to pass in the bounce each time I want to make sure my root value stays within that so I'm going to be passing any left and right about now with a recursive solution you want two things the base case and the recursive case so for the base case what is base case number one what happens if the root that I'm passing in doesn't exist if it's non-existent it can't be not valid right so if root is none we would return true and what this means is we've gone through every single node in our tree and we've reached the end we've gone past the child past the leaf node so a leaf node is any node that's not having left to right child we've gone past that which means if we've made it that far everything we've seen up till now has been valid and we would return true now when do we return false well every time we want to make a check if our root is within bounds right so we want to see if left is less than our Roots value and is Our Roots value less than right and this is not true so if this condition does not hold then we know we're not within bounds and we would return false now we know our root Falls between these bounds if it has not exited either of these if conditions now we want to check our child notes so we want to check both left and right children and see if they both return true so for that I am going to say we want to return self.helper on root dot left so I'm calling with my left child first and what are the bounds that I'm passing I am passing in the same left bound that I have from my parents if I'm a left child I have the same left bound as my parent so I'm going to be passing it left the only thing that is changing is the right bound right that is going to get tighter and that's going to take our root nodes value our appearance value so this is going to be root dot about this is getting tighter so if this is true and if my right node is also true so solve dot helper on root dot right and what am I passing in for my left bound if I am a right to note I am getting tighter on my left bound right if I'm a right note right here I'm getting tighter on my left bound because there's a new value that I need to be greater than so I'm going to be passing in root dot vowel that parent node for my left bound I need to be greater than this new left and my right can say what it was from my parents so that is going to be right exactly what we're passing in because this is going to remain unchanged the right bound remains unchanged and if both of these return true then we would output true if either returns false we output false because of this and operator right here and that is our helper function what are we going to call it with we pass in the very first note so we're going to be calling this helper with our root node so root and what are my initial left and right balance well that would just be negative Infinity so negative infinity and floats of positive Infinity let's go ahead and run this code long answer I actually don't have a return here so all right that is accepted and we can go all right that is accepted and we can go ahead and submit this and it is accepted ahead and submit this and it is accepted as well so we're talking about space and as well so we're talking about space and time complexity we are going to be going time complexity we are going to be going through every single node so fourth time through every single node so fourth time that would be o of n because we want to that would be o of n because we want to check if every single node is valid and check if every single node is valid and for space our recursive call stack could for space our recursive call stack could be as big as the number of nodes in our be as big as the number of nodes in our tree so that is also over and over space tree so that is also over and over space now let's super quickly run through a now let's super quickly run through a quick example just so we can see how our quick example just so we can see how our code is running line by line I'm code is running line by line I'm actually going to be taking example two actually going to be taking example two and modifying it just a little bit so I and modifying it just a little bit so I have the root Note 5 and have one six have the root Note 5 and have one six four three so let's start at the very four three so let's start at the very beginning and just go through this line beginning and just go through this line by line the first thing I do is I call by line the first thing I do is I call my helper function with my root node my helper function with my root node being passed in so I'm calling puffer being passed in so I'm calling puffer with my not being passed in negative with my not being passed in negative infinity and positive Infinity these are infinity and positive Infinity these are my left and right bounds I'm just going my left and right bounds I'm just going to write this out so it's a bit clearer to write this out so it's a bit clearer so I have group and five left this and a so I have group and five left this and a right being this now I'm in my helper right being this now I'm in my helper function and I see if my root is done I function and I see if my root is done I would return true root does exist so would return true root does exist so it's not none now I want to check these it's not none now I want to check these bounds does my value fall between these bounds does my value fall between these bounds it does so now I'm going to be bounds it does so now I'm going to be calling the helper function again calling the helper function again with my left and right child so what is with my left and right child so what is the left child of my root node five well the left child of my root node five well that would be one so I'm passing this in that would be one so I'm passing this in with one with one and my left would stay negative Infinity and my left would stay negative Infinity that bound stays negative infinity and that bound stays negative infinity and my right updates to the value of my root my right updates to the value of my root so that would be 5. and I would call the so that would be 5. and I would call the helper again with my right as well so helper again with my right as well so that would be six that would be six root dot vowel so the left bound becomes root dot vowel so the left bound becomes five and my right bound would stay five and my right bound would stay infinity and since we read left to right infinity and since we read left to right we would solve for this first so we're we would solve for this first so we're calling helper again with root node one calling helper again with root node one left being negative infinity and right left being negative infinity and right being 5. being 5. now I go into this condition once again now I go into this condition once again root is not none and one is between root is not none and one is between these two bounds negative Infinity is these two bounds negative Infinity is less than one and one is less than five less than one and one is less than five so now I call helper again passing in my so now I call helper again passing in my left and right children so left and left and right children so left and right children of one are none so I'm right children of one are none so I'm just going to be passing them in and the just going to be passing them in and the left bound for the theoretical none left bound for the theoretical none would be the left so that would be would be the left so that would be negative negative infinity and root dog vowel which is one infinity and root dog vowel which is one and I'm passing in with my right which and I'm passing in with my right which is also none root dot val which is one is also none root dot val which is one and infinity and infinity so I'm reading this left to right I so I'm reading this left to right I first call helper with these values I first call helper with these values I have root equaling none left being have root equaling none left being negative infinity and right equaling one negative infinity and right equaling one now what we're in this condition and now what we're in this condition and root is none so I would return true so I root is none so I would return true so I return true for over here and I can go return true for over here and I can go and make this call again but I know this and make this call again but I know this should be returning true because the should be returning true because the root would be none so this would also root would be none so this would also return true that means that this whole return true that means that this whole call up until one this whole thing would call up until one this whole thing would be true because we have returned true be true because we have returned true and true and true and this call we bubble all the way back and this call we bubble all the way back up would be true so the left child would up would be true so the left child would be true now we want to call this with be true now we want to call this with our right so now we want to call it in our right so now we want to call it in with six with six which would be helper with the root which would be helper with the root being six left being five and right being six left being five and right equaling Infinity equaling Infinity we go into this helper function and root we go into this helper function and root is not none and now we want to check the is not none and now we want to check the balance balance is left less than the value which it is is left less than the value which it is and is the root value less than the and is the root value less than the right bound that it is so now we're right bound that it is so now we're going to be calling our left and right going to be calling our left and right helpers so I'm going to be calling with helpers so I'm going to be calling with my left child so left child of six is my left child so left child of six is four the left bound stays what it is four the left bound stays what it is over here so that would be five and my over here so that would be five and my right bound what I cannot be greater right bound what I cannot be greater than would be my current node's value so than would be my current node's value so six so I need to say between five and six so I need to say between five and six and for my right child I am passing six and for my right child I am passing in my right node so that would be three in my right node so that would be three my current value so 6 I need to be my current value so 6 I need to be greater than 6 and my right bound which greater than 6 and my right bound which is infinity I need to be less than is infinity I need to be less than infinity infinity So reading love story again I will be So reading love story again I will be calling with this right over here so I'm calling with this right over here so I'm calling with my root node being 4 my calling with my root node being 4 my left Round being five and my right bound left Round being five and my right bound being six I go into this helper root is being six I go into this helper root is not none so now I'm in this if condition not none so now I'm in this if condition is my left less than my root value that is my left less than my root value that is not true right left is not less than is not true right left is not less than my right so I would return false over my right so I would return false over here once I return false I can actually here once I return false I can actually bubble back up to this color and say bubble back up to this color and say that this is false at this point I don't that this is false at this point I don't even need to call this Helper and have even need to call this Helper and have it figure out if it is true or false I it figure out if it is true or false I have one false so that means this whole have one false so that means this whole thing evaluates to false and I bubble thing evaluates to false and I bubble this back up to my color which is false this back up to my color which is false so this whole thing so this whole thing is now false true and false would equal is now false true and false would equal false and I would return false because false and I would return false because this is not valid four should have been this is not valid four should have been greater than 5 and less than six greater than 5 and less than six obviously this wouldn't be an integer we obviously this wouldn't be an integer we can see that this already breaks but can see that this already breaks but this would be false and that is what we this would be false and that is what we would return would return so this is how we would validate a so this is how we would validate a binary search tree if you have any binary search tree if you have any questions at all let me know down below questions at all let me know down below otherwise I will see you next time | 2024-03-20 13:46:30 | 98 | Validate Binary Search Tree - LeetCode 98 - Python |
|
pOlA8FZmC0Y | This [music] [music] point lungs and sunscreen in this question I have given you a string which will only visit someone will keep given you a string which will only visit someone will keep mother will edit content from zero to nine mother will edit content from zero to nine this is ok now what is the use of it this is ok now what is the use of it see you tell on this any see you tell on this any servicing servicing servicing I caught your reception, now whatever numbers are there in it, the number of years the commissioner has showered on it, it has to be made on these ROMs, okay then some will be able to become servicing, some will not be able to become, what should I tell you that friend, the Which Which Which can become the first film, okay with these flights ware can become the first film, okay with these flights ware Shyam friends, now how much love can you have, then Shyam friends, now how much love can you have, then look at this sticker, it look at this sticker, it will be seen as Samsung will be seen as Samsung 214 2418 214 2418 What gas can I wrap in space, so What gas can I wrap in space, so basically duty then here to two and basically duty then here to two and here here here Edit: This is a ROM so its length becomes 5ghz. Why is this my answer because there was no one else on this page who can make a calendar of length more than 5, So this is my So this is my So this is my answer, there is no reaction on doing this answer, there is no reaction on doing this and the number of behavior you can do is so big, and the number of behavior you can do is so big, if you look at some more examples, if you if you look at some more examples, if you get some time like this get some time like this 1234 1234 560, then only one court will become soft on this first, 560, then only one court will become soft on this first, hold some back, you one. hold some back, you one. hold some back, you one. I take two as hang, then two will become Passion Pro m1 length, you add, so basically the length of all this screen is one, that is my Ki Reddy, I have to find you a long serving, how many times should I lift it and open loop is But look at But look at But look at 2068 here, 2068 here, how to scan Jatin happens, basically you how to scan Jatin happens, basically you can see so many and 212, this is first tight in this row, then the can see so many and 212, this is first tight in this row, then the answer will be three, it is answer will be three, it is okay, this question is two, this trick will have okay, this question is two, this trick will have only visits from zero to K only visits from zero to K line and line and line and comes from one to five according to. Okay, so you can try it from now. Let's switch on to solve. When can any spring balance ROM be made? What is the property of electric param? There is something in it which is called two There is something in it which is called two There is something in it which is called two three legs, it is not a pearl drop and but okay, three legs, it is not a pearl drop and but okay, it is proved that now you can do these flats, it is proved that now you can do these flats, then you do something like this, 2308 youth gone, all the characters in this pen, is is is torch light 2b again three twice hiv torch light 2b again three twice hiv two times here if it was on again then two times here if it was on again then put four four bugdi in the plane room now so if put four four bugdi in the plane room now so if any substring it any substring it has ABCD of some strings here then if has ABCD of some strings here then if I say that so many I say that so many I say that so many spring that all the guys, if number and times are even then you can make it a calendar. You do not have to show the height by making an Israeli panel, now you You You You can do it, okay, another can do it, okay, another pan is heated in it, which is called two three pan is heated in it, which is called two three loot loot 518 so many people with the number love and there 518 so many people with the number love and there is one more person along with it, so you and welcome is one more person along with it, so you and welcome make it central and make it central and 4321 people will go next to him, this is also a 4321 people will go next to him, this is also a calendar, this calendar, this calendar, this one guy is just different Even on flash lights If still and number track Thought 24 forced Two three for four Can be any four On this 4 is what it is Five Can be any four On this 4 is what it is Five behavior all the rest twice again Pet is from one number, so now basically my question is Pet is from one number, so now basically my question is who has been completely reduced, so I have who has been completely reduced, so I have a brief sample on my string, there is a brief sample on my string, there is every possibility in my chemistry in which every possibility in my chemistry in which all the elements are repeated even number of times, all have an even all the elements are repeated even number of times, all have an even number of repeats or number of repeats or number of repeats or time or all the events except one more person, then okay then it is fine, we can do this, okay, then look at every point, okay, then look at every point, whatever I pin is at this point. whatever I pin is at this point. whatever I pin is at this point. once from us on this point three more number from time and two more numbers from obscene speed and go ahead free 21 4545 and tree that there is something like this then this point if you directly then It has arrived It has arrived It has arrived here, I am confident, it is completely fine, it is okay, 3rd here, I am confident, it is completely fine, it is okay, 3rd November, I will have to cry to November, I will have to cry to get over it, okay, three, now there is get over it, okay, three, now there is another number, and the number, time, SIM, is another number, and the number, time, SIM, is with it, with it, and whatever it is, it is again or and whatever it is, it is again or and whatever it is, it is again or or that too add and this guy at two o'clock and the number is time so for that if there are two more guys then he can send you a comment then so much prefix is wrong I will do that I will have to submit something like this If I remove it then three If I remove it then three If I remove it then three events are created or two events are created. Okay, so events are created or two events are created. Okay, so how can I make this work? how can I make this work? Look at this post, basically three more numbers from Look at this post, basically three more numbers from Sa and the rest are 245, all these are Sa and the rest are 245, all these are zero legs. zero legs. zero legs. tight, all these guys are fine with the even number time, so the number track they feel and the total overall marriage number time, now you will get it out this year, even then, after getting out of this year, whatever number Remaining joint account that too one lokay good ok but there is free speaker here and number 17 tight and number matters and we take 5 told me that even on this much portion no three and number friends I would have been one traveler Okay, if you remove Okay, if you remove Okay, if you remove three accounts on this, how many degrees will go, then five will go to three accounts on this, how many degrees will go, then five will go to 142 or 5 will go to free two or 142 or 5 will go to free two or 5150 will go, whatever degree will be formed there. 5150 will go, whatever degree will be formed there. Okay, so if I work on this then There is some There is some There is some configuration like this, there are two more people, okay, so configuration like this, there are two more people, okay, so to remove three, I to remove three, I need some traffic in which three more number are need some traffic in which three more number are friends and all the other people are event number, friends and all the other people are event number, timezone, okay, if anyone else, tell the order here, but for timezone, okay, if anyone else, tell the order here, but for example, if there is powder example, if there is powder here. here. here. come here once and there tell me if an ad is coming then if you remove so many sequences and do something like this intermittently here and there then send the fiber. Had it been even then it would have become more. My work would have got spoiled because I had created one and the other one was created. Okay, okay, now the Congress has come back to do what I have to do. What is the basic thing? Look at the current situation, how many people are there, how many Find out if there is an app, either Find out if there is an app, either Find out if there is an app, either celebrate Eid to all of you, meaning three and two, this is a celebrate Eid to all of you, meaning three and two, this is a day and make it number wise, Dad, day and make it number wise, Dad, I need a fee point like this, there are I need a fee point like this, there are three more numbers, Times also has two more numbers, three more numbers, Times also has two more numbers, legs and remove that. legs and remove that. legs and remove that. should be whatever life is, is the light okay or else or what can you do? The first person reached Shraddha and the second person said that you leave one more person and organize the event for all the others. It was admin sir. was admin sir. was admin sir. or make it an event. Okay, so Abhinav, let's take an example. It's okay after applying it. If this oil strainer had been given to me, then look at this point or see how many times the Sun Temple is there in the traffic of this point. So on this basically two has come once and number times is every third number and again or even times and torch light so if I have to have so many segments torch light so if I have to have so many segments in the calendars then basically ending on this in the calendars then basically ending on this One substring to do is okay, from One substring to do is okay, from here onwards, I will have to make here onwards, I will have to make these two more guys one here these two more guys one here or at least one will or at least one will have to be made one, light or what is the one more addition have to be made one, light or what is the one more addition that you can do in these that you can do in these you can order something from here, this is also your choice. Okay, let's see now what else can I do to make both of them even. So now what Look at the location, there Look at the location, there Look at the location, there are two here and also three from number time and are two here and also three from number time and number time set, so so many tourists, number time set, so so many tourists, remove so many parts from these, okay, remove so many parts from these, okay, so these two and the number that is their account, so these two and the number that is their account, this event will become this change. this event will become this change. this event will become this change. okay, so basically, you will only get this wisdom, how many front row torch lights are there in such big cities, and now if this course is done on all of us at one time, then you can paralyze us by cleaning it, Substring Substring Substring will be this then ignorance one and can say will be this then ignorance one and can say that now I will that now I will try to change one of the two I do something Can try to change one of the two I do something Can I create an event by changing these three If there will I create an event by changing these three If there will be one more then it will work Okay so be one more then it will work Okay so basically I will get such a sequence basically I will get such a sequence basically I will get such a sequence people are even times on please, that and times are tight, here two is that and time is here, tight, here two is that and time is here, two is here and time is is three and time is two is here and time is is three and time is no breast cancer which has no breast cancer which has three jo in its prefix. three jo in its prefix. three jo in its prefix. times the van coming back only three, here there were three more but also two more a bit tight remove this which will make both of them ok then this is not possible now you could not do this ok ok can I do this can I do this Now find such a sequence Pichola Now find such a sequence Pichola in which there are two places and times and here it is in which there are two places and times and here it is and tank right if you give this much papad then the remaining and tank right if you give this much papad then the remaining portion will be left here, you can change it to kheer portion will be left here, you can change it to kheer pantro and make the team mute pantro and make the team mute 245 are two times 4455 something is clear 245 are two times 4455 something is clear now let's take one more task and now let's take one more task and examples and to see this we will have to change it a bit, examples and to see this we will have to change it a bit, here I have here I have put it 13 times, I am okay, let's do put it 13 times, I am okay, let's do 13 outside the last two times, If there is electricity juice, then If there is electricity juice, then If there is electricity juice, then six will also come here, see from the given time, six will also come here, see from the given time, we had taken two cords before, we had taken two cords before, eat this, we new this too, celebrated this too, if so many eat this, we new this too, celebrated this too, if so many scams have happened, then it will be done, if it has to be scams have happened, then it will be done, if it has to be made in just two people, then that too will be done. made in just two people, then that too will be done. Remove so many ideas, now look at what has been mentioned, Remove so many ideas, now look at what has been mentioned, I will add to this also, I will also describe this I will add to this also, I will also describe this along with it, any one more reason out of these along with it, any one more reason out of these will do, okay, no forward will do, okay, no forward can be made in this and if we had to make another one, can be made in this and if we had to make another one, then we have the sequence of electricity, that. then we have the sequence of electricity, that. then we have the sequence of electricity, that. number times are these and number friends and also call on four more numbers ok ok and if you remove the point on number times even then it becomes Lovers are going to score a lot this is three more times from this many times three more times from this many times three more times from this many times torch light, if I remove so many people, then give me more number permissions and he will become the same. If I remove this much, he will become Bigg Boss 30 more times. The form here will not matter because there are not only so many fans but And tension, yes, it changed with the intake And tension, yes, it changed with the intake And tension, yes, it changed with the intake and it will become right, all the guys here, if there is and it will become right, all the guys here, if there is one more guy from the given time, then you can use the SIM, okay, it is fine, okay, it is fine, but again how will I do it in the work, everyone, but again how will I do it in the work, everyone, I have to maintain the account and keep it. I have to maintain the account and keep it. When time you all type When time you all type that if you do it amongst each other then it is on Sunday that if you do it amongst each other then it is on Sunday everyone will have to do it first consider the estate everyone will have to do it first consider the estate if one person has some configuration like this then if one person has some configuration like this then switch off next switch off after doing full test such switch off next switch off after doing full test such anger infection is this end anger infection is this end square's he will go square's he will go New, this is what we don't want, so now we are New, this is what we don't want, so now we are going to do this, now basically this circular going to do this, now basically this circular pattern, we will make only that an accident, let's see how by using bread, so now I am going to see how by using bread, so now I am going to put the states in an intermediate form put the states in an intermediate form like here. like here. like here. multiple with the right on the interior, here at that place, this need will be erased, intact, I am pleasing 12345 Sitam is so beautiful, okay, so here, I will have sacrificial youth, I will give them the That element event has That element event has That element event has come, the number of one means that element and come, the number of one means that element and time are shadow. time are shadow. Okay, so if this situation had to Okay, so if this situation had to please me at a distance of one number, then please me at a distance of one number, then what would I have done? You are here and time has come, the what would I have done? You are here and time has come, the tube has become yours or cotton. tube has become yours or cotton. tube has become yours or cotton. and this is the tabs from one time which is 520, this is business, this is also zero times, one is not here even once or is it a product and does not cry, okay so all the other 10 are that point. Whatever else is inside, there is only one number here. Now see how our work gets reduced. If you represent everyone on this phone, then let me find you a CR. Friend, if you want to make all the brothers PM, then it is okay to Two, right Two, right Two, right now, you have to now, you have to make both of them PM from Android. You need some make both of them PM from Android. You need some sequence where all the even number sequence where all the even number times should be only two and three and you times should be only two and three and you need exactly the same condition, tight all the need exactly the same condition, tight all the people are 09 times and here one here. people are 09 times and here one here. people are 09 times and here one here. one at the same position earlier also somewhere on the set. Okay, so for now you just need to friend only one number, the interior number. If you find it at any position then your work is done. You will get this 1GB. This is one. Good excuse will be made, the other way was that and you close one, basically you have to do these two, okay here but apart from this you can do any one, so if I should do this, what Those who want to do that Those who want to do that Those who want to do that I am talking I am talking that these two and number lovers along with six that these two and number lovers along with six more numbers will more numbers will become time pod, the result like that will also become become time pod, the result like that will also become then good morning, the second option is if you do then good morning, the second option is if you do n't do anything else, cover it and n't do anything else, cover it and call me now on 25 call me now on 25 call me now on 25 point out this sequence, does it add anywhere first or not? Okay, don't do this and this also. Do this and this instead of this and here. ₹ 1 instead of these two. If you don't do this and this also then now it is Come, if you say that friend, Come, if you say that friend, Come, if you say that friend, I have made one person an event, leave him alone, dial him, we are installing electricity here, I have made dial him, we are installing electricity here, I have made all of them one, all of them one, it was being shut down, so it was done. it was being shut down, so it was done. it was being shut down, so it was done. zero size, it has become like a hero, now one, you are making it zero, I am now more like, yaar png, such a sequence and here 3 even numbers are fine from the time, so if this let's support had come here seven times, then I am removing the audience of even number times. If I remove four then again Sarveshwari Question 19 currency will be left. Now all my efforts have come on Sachin. You just have to search this number You You You can use an SMS which will give you the course morning of this number can use an SMS which will give you the course morning of this number an inquiry into it an inquiry into it then okay then okay okay so again what do you do here okay so again what do you do here you strike all the different possibilities you strike all the different possibilities right you have from zero right you have from zero to nine cactus become to nine cactus become Okay, so keep making all of them one by one, Okay, so keep making all of them one by one, try once to see that all are done, send the try once to see that all are done, send the straight one easily in the same condition straight one easily in the same condition and secondly, order all of them one by one, and secondly, order all of them one by one, you can total a tweet here. you can total a tweet here. you can total a tweet here. doing it, just once, set it to one, this time set it to 101, set it to 120, set it to zero, make it water or make it a commo, we fold you like this, do something less, do While solving it, we will While solving it, we will While solving it, we will discuss it, okay, first of all, it will be smooth, interior coma is interior coma is 218, okay, now what will I do, see, okay, now what will I do, see, most of you are infiltrators, most of you are infiltrators, because of this, it means something like this, friend, twice, because of this, it means something like this, friend, twice, twice. twice. twice. that I have to do it, that I have to do it, if so then you would like me to do something like this if so then you would like me to do something like this 01 means I will search here 01 means I will search here okay so if you complete someone here then I have done it here. I have done it here. I have done it here. soon against 80 here - I will keep the points so that the rest of the work is done, then in the A map, I got up and put the gas at zero - it in the A map, I got up and put the gas at zero - it is closed, is closed, okay, I will not do it now, so now let's okay, I will not do it now, so now let's start the work. start the work. enter the enterprise's proof and loot, first take out the character. Okay, so again, let's start now. Look, where are you going to develop till now, here is two, this point is packed juice straight, so 1000 here is Chakli, all the temples are there, Okay here prostate is the Okay here prostate is the Okay here prostate is the method of one bitten and light or copy of four method of one bitten and light or copy of four goes neither so what does he have to do he goes neither so what does he have to do he just has to toggle this plate instead of this one just has to toggle this plate instead of this one crazy why if it was even time before this it crazy why if it was even time before this it was 700 then now one more good was 700 then now one more good was 700 then now one more good give one, it will be okay, if it is still on how many and in the number friend side where one is kept, if one more operation is done, then now it will become odd-even, tight, it will become zero, Just go to three and Just go to three and Just go to three and toggle that monkey toggle that monkey edit and if we can do it louder okay then edit and if we can do it louder okay then basically I have to do just mom I have to do basically I have to do just mom I have to do some number like this some number like this have to make a mask have to make a mask 200 200 is running one two and three get the lift made is running one two and three get the lift made is running one two and three get the lift made character has one, everyone else has zero, okay, so the statement that is coming till now is pro, after running him, 2 That's why the A state in, that's why or was on this, I went and made a A state in, that's why or was on this, I went and made a mask on mask on 1 Swift, how much is this? 1 Swift, how much is this? 1 Swift, how much is this? character - there is zero time, dog or worship, will do 323 and set, okay now next day Petkovich will do 18 masks, Parmarth, now whatever is straight, it is absolutely according to the current situation, from one number and time, and number times, first of all, So here we show the list of the So here we show the list of the people who were there on representative and representation, there is one there, if I find exactly the same condition somewhere on the part, then you can completely even, tight, complete power plants can be made, these are the complete Pentro, this will be done, okay, Pentro, this will be done, okay, Pentro, this will be done, okay, so now I am going to ask everyone, do so now I am going to ask everyone, do you have the exact same you have the exact same configuration, only the straight one configuration, only the straight one will do this incident, there is no difference in it, will do this incident, there is no difference in it, I call it this business I call it this business index, 500 yards contact with the current ID. index, 500 yards contact with the current ID. map.com date map.com date is stomach if j is equal to null is stomach if j is equal to null then I have not found any such stand before then I have not found any such stand before no devotional fan you I have got straight before also no devotional fan you I have got straight before also ok now see the length what will happen ok now see the length what will happen if you are currently here at this point if you are currently here at this point high on him high on him high on him Bichi Tej was where you are going to remove ok so I can take it from here till I but I can become these Rome side so if it is 2012 and here 3 4 5 6 Dancing Flag is 2012 and here 3 4 5 6 Dancing Flag Afternoon August 6 Afternoon August 6 Afternoon August 6 will become i minus plus one, in this you have this to itne bande hain itne bande hain one more here you will get 10 so here I have requested you Madam X N X which is not Pamma Well, I made it the highest, when all the guys even number of times, now if I can tighten the time of any one, then what will I do, Let's get a Let's get a Let's get a chance here by taking e world request 204 and this lu taking e world request 204 and this lu judicial commission plus judicial commission plus again let's make meat for it again let's make meat for it that you will become mafia one I that you will become mafia one I will set more number time ok now next day will set more number time ok now next day whose request do I have this whose request do I have this whose request do I have this saw here if the current scenario is current status of the show. If you have to current status of the show. If you have to mix all of them then you have to have tight requirements. mix all of them then you have to have tight requirements. If you have to leave one more then If you have to leave one more then make any one crazy that now I am not yours. make any one crazy that now I am not yours. make any one crazy that now I am not yours. requirement, bring more of this and give it, if it is different, then this guy will be more concerned about the result, all the rest will become fans, okay once I install it, I will dial it, if I open it, I will do Tubelight, now If you If you If you ask for help from ask for help from map.com, get current sports and see map.com, get current sports and see this interior interior of CPI(M), you this interior interior of CPI(M), you can get it here, then it that if it is not a journal, I got it straight, that if it is not a journal, I got it straight, then the answer is maximum. then the answer is maximum. then the answer is maximum. okay, this work will be completed then you will get the a written and when it is coming absolutely correct, it is presented for this test because we have not updated our pet, so basically I have done the work of current state. so basically I have done the work of current state. so basically I have done the work of current state. but as it is time, it does not have the data of my current state. It may be difficult in the future if someone else asks for my set then it is not my responsibility that I had posted zero here first in the exam. After that, whenever the current is broken, it is okay, then see once when example, here two is three, two is three, example, here two is three, two is three, in this much, you are also even, still they are 221 in this, in this much, you are also even, still they are 221 in this, TV is okay, hence in this position. 11000, okay, this is also another one, this one is also another one, okay, so for this, there are all the temples, this one must have an inactive state, 138, this one's arrangement is fine, now suppose that some person will come on Twitter Will say friend two and Will say friend two and Will say friend two and remove the triangle it here ABCD remove the triangle it here ABCD is some rate here you will go on rough inducting atoms is some rate here you will go on rough inducting atoms take 20123 and 576 at this point demand war 40 bring from state part ok then what will he do he will make length I I - Yes like this Try it, if I give you all the induction in this, then it will forward the three, it will make it tight, it will make it amazing, then I - whatever is there, it will become rhythm, the one here which will be added on comparison will be erased from both the places, two There is three and here it is 123 if There is three and here it is 123 if There is three and here it is 123 if you give well one and keep three then the you give well one and keep three then the life that is right will be able to maximize this volume on this life that is right will be able to maximize this volume on this side and what do I want side and what do I want maximum subsequent, then we want garre ok maximum subsequent, then we want garre ok ok so what am I going to do ok so what am I going to do If someone is already there in this state, then If someone is already there in this state, then leave it, but if no one is there, leave it, but if no one is there, then enter me as then enter me as 28. My direction is on this form. 28. My direction is on this form. Okay, so here if someone has entered Okay, so here if someone has entered If you come here from the city, then I will If you come here from the city, then I will If you come here from the city, then I will not update it, okay, I will not update it, okay, I will leave it there, so leave it there, so here we come inside the loop, here we come inside the loop, I just have I just have a map, don't have a map, don't have content, a content, a pet is equal to pause, pet is equal to pause, now I don't do half an hour of content. now I don't do half an hour of content. now I don't do half an hour of content. evening and verify the torch light 10334 slogan by submitting it here and try it. All the tests on the phone are running fine with this, but All the tests on the phone are running fine with this, but still our time complexity is 158 milliseconds. still our time complexity is 158 milliseconds. This was the complete code, This was the complete code, this is just the implementation, we are going to change it, so this is just the implementation, we are going to change it, so why is it taking so much time, why is it taking so much time, then the speed and time is being spent because we are then the speed and time is being spent because we are doing the work on time, if doing the work on time, if anything happens then it will be Bigg Boss, then you know. anything happens then it will be Bigg Boss, then you know. anything happens then it will be Bigg Boss, then you know. tell me how much range do I state state basically varies from one to nine number is zero 12345 680 i to maximum if we talk about the rally of this whole then I can also and number one to the maximum is this to the maximum is this Okay, okay, if you Okay, okay, if you make anyone in this zero, then it will reduce the overall value of you. In comparison to make anyone in this zero, then it will reduce the overall value of you. In comparison to one, one, I know that what is there in this is that by I know that what is there in this is that by taking 03 and folding the state till this value. taking 03 and folding the state till this value. taking 03 and folding the state till this value. going to make it so deep, it is repeated again and again, he will not ask directly from the time, hey, I will check, what value is there on this state, is there any indexing, okay, this course is like taking pizza, but the read-write on it is read. read. read. ok so come next day basically how much valley will be on the interior so what you can do is fit one 10 times then basically will set off once I am here will be considered twice I am here I will come here 10 times, this is the number of here the forest officer definitely comments that he will cover all the stretches, so what do I do to you, here now instead of the map, an interview will be made, map new okay, okay, and here ma'am don't okay, okay, and here ma'am don't need a map instead of it, inductive, I took the need a map instead of it, inductive, I took the shoulder, I took the shoulder, I took the torch light, now you know, if I torch light, now you know, if I make it an interior, if I make it an interior, if I become a teacher, now basically this become a teacher, now basically this become a teacher, now basically this body full of vegetables, the colonel is lying there, okay, body full of vegetables, the colonel is lying there, okay, so instead of the date, I read the tiffin here, so instead of the date, I read the tiffin here, from that position here too, ma'am don't get it, from that position here too, ma'am don't get it, read where are you from, It is It is It is completed, we have to see this point, completed, we have to see this point, this platform will not be there, this platform will not be there, what can happen at this point, if I what can happen at this point, if I tap on the map date, then tap on the map date, then I will come here to that stage and put I will come here to that stage and put a Aayenge, everything is a Aayenge, everything is a Aayenge, everything is a total, it was a mistake, okay, so this was also not correct, 158 This 2009 Torch Light Proxy has become ten times ready, so I hope you got to learn something from this video. If you got to learn from this video, If so, please like this video and tell us in the comments. Subscribe to our channel. Thanks for watching. | 2024-03-21 11:42:20 | 1,542 | Find Longest Awesome Substring | Leetcode 1542 |
|
k48MN4dCdMo | Hello Hi Guys How Are You I Hope All You Are Doing Good Welcome To The Land Cords Lee Welcome To The Land Cords Lee Today Will Do The Longest Union Value Path Today Will Do The Longest Union Value Path Withdrawal Question So Let's Video Give Withdrawal Question So Let's Video Give Inside And Outside Returns The Length Of The Inside And Outside Returns The Length Of The Longest Pass Thursday And Not Passed Through Longest Pass Thursday And Not Passed Through The length of the match between to note servi The length of the match between to note servi servi now in which will not the length of the number servi now in which will not the length of the number of subscribe now to the of subscribe now to the part of the part of the little bit pieky birth but not s part of the part of the little bit pieky birth but not s hard s you know a little bit vacation you can solve between there hard s you know a little bit vacation you can solve between there sorrow sorrow sorrow function is veervar [praise] [praise] [praise] and safed meaning of 108 laung ispat and this and safed meaning of 108 laung ispat and this root is so I make that a function and a game for storing the maximum volume maximum length hai ki maang Length Swasthya to maintain Length Swasthya to maintain Length Swasthya to maintain Vaikuntha variable max variable in this Vaikuntha variable max variable in this annual is so first ayurveda call fruit a [ pramshan] kar dena hai maintaining Tubelight is left and right and left left will call for the pramshan] pramshan] hai Android m calling from the right toe hai Android m calling from the right toe [ [ [ That boat gift Abhay Root That depth of That depth of I 10 Not fixed to none I 10 Not fixed to none and that and that rudded well [Praise rudded well [Praise ] ] That it is equal to the left left I left side is 0 [Praise] The Zero Zero Zero [praise] have done all right [ right [ praise] have done 102 Not have left or right Significance of 102 Not have left or right Significance of Bus Calculator will calculate the match The Bus Calculator will calculate the match The maximum disturbance till nine som maximum disturbance till nine som On I Maths Of I Sleep On The Right Side Inside Left Side You Return Hair Maximum Morning Hour Sleep On The Right Side Inside Left Side You Return Hair Maximum Morning Hour M Calling Alarms Calling Loot Show Fear Of M Calling Alarms Calling Loot Show Fear Of Mysticism Moment Person Then Implementing Mysticism Moment Person Then Implementing A Cliff Route Byte Route Byte Route Byte Route Off A Cliff Route Byte Route Byte Route Byte Route Off List Route of leaders not equal 19 feet in this Route of leaders not equal 19 feet in this Route of leaders not equal 19 feet in this how can compare can see the laptop fit how can compare can see the laptop fit and this is name five years by check Delhi and this is name five years by check Delhi 100 100 feet is prescription hai sanwarlu subah us 100 100 feet is prescription hai sanwarlu subah us check the route beet route start top ten sport check the route beet route start top ten sport and route of laptop and mid and route of laptop and mid and route of laptop and mid increment left side one should you know it is the meaning of the same 2009 right side subscribe button from left side to right side this is becoming too length of shame vaginal value talk but happy return of the match Jor right side hai tomorrow morning aap return gift uddh axis in this will return here one happened 102 that this to 9 elite and even when the welcome one should be felt in the middle of the night sweet will happen in the same manner Sukhbir and Volume Maximum Difficulty Volume Maximum Difficulty Volume Maximum Difficulty Is Add All The Maximum Is Illness Serious And Is Add All The Maximum Is Illness Serious And Holding Every Time The Maximum Is Univalent Holding Every Time The Maximum Is Univalent Pat 108 Has Been Done Limited 998 Submitted Her Home In The State Were Traveling Every Time You Were Not The Only One Very Little Bit Unit Very Little Bit Unit Very Little Bit Unit Tool Practice How To Do The Question Tool Practice How To Do The Question Is No How To Years When You Can Do It Is Lee Sanseri Hai Way Do I Will Is No How To Years When You Can Do It Is Lee Sanseri Hai Way Do I Will Meet In X Meet In X Video MP Samvida Next Video Video MP Samvida Next Video Bye-Bye Take Care And Please Like Bye-Bye Take Care And Please Like Subscribe And Comment And Don't Subscribe And Comment And Don't Subscribe And Comment And Don't | 2024-03-20 17:06:28 | 687 | 687 Longest Univalue Path | Medium Level Interview Question Solution in Python |
|
zT-ZfIKgNZ4 | Ki Welcome Back Everyone in this Video Bihar Ko * Solid Code Easy Level Question and the Ko * Solid Code Easy Level Question and the Question is Reverse Swing in this question will be given and Question is Reverse Swing in this question will be given and head of head of characters and what we have two years were written characters and what we have two years were written directed by reversing the no1 directed by reversing the no1 extra memory ok soft Video extra memory ok soft Video Subscribe Subscribe Subscribe Is The Mean Of The Day That So And Flowers Only And i20 Phone Online There Is Five Okay Length Is 500 To That They 125 - E - 150 - 150th Comments Roy And The Elements And Coasts 21 Dead - Verb - Wonderland - 25 - 235 They Saw A Pretty Simple The Dates To Length Of Dates To Length Of That Sn Hai That Sn Hai Lunch Ok 204 Lunch Ok 204 That In Tie Cost Him Zor Loop By Two That In Tie Cost Him Zor Loop By Two Yes Brother Plus Plus Yes Brother Plus Plus A Friend Rail Ticket A Friend Rail Ticket That TDS Charge Anil Store Apps Of That TDS Charge Anil Store Apps Of This This This half learned - I - one okay and that's half learned - I - one okay and that's such a plan - 22 - One will be reached to such a plan - 22 - One will be reached to tier e and e don't have written a thing The tier e and e don't have written a thing The Amazing with oo Bigg Boss Reverse String Easy Bigg Boss Reverse String Easy Bigg Boss Reverse String Easy Level Questions IF Everyone Gets Injured Video Level Questions IF Everyone Gets Injured Video Thank You So Much and Bye-Bye | 2024-03-24 11:05:20 | 344 | Reverse String | LeetCode Easy 344 | C++ | Simple Solution |
|
l-XCWjps-UQ | [Music] how's it going everyone today we're how's it going everyone today we're gonna try to solve one of the really gonna try to solve one of the really popular questions on li code this is popular questions on li code this is gonna be the something called the gonna be the something called the longest palindromic substring now if we longest palindromic substring now if we look at this question majority of the look at this question majority of the people would solve it in various ways people would solve it in various ways that it's kind of brute force e but that it's kind of brute force e but actually in this episode I'm gonna try actually in this episode I'm gonna try to go through something that is a little to go through something that is a little bit more on the advanced topic we're bit more on the advanced topic we're still gonna try to go through to solve still gonna try to go through to solve this in the traditional way but I this in the traditional way but I thought I throw a little bit of nice thought I throw a little bit of nice little tricks in there to make you have little tricks in there to make you have an ability to saw this in a web and time an ability to saw this in a web and time okay cool so let's first try to okay cool so let's first try to understand the question understand the question okay longest palindromic substring let's okay longest palindromic substring let's read the question given a string s find read the question given a string s find the longest palindromic substring in s the longest palindromic substring in s you may use you may assume that the you may use you may assume that the maximum length of s is 1,000 cool so for maximum length of s is 1,000 cool so for those who don't know what a palindrome those who don't know what a palindrome in is it's pretty much something where in is it's pretty much something where if you take the midpoint if you look to if you take the midpoint if you look to your left you look to your right your left you look to your right everything beside you going out is the everything beside you going out is the same for example a word like race car same for example a word like race car would be a palindrome something like a a would be a palindrome something like a a b b a a that's a palindrome because in b b a a that's a palindrome because in the middle between the two a's you the middle between the two a's you basically see a mirror image of one basically see a mirror image of one another right cool so let's look at a another right cool so let's look at a quick example this is really quick example this is really self-explanatory you know the palindrome self-explanatory you know the palindrome the biggest pile of German here is the biggest pile of German here is something in the middle you know is something in the middle you know is three of size three right and the next three of size three right and the next palindrome on this one is of size two palindrome on this one is of size two cool now I wanted to actually dive cool now I wanted to actually dive deeper into this question because one deeper into this question because one way to solve these type of questions way to solve these type of questions what we could do is iterate through each what we could do is iterate through each element and then as you are in a element and then as you are in a specific element you can start expanding specific element you can start expanding outwards to see outwards to see if it's a palindrome or not although if it's a palindrome or not although that can solve the problem for example that can solve the problem for example you go here and you expend left and you you go here and you expend left and you spend right can expand go here expand spend right can expand go here expand left right you can't go here you can left right you can't go here you can spend right and left you go be be spend right and left you go be be excited cetera that you can solve it excited cetera that you can solve it that's like a brute-force away and your that's like a brute-force away and your time complexity is quite high time complexity is quite high effectively you're forcing your effectively you're forcing your algorithm to go through the question algorithm to go through the question like twice or and square it in a sense like twice or and square it in a sense so we're gonna try to go and review a so we're gonna try to go and review a really cool more advanced algorithm to really cool more advanced algorithm to solve this question this this algorithm solve this question this this algorithm is actually called the manager or is actually called the manager or manager I'm probably pronouncing really manager I'm probably pronouncing really horribly but it that's what it's called horribly but it that's what it's called and we're gonna actually go through it and we're gonna actually go through it right now so let me explain it I'm gonna right now so let me explain it I'm gonna try a new different topic I'll try to try a new different topic I'll try to bring it up as a you know a presentation bring it up as a you know a presentation to see if you guys like this format more to see if you guys like this format more okay so let's begin to look at this okay so let's begin to look at this algorithm let's use an example because algorithm let's use an example because examples are always great to explain a examples are always great to explain a difficult concept so the example I'm difficult concept so the example I'm giving here is you know and B and and B giving here is you know and B and and B are right by the looks of it just by are right by the looks of it just by eyeballing we know the highest the eyeballing we know the highest the longest palindrome contained here is longest palindrome contained here is gonna be of size four right gonna be of size four right but in monikers or manicure I on you but in monikers or manicure I on you know what is called manicures algorithm know what is called manicures algorithm what we need to do first is to address what we need to do first is to address the question of whether the string is the question of whether the string is even or odd so one of the very first even or odd so one of the very first things we would want to do is try to things we would want to do is try to manipulate this string such that you manipulate this string such that you know regardless if it's even or odd know regardless if it's even or odd we're still gonna get the same results we're still gonna get the same results right so the next step we want to do is right so the next step we want to do is you know adjust the string boom alright you know adjust the string boom alright let's let's focus on the thing I've let's let's focus on the thing I've highlighted here first we'll talk about highlighted here first we'll talk about the bottom elements and top later on but the bottom elements and top later on but I just basically manipulated the I just basically manipulated the previous string and inserted money signs previous string and inserted money signs in between each of the characters this in between each of the characters this ensures that you know regardless if it's ensures that you know regardless if it's an even or odd string effectively I can an even or odd string effectively I can still solve this problem right it still solve this problem right it doesn't matter doesn't matter cool so once we have that cool so once we have that what we also need to do is create an what we also need to do is create an array that basically tracks what are the array that basically tracks what are the longest powered rims as we go along on longest powered rims as we go along on this adjusted string right cool this adjusted string right cool the next thing in this algorithm that we the next thing in this algorithm that we need to really really focus on is the need to really really focus on is the concept of mirroring I'll dive deeper as concept of mirroring I'll dive deeper as we go along this example and you'll we go along this example and you'll probably get the reference of what I'm probably get the reference of what I'm talking about talking about but that's something that you have to but that's something that you have to think where you know as an example if I think where you know as an example if I take a random figure like n the mirror take a random figure like n the mirror value for this would be something like value for this would be something like this will be there n prime this will be there n prime I won't dive into until we get to that I won't dive into until we get to that point but let's let's continue with this point but let's let's continue with this example so one of the requirements we example so one of the requirements we need to do is iterate through this need to do is iterate through this string and do a series of checks right string and do a series of checks right our first check to see is is that okay our first check to see is is that okay at arch and I equal to 0 at the at arch and I equal to 0 at the beginning point let's let's set our beginning point let's let's set our center point which is the center of our center point which is the center of our longest palindrome and to 0 and also longest palindrome and to 0 and also let's let's move Valar i to its let's let's move Valar i to its beginning position right so our first beginning position right so our first task is to check ok well how many times task is to check ok well how many times can I expand right and left and such can I expand right and left and such times still a palindrome in this case times still a palindrome in this case it's 0 right so that's fine that's it's 0 right so that's fine that's simple you basically update this to 0 simple you basically update this to 0 cool now the next step cool now the next step new we need to do is move the I to the new we need to do is move the I to the next level right in here we're going to next level right in here we're going to look at ok well is is this is my longest look at ok well is is this is my longest palindrome 0 mmm not really because my palindrome 0 mmm not really because my left and right I could still expand left and right I could still expand right so once I find a palindrome that right so once I find a palindrome that is of size that's greater than my is of size that's greater than my previous one well let's set the the previous one well let's set the the center to equal to this end and update center to equal to this end and update this value to 1 now one of the things this value to 1 now one of the things that we need to keep track of in the in that we need to keep track of in the in this algorithm is an idea of our this algorithm is an idea of our rightmost boundary right or what what is rightmost boundary right or what what is your boundary on your most thinking your boundary on your most thinking ahead of you what I mean by that is that ahead of you what I mean by that is that we may need to create a flag are on top we may need to create a flag are on top of this particular index I'll dive of this particular index I'll dive deeper into that later but well we'll deeper into that later but well we'll just go into that so cool we set a flag just go into that so cool we set a flag here because once you have this right here because once you have this right flag that's one indicator when we can flag that's one indicator when we can check okay well if we should repeat check okay well if we should repeat something or not right I'll go through something or not right I'll go through an example what I mean so well this is an example what I mean so well this is this power drill is satisfied so what this power drill is satisfied so what we're gonna do next right we're gonna go we're gonna do next right we're gonna go in here and check okay well is this in here and check okay well is this gonna be a palindrome well not really gonna be a palindrome well not really because you're sitting on top of our because you're sitting on top of our your rightmost battery and there's no your rightmost battery and there's no really thing very cold over here really thing very cold over here although you could look at this one that although you could look at this one that looks the same but you know that doesn't looks the same but you know that doesn't tell you much so I'm just gonna go okay tell you much so I'm just gonna go okay well this is not a boundary so I'm gonna well this is not a boundary so I'm gonna keep it as like the zero it doesn't do keep it as like the zero it doesn't do anything to me right so I'm gonna go anything to me right so I'm gonna go move my thing keep going along keep move my thing keep going along keep expanding so I'm hearing now right on B expanding so I'm hearing now right on B so what happens here so on B I'm already so what happens here so on B I'm already above my my R which is gonna be like above my my R which is gonna be like okay well if we look at if we expand okay well if we look at if we expand left and right our longest palindrome in left and right our longest palindrome in this case is gonna be one two three one this case is gonna be one two three one two three two three three right this is our longest three right this is our longest palindrome we're gonna change it to palindrome we're gonna change it to three but we're gonna also move where I three but we're gonna also move where I said before this to the rightmost flag said before this to the rightmost flag right and then I'm gonna set this right and then I'm gonna set this particular I love my Center into my particular I love my Center into my longest segment cool so that's longest segment cool so that's relatively simple right nothing relatively simple right nothing difficult here but this is where the difficult here but this is where the power begins when we move on to the next power begins when we move on to the next step so when we go in here move along step so when we go in here move along the I again if I check what if my I is the I again if I check what if my I is less than my right boundary right what less than my right boundary right what can I do here in can I do here in in a sense so we know that the power in a sense so we know that the power drum on I if if this was my Center the drum on I if if this was my Center the maximum this can be would either equal maximum this can be would either equal to the minimum of what my counterpart to the minimum of what my counterpart would be which is this one which is zero would be which is this one which is zero or the boundary of what my right would or the boundary of what my right would be right because that's like the be right because that's like the attribute of a palindrome right your attribute of a palindrome right your left will equal to your right so left will equal to your right so therefore your little brother or little therefore your little brother or little partner here should be equal to what you partner here should be equal to what you have as at them at the very least right have as at them at the very least right so what we can do right now is see like so what we can do right now is see like okay can I expand in this case if it's okay can I expand in this case if it's zero or are - my position - if it's zero zero or are - my position - if it's zero to the minimum of those of those two to the minimum of those of those two elements well I'm gonna take the zero as elements well I'm gonna take the zero as my position cool and then I'm gonna go my position cool and then I'm gonna go check you know if my left and right check you know if my left and right would actually do anything well in this would actually do anything well in this case zero is probably my right solution case zero is probably my right solution great let's move on along okay cool great let's move on along okay cool so in this case same thing less than our so in this case same thing less than our checking here your counterpart over here checking here your counterpart over here is this one and we know that okay it can is this one and we know that okay it can be a 1 we can insert that either our - I be a 1 we can insert that either our - I or or n they're both equal to 1 so we're or or n they're both equal to 1 so we're gonna actually say alright let's let's gonna actually say alright let's let's keep this as one great alright so the keep this as one great alright so the next step is gonna move on to hear more next step is gonna move on to hear more on top of our right once we're here on top of our right once we're here we're gonna go check out okay well I we're gonna go check out okay well I can't check even my up my right bounding can't check even my up my right bounding anymore because I'm on top of it so what anymore because I'm on top of it so what do I need to do well we're gonna start do I need to do well we're gonna start checking left and right right and start checking left and right right and start expanding beyond that so I could expand expanding beyond that so I could expand it seems like okay well I could spent it seems like okay well I could spent all the way down to 4 right so we're all the way down to 4 right so we're gonna update this number to 4 and put gonna update this number to 4 and put this on the right boundary to this this on the right boundary to this particular element and ensure that this particular element and ensure that this comes in here great now we can continue comes in here great now we can continue along and move along in this element along and move along in this element again and effectively go and check if my again and effectively go and check if my I is less than R it is less than R I'm I is less than R it is less than R I'm gonna go check over here of less it's gonna go check over here of less it's gonna be one or two the less of those gonna be one or two the less of those two I'm going to take this as 1 oops not two I'm going to take this as 1 oops not that value oops that value oops change that to one great and then I'm change that to one great and then I'm gonna effectively see if it is the case gonna effectively see if it is the case which is the case great because I could which is the case great because I could start from these two variables that's start from these two variables that's great and expand doesn't make sense and great and expand doesn't make sense and move along cool now I am going to ensure move along cool now I am going to ensure that check on this particular value so that check on this particular value so it's going to be zero or two take the it's going to be zero or two take the zero and I check left and right of zero and I check left and right of course it's zero go on to be B over here course it's zero go on to be B over here it's gonna be either three or one this it's gonna be either three or one this is an interesting one so it could be is an interesting one so it could be three or one so I'm gonna make sure that three or one so I'm gonna make sure that I gotta go okay I'm gonna change it to I gotta go okay I'm gonna change it to one because I'm taking the less of the one because I'm taking the less of the two which is the case in here great we two which is the case in here great we going to hear boom same case I'm on top going to hear boom same case I'm on top of it of it I can check left and right I can't go I can check left and right I can't go anywhere that's fine so my boundary anywhere that's fine so my boundary boundary just stays the same doesn't do boundary just stays the same doesn't do anything my new Center is not the same anything my new Center is not the same and then BOOM keep going along am i and then BOOM keep going along am i right right cool and then update this particular cool and then update this particular value to here move this to the center value to here move this to the center and boom this is gonna be my value of and boom this is gonna be my value of one right so by doing this we keep track one right so by doing this we keep track of our maximum palindrome on this way of our maximum palindrome on this way and from this we can actually solve the and from this we can actually solve the problem really quickly just read the problem really quickly just read the longest one and then there's your longest one and then there's your palindrome so let's go let's go to some palindrome so let's go let's go to some code and what we will but understanding code and what we will but understanding a little bit more all right a little bit more all right we're back at the code all right let's we're back at the code all right let's try to solve this so one of the first try to solve this so one of the first things remember our reference before things remember our reference before what we need to do is to adjust the what we need to do is to adjust the string to accommodate for the edge cases string to accommodate for the edge cases of even and odd numbers so let's do that of even and odd numbers so let's do that I'm gonna go Const equals to a I'm gonna I'm gonna go Const equals to a I'm gonna call this like new string will equal to call this like new string will equal to I'm gonna grow a helper function because I'm gonna grow a helper function because here's a actually pro tip if you were to here's a actually pro tip if you were to go through an interview and if you won't go through an interview and if you won't know you need to do something but you know you need to do something but you don't have time to do it you could don't have time to do it you could explain to the interviewer what you're explain to the interviewer what you're trying to do and use a helper function trying to do and use a helper function to return the result that you want so to return the result that you want so for example in here I'm gonna get for example in here I'm gonna get something called get something called get if I'd string and passing the s and you if I'd string and passing the s and you got let the interview know that okay got let the interview know that okay what this really does is just add money what this really does is just add money signs to the string that you're signs to the string that you're interested and so on and so forth interested and so on and so forth cool this will save a lot of time for cool this will save a lot of time for you and if you have time at the end of you and if you have time at the end of the interview you can actually write the interview you can actually write this equation out but for now we're just this equation out but for now we're just gonna go and create this helper function gonna go and create this helper function I will write down that segment later on I will write down that segment later on but for now we understand that okay this but for now we understand that okay this basically creates those hashes there the basically creates those hashes there the next thing we want to do is to create next thing we want to do is to create that p function you could be an p array that p function you could be an p array which I'm gonna call P is a new array of which I'm gonna call P is a new array of size a new string dot length right and size a new string dot length right and then I'm gonna fill it with zeros so then I'm gonna fill it with zeros so what this really does is like creating what this really does is like creating the saw equal size of that particular the saw equal size of that particular string filling it with zeros great now string filling it with zeros great now my next step remember what I said before my next step remember what I said before in my presentation that we need to keep in my presentation that we need to keep track of a few things we need to keep track of a few things we need to keep track of where our Center is and we also track of where our Center is and we also need to keep track of where the right need to keep track of where the right boundary would be right so let's do that boundary would be right so let's do that let's send Center B 0 and let right bow let's send Center B 0 and let right bow equal to 0 for now because we start from equal to 0 for now because we start from 0 great 0 great cool now here's the fun part now we're cool now here's the fun part now we're gonna actually start iterating through gonna actually start iterating through the character so we're gonna do that for the character so we're gonna do that for let I equal to 0 and it's gonna be less let I equal to 0 and it's gonna be less than the new string length and i's gonna than the new string length and i's gonna i's gonna plus plus right cool i's gonna plus plus right cool ok so what are we gonna do here so one ok so what are we gonna do here so one of the things that we need to keep track of the things that we need to keep track of is the center of where you know where of is the center of where you know where we have to mirror okay where where's our we have to mirror okay where where's our index the the mirrored index so remember index the the mirrored index so remember when i was looking back earlier talking when i was looking back earlier talking about okay well let me go back to an about okay well let me go back to an example so when we're looking at this example so when we're looking at this the mirror value is here well we if we the mirror value is here well we if we have the center point here have the center point here we want to find the index of its mirror we want to find the index of its mirror it's basically the same thing as Center it's basically the same thing as Center you know it's basically Center - the I you know it's basically Center - the I mean sorry this - the center you'll get mean sorry this - the center you'll get a value and then you don't bring it back a value and then you don't bring it back in here so let's get back in here so the in here so let's get back in here so the equation is relatively simple it's gonna equation is relatively simple it's gonna be let the index be let the index mirror mirror equal to center - the index she's it's might be ya index - Center cool so that will basically tell me where my my mirror index would be okay so in here it's gonna be zero that's do anything that's great so one of the things we need to do now is to check well is my eye less is it basically on my right boundary right so we're gonna have to do a check is like if my eye is less than my right boundary if it is the case I'm going to update my P of I P of i2 equal to my minimum math.min of basically what we were saying before which is the right boundary - the eye or the P at the mirror value index no score mirror well I can use camel case that's probably better JavaScript e cool great so let's shrink this over here great cool what does this da do it's basically what we were mentioning earlier we're gonna check if the value is less than the right boundary and then take the less of those two great now this is where we start doing the expansion the expanding game okay so let's let's go and try to expand left and right let's define that first let's let let left equals to I plus I'm gonna go and say like eight where I'm at right now G's plus okay I'm gonna go and save my P of I position right plus one right because I want to go oh not if I go one is right I'm gonna go one ahead of me and one behind me right so I'll do that and let's go look at that let's go here go on left the left is like the opposite a minus that value alright great so I know my left and right boundaries right so my next thing to do is well let's go and I'll go this spacing is horrible sorry excuse my things okay cool the next thing to do here is basically check annex start expanding my left and right right so I'm gonna go and write a quick while loop Wow my right is less than the length new string length so basically I won't expand beyond my right boundary and my left is greater than or equal to zero and also my new string at the left position is equal to my new string on my right position basically if there's like if those position are equal to the same what I'm gonna do I'm just gonna increase the value over here by one and I'm also gonna expand more on the right and left so I'm gonna go right plus plus left - - great okay cool so now we have this this thing let's go and try to look at okay let's let's go and try to explain this a little bit okay so we've already expanded that's great now what do we do when we hit the boundaries what we're gonna do in here is gonna go like basically check if my eye position plus my p @ @ i right is gonna be greater than right boundary is it gonna be greater than that if it is well I'm gonna go and readjust my Center will equal to my eye position right so I'm saying that if where I'm at in my time I'll overlapping the right boundary or being a little bit more I'm gonna adjust my new Center and also set the right boundary to equal to my I plus plea and I great cool so this pretty much covers majority of the algorithm I'm gonna paste in some code that I've written before to do it you know to deal with this string here which I'm gonna give me a second I'm gonna paste it in here so I don't waste anyone's time cool I could just go constant that equals to the word cool so what this pretty much does is that you know adds hashes to the word and it returns that's what it does right it returns that's what it does right it returns that but we're not quite done yet right that but we're not quite done yet right because right now all we have done is because right now all we have done is construct a P of I that tells me where construct a P of I that tells me where is the longest palindrome right we still is the longest palindrome right we still have to return the actual palindrome have to return the actual palindrome itself right so one of the things we itself right so one of the things we need to do is start doing that so last need to do is start doing that so last bits of stuff is gonna go and see like bits of stuff is gonna go and see like what is the maximum length what is the maximum length I'm gonna call length well math max I'm I'm gonna call length well math max I'm gonna spread what spread LV element on P gonna spread what spread LV element on P to identify what the maximum length is to identify what the maximum length is and let the index of well that will be Pete index of length cool now we help the backs of leg that when you know when the index of that would be I'm gonna start returning the new string dot substring stop string and I'm gonna go and define it as my index minus length plus 1 and length sorry I'm I length cool once we have that substring length cool once we have that substring of that that total substring from the of that that total substring from the beginning to end for the longest air beginning to end for the longest air segment I'm gonna make sure I get rid of segment I'm gonna make sure I get rid of those hash tags so I'm gonna go split those hash tags so I'm gonna go split hash tag hash tag great geez come on cooperate okay I get rid of those hash tags and I'm gonna join the string again cool by doing this effectively I have I should have solved the problem there is an edge case that you know I wanted to deal with not edge case but I wanted to you know not have to deal with all this stuff with my sight string a size one so I'm gonna do anything here if my s all like this is gonna be less than one which is you know it can be an edge case I'm just gonna return s which is fine cool so I think this is uh this will solve a problem so let's see how it actually works great accept it and it's a hundred percent beating everybody else so I hope everybody understands this I know there's a little bit more complicated algorithm to think about however I know the results are here it's fast I beat everybody and I just did a life that's pretty cool and and yeah so that's it hope you guys hit that subscribe hit that give me a like give me a comment let me know if you like this new format of me explaining things on the PowerPoint I know I'm just trying to do it as one take as much as I can I'm trying to not edit as much as possible so you get the raw raw deal or you see the struggle I experienced because no not everyone's perfect I know videos you can make sometimes make it perfect however I want to give you the real deal so stay tuned for the next episode thanks for attending bye | 2024-03-18 11:18:10 | 5 | LeetCode Solution - 5.0 Longest Palindromic Substring | Manacher Algorithm 100% Beat |
|
J63D5bmeSdo | hi everyone it's Soren today we have a problem when we are given a string s and problem when we are given a string s and we need to repeatedly make a duplicate we need to repeatedly make a duplicate removals from s until we no longer can removals from s until we no longer can so what's a duplicate duplicate is if so what's a duplicate duplicate is if the two adjacent two the two adjacent two adjacent characters are equal so for adjacent characters are equal so for example in this case we have a b b a c a example in this case we have a b b a c a so these two characters are equal right so these two characters are equal right so we are removing them now we have a a so we are removing them now we have a a c a and again these two characters are c a and again these two characters are also adjacent two characters are equal also adjacent two characters are equal right so we are removing also these two right so we are removing also these two now we have CA and we are returning CA now we have CA and we are returning CA as a as a result we are going to solve this result we are going to solve this problem using a stack data structure so problem using a stack data structure so what we are going to do to our stack so what we are going to do to our stack so let's take this example a B B A CA the let's take this example a B B A CA the example that we have seen earlier so example that we have seen earlier so what we do starting from the first what we do starting from the first character we are adding that to our character we are adding that to our stack so for example in this case first stack so for example in this case first we are adding a the next one so as we we are adding a the next one so as we are adding the character so we are are adding the character so we are checking that is the previous character checking that is the previous character in a stack is that equals to our current in a stack is that equals to our current character so for example we are adding a character so for example we are adding a because there is no character in the because there is no character in the stack so the next one we are adding what stack so the next one we are adding what we are adding B so again we are we want we are adding B so again we are we want to add the next pep but we are checking to add the next pep but we are checking okay if the if the top character is okay if the if the top character is equals to our this character B right yes equals to our this character B right yes it equals so we are removing so we are it equals so we are removing so we are removing the this character also from removing the this character also from the stack right so we are removing this the stack right so we are removing this character from the stack and now we are character from the stack and now we are adding the next one next one is a right adding the next one next one is a right we are adding a we are trying to add a we are adding a we are trying to add a is the a is it equals to A yes it equals is the a is it equals to A yes it equals to A so we are also removing from the to A so we are also removing from the stack this character so the next one we stack this character so the next one we are adding C and we are checking that is are adding C and we are checking that is the next one is a is a equals to C no so the next one is a is a equals to C no so we are adding a here and the last one is we are adding a here and the last one is that we are going over our stack and that we are going over our stack and adding that to the so we are forming a adding that to the so we are forming a new string and returning that as a new string and returning that as a result so what's the time and space result so what's the time and space complexity in this case the time complexity in this case the time complexity is we are going over our complexity is we are going over our string only once so it's of n and the string only once so it's of n and the space complexity is we are using stack space complexity is we are using stack and for the stack in the worst case and for the stack in the worst case scenario our space complexity is also scenario our space complexity is also going to be off going to be off n okay first thing that we do here we n okay first thing that we do here we are creating a stack with the type is are creating a stack with the type is being the character so we are going over being the character so we are going over our string and for each character we are our string and for each character we are checking if our stack is not empty and checking if our stack is not empty and if our the the element that is on the if our the the element that is on the top of the stack if that equals to our top of the stack if that equals to our our current character so what we do we our current character so what we do we are taking that character from the stack are taking that character from the stack because they are they are adjacent to because they are they are adjacent to adjacent uh characters that are equal if adjacent uh characters that are equal if not then we are adding that character to not then we are adding that character to our stack and once we exit this Loop we our stack and once we exit this Loop we have we don't have no longer two have we don't have no longer two adjacent characters that are equal so we adjacent characters that are equal so we are building up our result so for that are building up our result so for that we are using a string Builder and we are we are using a string Builder and we are going over our stack until it's empty going over our stack until it's empty and we are adding inserting the to the and we are adding inserting the to the zero character why because for example zero character why because for example in the stack uh in our previous example in the stack uh in our previous example right so the characters are first is a right so the characters are first is a and the next one is C but the the and the next one is C but the the correct result should be the correct correct result should be the correct result that we should return should be result that we should return should be ca right CA so that's for that reason we ca right CA so that's for that reason we are adding the we are adding the are adding the we are adding the character to the zero index making sure character to the zero index making sure that uh we have the correct order so that uh we have the correct order so should be in reverse order and at the should be in reverse order and at the end we are just returning a end we are just returning a result okay that's it uh that's it for result okay that's it uh that's it for today hope you like my content if you today hope you like my content if you like it please hit the like button and like it please hit the like button and subscribe my channel see you next time subscribe my channel see you next time bye | 2024-03-25 16:01:12 | 1,047 | LeetCode - 1047. Remove All Adjacent Duplicates In String | Stack | Java |
|
Lp2pncT8FXc | as most of you know every day we try to pick one the code one interview pick one the code one interview experience from read code and try to experience from read code and try to solve all the interesting question of solve all the interesting question of the interview experience the interview experience not only that we also try to not only that we also try to solve all the possible follow-ups of solve all the possible follow-ups of that particular question that can be that particular question that can be asked during an interview so we have asked during an interview so we have already solved a lot of interview already solved a lot of interview experiences from experiences from microsoft facebook amazon microsoft facebook amazon and others and others i will link them in the description i will link them in the description below do check them out you will be below do check them out you will be amazed to see how a very easy problem amazed to see how a very easy problem turns into a very hard problem of lead turns into a very hard problem of lead code code so do check them out in this particular so do check them out in this particular video we will be looking at video we will be looking at this linkedin interview experiences of this linkedin interview experiences of january january the first question the first question we will be not we will not be discussing we will be not we will not be discussing because we have already discussed this because we have already discussed this kind of question kind of question several times in our channel i will link several times in our channel i will link some of these some of these some of the some of the questions that are of similar type in questions that are of similar type in the description below i will strongly the description below i will strongly encourage you to solve it on your own encourage you to solve it on your own and if you have any doubts you can link and if you have any doubts you can link it you can comment down below and i will it you can comment down below and i will answer them answer them or if you want me to create a separate or if you want me to create a separate video for this particular question uh do video for this particular question uh do mention it below i will mention it below i will create that as well create that as well let's let's discuss the second problem let's let's discuss the second problem so the second problem is basically we so the second problem is basically we are given an integer n are given an integer n and we have to transform this integer n and we have to transform this integer n to zero to zero by performing some operations we have to by performing some operations we have to we can perform we can perform two type of operation the first two type of operation the first operation is operation is change the right most bit change the right most bit to zero to zero if it is like change the right most bit if it is like change the right most bit basically if it is zero change it to one basically if it is zero change it to one if it is one change it to zero if it is one change it to zero similarly the second operation is we can similarly the second operation is we can change the if bit change the if bit if if i minus 1 bit is 1 and all the bits i minus 1 bit is 1 and all the bits after after i minus 1 which is i minus 2 to 0 all i minus 1 which is i minus 2 to 0 all are 0 are 0 so we have to find the minimum number of so we have to find the minimum number of minimum number of operations minimum number of operations that will be required to that will be required to make this n to zero so make this n to zero so let's understand this is an example so let's understand this is an example so let's say let's say the number is the number is one one one one zero zero zero then we can apply the zero zero zero then we can apply the second kind of operation so first second kind of operation so first operation is i think very straight operation is i think very straight forward just change the right most bit forward just change the right most bit so second second operation like if this so second second operation like if this is the number we can change this to this is the number we can change this to this because because this is the 8th bit let's assume so i this is the 8th bit let's assume so i minus 1 8th bit is 1 that's correct minus 1 8th bit is 1 that's correct and all the bits after i minus 1 is 0 so and all the bits after i minus 1 is 0 so that's where we can apply second kind that's where we can apply second kind second operation second type of second operation second type of operation here to convert this to this operation here to convert this to this but but notice that we can't notice that we can't uh if the number is this we can't uh if the number is this we can't convert it to convert it to uh this uh this because because if the bit is like if this is it bit if the bit is like if this is it bit then this is one that's fine but after then this is one that's fine but after this not all of them are 0 like this is this not all of them are 0 like this is not 0 right so that's where we can't not 0 right so that's where we can't perform this operation perform this operation so hope the question is now clear now so hope the question is now clear now let's just look at an example let's just look at an example let's say let's say we have to convert this convert 6 to 0 we have to convert this convert 6 to 0 and you have to find the minimum number and you have to find the minimum number of operations to do that so of operations to do that so 6 is represented as 1 1 0 in binary 6 is represented as 1 1 0 in binary so here so here what we have done is we have first what we have done is we have first performed the second kind of operation performed the second kind of operation so this is the ith bit so this is the ith bit and we can see i minus one bit is one and we can see i minus one bit is one and all the bits after this is zero so and all the bits after this is zero so that's where we can we have performed that's where we can we have performed second kind of operation to come second kind of operation to come to this stage to this stage from here we perform the first kind of from here we perform the first kind of operation operation to change the right most bit to change the right most bit from here we again perform the second from here we again perform the second kind of operation so basically this is kind of operation so basically this is the 8th bit in this case the 8th bit in this case so i minus 1 bit is 1 and all so i minus 1 bit is 1 and all the bit after this is zero so there is the bit after this is zero so there is nothing after this so we can assume that nothing after this so we can assume that everything is zero so that's where we everything is zero so that's where we have performed uh have performed uh this two and change this one to zero this two and change this one to zero after this we are going to perform the after this we are going to perform the first kind of operation to change this first kind of operation to change this rightmost bit to zero so in total we rightmost bit to zero so in total we have performed four operations to make have performed four operations to make this six to zero this six to zero right so that's the answer right so that's the answer now now as i keep on saying in every video as i keep on saying in every video if the question is difficult try to if the question is difficult try to solve a simpler version of the question solve a simpler version of the question so in this case so in this case one simpler version could be one simpler version could be let's try to solve the case where there let's try to solve the case where there is only one bit set so let's say this is is only one bit set so let's say this is the question the question and we have to convert this to and we have to convert this to 0 by applying these two set of operations only so now how to do that first of all let's think of what all operations we can actually apply so this operation we can apply every time because this is just the setting the right like changing the right most bit but the second operation is quite interesting notice that we have to change this particular bit to zero right so we can do this only with second operation so first operation only allow you to change the rightmost bit but if you want to change any other bit you have to use second operation so here we have to change this bit to zero right our final final goal so we have to use second kind of operation now once we are sure that we are using second kind of operation it indirectly means that we have to convert this to this somehow like somehow uh first this this will be made and from here we will then convert this we will then apply the second kind of operation to convert this to this basically to make the first bit as zero like now if this part is clear then like now if this part is clear then what is left is we have to convert this what is left is we have to convert this 0 0 0 0 0 0 to 1 0 0 somehow so our question now to 1 0 0 somehow so our question now becomes that we have to convert this 0 0 becomes that we have to convert this 0 0 to 0 to 0 to 1 0 0 by applying the same kind of to 1 0 0 by applying the same kind of operations operations so this is so this is equivalent to saying that we have to equivalent to saying that we have to convert convert 1 0 0 1 0 0 to 0 0 to 0 0 okay so these two are the same thing now okay so these two are the same thing now let's assume that let's assume that total x number of steps are required to total x number of steps are required to do so okay so do so okay so we have performed x number of steps we have performed x number of steps to convert this to this then we have to convert this to this then we have performed one more step to convert this performed one more step to convert this to this to this and then we have to perform again x and then we have to perform again x number of steps to convert this to zero number of steps to convert this to zero zero zero zero zero zero zero zero zero because because as as we have discussed like converting as as we have discussed like converting zero zero zero to one zero zero required zero zero zero to one zero zero required x step so converting one zero zero to x step so converting one zero zero to zero g zero will also require x step so zero g zero will also require x step so that's why we are doing like but that's that's why we are doing like but that's what we are doing here like converting what we are doing here like converting this one zero zero to zero zero zero this one zero zero to zero zero zero will require x steps so in total we require 2x plus one number of steps to convert this one zero zero zero to zero zero zero zero where x is the number of steps required to convert one zero zero to zero zero zero or zero zero zero two one zero zero now let's name this uh one zero zero thing so let's say uh if ith bit or let's name it j so if jth bit is set like but as you have discussed we have solved we are solving the case where there is only one bit set so let's assume that if jth bit is set the answer is denoted by f of j okay so f of j comes out to be 2 into x so what is x x is nothing but f of j minus 1 right so x denotes x denotes the number of the number of number of steps required to convert one number of steps required to convert one zero zero to zero zero zero so if zero zero to zero zero zero so if here if uh j is you can see j is zero here if uh j is you can see j is zero one two three third position so one two three third position so and one zero zero here j is second and one zero zero here j is second position right so that if f of j position right so that if f of j denotes the number of denotes the number of uh steps required to convert an integer uh steps required to convert an integer with jth bit set with jth bit set 2 0 0 0 then this is nothing but f of j 2 0 0 0 then this is nothing but f of j minus 1 right so what we have found is f minus 1 right so what we have found is f of j is nothing but 2 into f of j minus of j is nothing but 2 into f of j minus 1 plus 1 1 plus 1 okay so okay so if you don't understand this if you don't understand this equation equation i will strongly encourage you to rewind i will strongly encourage you to rewind the past five minutes of the video and the past five minutes of the video and rewatch it to understand this because rewatch it to understand this because this is the core of the solution this is the core of the solution now now it like what does it mean it means like it like what does it mean it means like let's say like we know f of one right f let's say like we know f of one right f of one is nothing but uh the number of of one is nothing but uh the number of steps required to convert steps required to convert the the uh or basically we know f of zero uh or basically we know f of zero like zero is the number of steps like zero is the number of steps required to convert the zero with uh to required to convert the zero with uh to convert the number with zero with bit convert the number with zero with bit set so basically if the number is one set so basically if the number is one which is and we have to convert this to which is and we have to convert this to zero then this is f of zero zero then this is f of zero so what is the number of steps required so what is the number of steps required here so one is the last bit right so we here so one is the last bit right so we can apply simply apply the first kind of can apply simply apply the first kind of operation and to convert and convert operation and to convert and convert this to 0. so f of 0 is 1 this to 0. so f of 0 is 1 now with this equation now with this equation f of 1 f of 1 would be would be 3 3 basically 1 into 2 plus 1 basically 1 into 2 plus 1 similarly f of 2 similarly f of 2 uh would be 7 uh would be 7 3 into 2 plus 1 3 into 2 plus 1 and so on and so forth so and so on and so forth so now hope this part is clear now hope this part is clear now if you remember now if you remember we had solved this part as a we had solved this part as a easier version of the original question easier version of the original question we haven't solved the original question we haven't solved the original question yet so now let's look at yet so now let's look at how to solve the original question how to solve the original question wherein we might have more than one bit wherein we might have more than one bit set so till now we have solved uh set so till now we have solved uh we we have solved one question wherein we we have solved one question wherein we are saying only we are saying only the jth bit is if only the iii set the the jth bit is if only the iii set the number of steps or number of steps or j if only jth bit is set then the number j if only jth bit is set then the number of steps required is f of j minus 1 of steps required is f of j minus 1 cross 2 plus 1 so we already know all cross 2 plus 1 so we already know all the answers the answers for for converting 1 to 0 converting 1 to 0 for converting 2 to 0 for converting 2 to 0 for converting 4 to 0 for converting 4 to 0 for converting it to 0 and so on and so for converting it to 0 and so on and so forth basically all the numbers which forth basically all the numbers which have only one bit set we already know have only one bit set we already know the answer for all of them the answer for all of them with this equation okay now with this equation okay now let's add one more bit to our uh let's add one more bit to our uh question so let's say we want to convert question so let's say we want to convert this to zero zero zero zero zero okay this to zero zero zero zero zero okay now now think about it so if you think about it so if you remember remember from one zero from one zero from from basically one zero zero zero zero basically one zero zero zero zero we have converted this to this we have converted this to this and in between we and in between we saw that this number was coming right saw that this number was coming right because what we have said is we convert because what we have said is we convert this to this and then from here to there this to this and then from here to there right right so so this one the converting this 1 0 0 to 0 this one the converting this 1 0 0 to 0 0 0 0 0 has has this part this part plus this part right and what we require plus this part right and what we require actually is this part actually is this part so what is this part this part is so what is this part this part is nothing but nothing but uh uh if we just want to find this part this if we just want to find this part this part is nothing but part is nothing but the number of steps required the number of steps required to to convert this to this like this total convert this to this like this total path path and minus number of steps required to and minus number of steps required to convert this to this right so let's convert this to this right so let's let's formalize it so basically let's formalize it so basically we are trying to find or we are trying to find or this time let's not denote it by f this time let's not denote it by f that's denoted by that's denoted by uh uh f dash okay so we are finding f dash okay so we are finding 1 1 1 1 0 0 0 0 answer number of steps required to answer number of steps required to convert this to 0 0. so what we have convert this to 0 0. so what we have said is this is nothing but said is this is nothing but the the number of steps required to convert this number of steps required to convert this to this minus to this minus number of steps number of steps required to convert this to 0 000 why basically we already seen that this path this entire this integer comes in between this conversion so this is like this entire conversion consists of the steps required to convert this from this and then from here to here so if we want the number of steps to convert from here to there we only require this part uh like this entire path minus this path so this path is nothing but to convert 0 0 0 to 1 0 0 right so that's what this path is so we have just found we have just come up with this solution okay now this like if you look at this it is now clear that what we are actually doing so now let's say let's talk about the three uh the case where there are three bit set so let's say this is the case that we are looking at or let me just change the color so let's say this is the case that we are looking at and you have to convert this to this so what we can say is the value of like the answer for this is nothing but uh the value of this f of 1 0 0 0 0 0 minus 0 1 0 0 1 0 0 1 0 0 1 0 okay okay that's the answer now that's the answer now how to find this is again the same same how to find this is again the same same like we have if we want to find this like we have if we want to find this this is again the same kind of equation this is again the same kind of equation like if we like if we let's break this as well so what we'll let's break this as well so what we'll say is say is the steps required here is this minus the steps required here is this minus f of 0 0 0 1 0 okay so that's what the number of steps is so now you can see uh this is zero so now you can see what we are doing is the first bit for the first bit we are adding this to our answer then for the second bit we are subtracting like if we just uh like this entire thing will be in braces right so if we just open up the brace this will be minus and this will be plus so for the second thing for the second bit we are subtracting it then for the third bit we are again adding it similarly if there are other bits we will again subtract it and add it so what we are doing on every like we will start with the first bit we will add that to our answer then for the second bit we will subtract that to our answer then for the third bit we will again add that to our answer so what intuitively what is happening is we are saying that to go from here to there like from this particular thing to zero zero zero zero we will encounter like we first go we will first think of going from this uh this entire like this the set where only one bit is set and which is the largest bit now in the path of going from here to here we will encounter this particular thing so let's subtract that path from here and we will get the answer so now when we subtract the path from here this is again the same problem where we are trying to say what is the number of steps required to go from here to zero so you again for again do the same thing we will again know that to go from here to there we if we start from uh this particular step we will encounter this in between so let's just do this and then subtract the remaining part so that's what we are doing so the solution is very simple for the first bit add f of that to the answer for the second bit my subtract f of that to the answer for the third bit again add f of that bit to the answer so let's try to look at the code quickly the code is very simple we just find f initially f of 0 has discussed it's one and all the other f we have just found with this simple equation f of j minus 1 cross 2 plus 1 now uh we will check all the set bits so let's say this uh this j bit is set so for the first j like if it is the first bit we will add that if it is the second bit we will subtract that if the third bit will add what we have done is initially we will what we have done is initially we will add this f of j to the answer add this f of j to the answer then then as soon as we add something we will as soon as we add something we will like uh like uh revert this one to zero so if we like we revert this one to zero so if we like we are just drawing it because are just drawing it because drawing one with zero will give us one drawing one with zero will give us one uh enjoying one with one will give us uh enjoying one with one will give us one zero so that's where one zero so that's where we are just drawing we are just drawing this so after this if if if value of this so after this if if if value of plus is zero then it will become one plus is zero then it will become one and if value of one was a value of plus and if value of one was a value of plus was was one it will become zero so that's one it will become zero so that's basically after uh whatever we have done basically after uh whatever we have done in in done with the jth bit done with the jth bit for the next bit we will do the opposite for the next bit we will do the opposite so if we have added this before we will so if we have added this before we will just subtract this afterwards so add just subtract this afterwards so add first then subtract then again add then first then subtract then again add then for subtract so so on and so forth until for subtract so so on and so forth until we have exhausted all the set bits of we have exhausted all the set bits of this this n n and finally written the answer and finally written the answer so hope you understand the solution i will link this problem and the interview experience in the description below in the next video we will be covering uh the next set of question which is this and this so stay tuned for the next video if you like the video give the video a thumbs up and do subscribe the channel as i told i am regularly publishing the video every day for different interview experiences so | 2024-03-15 18:19:31 | 1,611 | Linkedin Interview Question | 1611. Minimum One Bit Operations to Make Integers Zero |
|
xdMyL--dOqE | Rico's question is called longest consecutive sequence this has given an unsorted array of integers find the length of the longest consecutive element sequence so for this question a sequence could be something like 0 1 2 or 10 11 12 13 14 things like that then it says your algorithm should run an O of n complexity so for the example they give us there's the array 100 for 200 1 3 & 2 and in that array is the sequence 1 2 3 & 4 so how many numbers are in the sequence 1 2 3 & 4 that would be four numbers so the length is four and as a side note a sequence is also considered a streak so I'll be going back and forth between sequence and streak during my explanation all right I've purposely slightly modified the example in the question so we can see how to deal with duplicates let's think about what our end goal is at the end of this we have to determine what the longest streak is so we're going to look at each number and determine the length of the streak that it's involved in so a length from 1 to n so in the first case let's say the first number is 100 we're gonna somehow determine how long the streak it's included in is but let's say then we go to the next number the next number is also 100 but we've already determined the streak that the number 100 was involved in because we've seen it before now let's think about by the time we get to this over here that's also the number 100 if we kept the duplicates in we will have checked three times the length of the street that the number 100 is in do we really need to do this multiple times no we really only need to check it once so really the first thing we should do is remove any duplicates and we'll do that using a set and that's because a set by definition doesn't contain any duplicates so we'll add everything to a set and then we'll loop over only the numbers in the set because we know at that point that every number in the set is unique so after we add to the set our dataset would look more like this okay so now that every number in our dataset is unique what happens now let's start again with the number 100 to increase the streak we need to look at whether the number 101 is in the set is it no it's not so the current streak for the number 100 is 1 and since we can't extend that streak we can also say at this point that the global streak is also 1 because we've only looked at one number so far and it has a streak of 1 let's move on to the next number we need to reset the current streak to 1 but it's already 1 so you can't really tell in this case can we extend the streak for the number of 4 well we do know because of the example provided in the question that the number 4 is involved in a streak it's involved in the streak 1 2 3 4 so we shouldn't just consider the number that's one more than the number we're on we also have to consider the number that's one less than it but how do we actually go about doing that do we do something like we arrive at the number and we check if the number that's one number below it is in the set and if it is then we try to continue that streak and then also see if the number that's one number above that numbers in the set and try to continue that streak that would be unnecessarily complicated ideally we would find the lowest number in a streak let's say 1 and then only start counting the numbers in the from there so it's to do something like that we really do only have to consider if the number that's one greater than the number on is in the set but checking if the number that's one less than the number we're on does actually play a really important role let's consider the number we're on which is the number four we get to the number four and we check to see if the number that's one greater than it is in the set it's not now let's skip ahead a couple steps so let's say we're at the number one at the number one we check to see if the number that's one greater than it is in the set and we tried to create a streak that way so as the number that's one greater than one in the set which is the number two yes it is so we would have the number two can we keep that streak alive is the number that's one greater than the number two in the set which is the number three yes it is is the number that's one greater than the number three in the set which is the number four yes it is now is the number that's one greater than the number four which is the number five is that in the set no it's not so that streak is done but we know that eventually we'll get to the number three using the number three that streak we know will be three and four and then we'd get to the number two and we know that streak would be two three four notice how much duplication there is we've checked the number four one two three four times we've checked the number three three times and we've checked the number two twice this is not very efficient so what we can do instead is anytime we arrive at a number we can check whether the number that's one less than it is in the set if it is we know that the number were we'll already naturally be included in another streak and since it will be captured in another streak we can skip over it now and let the other Street captain so with that rule in mind we're gonna move on to the next number at this point the global streak is still 1 and the current streak is still 1 so let's move over to the number 200 first we check to see if the number that's one less than 200 is in the set because if it is we know that it will already be captured in a different streak so we don't have to worry about it now is 199 in the set No so now we can consider if the number 200 starts a new streak so is the number 201 in the set no it's not so the current streak is still 1 and the global streak is also still 1 now we move on to the number 1 is the number that's one less than 1 meaning the number 0 and the data set no it's not so now we can check to see whether the number 1 starts a streak so is the number that's 1 greater than 1 in the set well yes it is it's the number 2 so we know that this streak is at least 2 is the number that's 1 greater than 2 in the set yes it is so we add 1 to the current streak is the number that's 1 greater than 3 in the set yes it is the number 4 is in the set so we add another one to the streak and is the number that's 1 greater than 4 in the set no the number 5 is not in the set so our current streak ends at 4 so now that the current streak is done we can check is the current streak greater than the global streak well yes it is so now the global streak has to get updated to match the current streak all right so we're moving on to the next number which means we have to reset the current streak back to 1 because now we're going to be at the number 3 so is the number that's one less than the number 3 in the set yes it is the number 2 is in the set so we can ignore the number 3 because we know that the number 3 is already going to be captured or has already been captured in a different streak so the global streak remains 4 and the current streak remains at 1 all right so finally we're at the number 2 is the number that's one less than the number 2 in the set yes it is so we know that the number 2 is already going to be captured or has already been captured in another streak so we can skip over the number 2 and now we're at the end of the set so we know that the final answer is that the longest streak is 4 all right let's get to the code what lead code has given us is a function called longest consecutive which accepts an argument named gnomes and nums is just an array of integers so remember the first thing we have to do is create a new set so we'll say let's set equal a new set so now we add every number to the set so for let num of gnomes set dot add no so every number is added to the set at this point that would look like this this so it'll only have unique values all so it'll only have unique values all right so then we need to also keep track right so then we need to also keep track of the longest streak of the longest streak so we'll say let longest streak equal so we'll say let longest streak equal zero you can say over here longest zero you can say over here longest equals zero all right so now we have to equals zero all right so now we have to loop over every number in the set so loop over every number in the set so that's four let numb offset and this that's four let numb offset and this point would be here at the number 100 so point would be here at the number 100 so for every number we land on we have to for every number we land on we have to first check whether the number that's first check whether the number that's one less than it is in the set because one less than it is in the set because if it is we know that the number that if it is we know that the number that we're on either has already been we're on either has already been captured or will be captured in another captured or will be captured in another streak and in that case we can just streak and in that case we can just ignore it ignore it so we'll say if the set doesn't have the so we'll say if the set doesn't have the number that's one less than we're on number that's one less than we're on then we can continue all right and the then we can continue all right and the set does not have the number 99 so now set does not have the number 99 so now we can create a temporary variable that we can create a temporary variable that says let current num equal the number says let current num equal the number we're on and let the current streak we're on and let the current streak equal one so that it look like this current equals one all right so since the number that's one less than it is not in the set we can check to see whether or not the number we're on starts a new streak so we'll say while set has current num plus 1 so we check to see if the number that's one greater than it is in the set and if it is then we'll just see how many times that happens so we'll say current streak plus equals one and current num plus equals one so increment the count of the streak and increment the number by one until we no longer have a streak going all right then after we do that we just need to see which one is greater the current streak or the global streak so we'll say longest streak equals the maximum of either the longest streak or the current streak all right so now we go back to the diagram on the left the number 101 does not exist in the set so that streak is done so now we update the longest streak to equal the current streak because the longest streak so far only had the number 100 in it all right so now we move on to the next number which is the number four is the number that's one less than the number four in the set yes the number three is in the set so we know that the number four is going to be captured or has already been captured in a different streak so we can just move on to the next number is the number that's one less than the number 200 in the set no it's not so we can check to see if the number 200 starts a new streak is the number 201 the set no it's not so we just move on to the next number so remember that at this point the current streak is still 1 and the longest streak is still 1 also all right so we're at the number 1 is the number that's one less than the number one in the set no it's not so now we can see if the number one starts a new streak is the number that's 1 greater than 1 in the set yes it is that's the number 2 so our current streak is going to be updated to 2 so now we see how long this streak goes on is the number 3 in the set yes it is is the number 4 in the set yes it is is the number 5 in the set no it's not so our current streak ends at 4 so now that we're done with our current streak the longest streak now has to be updated to match the current streak since the current streak is greater than it so longest will be 4 we move on to the next number which means we reset the current streak to 1 we check if the number that's one less than the number 3 is in the set yes it is so we move on because we know that 3 is being captured somewhere else filing at the number 2 is the number that's one less than it in the set yes it is so we move on and now we're done so now we know that the only thing left to do is to return the longest streak all right let's run the code make sure it works yes it does all right so our solution was faster all right so our solution was faster than about 98% of other JavaScript than about 98% of other JavaScript submissions and it takes up less space submissions and it takes up less space than 100% of them so as usual you can than 100% of them so as usual you can find the code and written explanation find the code and written explanation down below and also in the description down below and also in the description our other algorithm resources similar to our other algorithm resources similar to this see you next time | 2024-03-21 11:35:39 | 128 | Longest Consecutive Sequence | LeetCode 128 | Coding Interview Tutorial |
|
4wlBBRo4tYY | [Music] hey guys welcome back to another video hey guys welcome back to another video and today and today we're going to be solving the lead code we're going to be solving the lead code question next permutation question next permutation all right so in this question we need to all right so in this question we need to implement next permutation implement next permutation which rearranges the number into which rearranges the number into lexicographically lexicographically next greater permutation of numbers if next greater permutation of numbers if such arrangement is not possible such arrangement is not possible it must rearrange it as the least it must rearrange it as the least possible order possible order so what that means is basically if you so what that means is basically if you reach the last arrangement reach the last arrangement we go back all the way to the beginning we go back all the way to the beginning okay so the replacement must be in place okay so the replacement must be in place so it happens in constant memory and so it happens in constant memory and here are some examples here are some examples inputs are on the left and the inputs are on the left and the corresponding outputs are on the right corresponding outputs are on the right all right so real quickly um all right so real quickly um in simple words what this question is in simple words what this question is asking is we're going to be given some asking is we're going to be given some sort of sort of order of numbers right and we need to order of numbers right and we need to find out what is the next permutation find out what is the next permutation going to be going to be and if you don't know what a permutation and if you don't know what a permutation is i'll be going over it real quickly is i'll be going over it real quickly okay so over here we have one two three okay so over here we have one two three and then we go to one three and two and then we go to one three and two since that's the next since that's the next uh permutation right uh then three two uh permutation right uh then three two one since that's the ending we're gonna one since that's the ending we're gonna go all the way back to the beginning go all the way back to the beginning which is one two and three which is one two and three and then one one five is going to end up and then one one five is going to end up being one five and one being one five and one okay so before we start off with the okay so before we start off with the question let's try to understand question let's try to understand uh what a permutation is and then we'll uh what a permutation is and then we'll look into different ways we can use look into different ways we can use to solve this question all right so i'm to solve this question all right so i'm not going to not going to spend too much time on this but let's spend too much time on this but let's just go through this real quickly so just go through this real quickly so let's say we have some sort of let's say we have some sort of uh box right and this box has three uh box right and this box has three numbers numbers one two and three and um think of these one two and three and um think of these as items and we can as items and we can place these items in three different place these items in three different locations so locations so each of the location is represented by each of the location is represented by an underline so think of this as an underline so think of this as location one location one location two location three right and location two location three right and our our job is to find all the possible job is to find all the possible combinations combinations or permutations they both mean the same or permutations they both mean the same thing right permutations can just be do thing right permutations can just be do think of them as different combinations think of them as different combinations to represent something to represent something so we need to find all these possible so we need to find all these possible combinations or permutations combinations or permutations of where we can put these items and of where we can put these items and we're going to follow the we're going to follow the lexicographical order lexicographical order and basically what that means is we're and basically what that means is we're going to start off with the smallest going to start off with the smallest number number possible so let's start off with our possible so let's start off with our first position over here first position over here and these are the numbers we currently and these are the numbers we currently have we have one two and three have we have one two and three so we'll pretty simply put we can either so we'll pretty simply put we can either have the number one have the number one two or three the first position can have two or three the first position can have any of these three numbers any of these three numbers and which one are we going to end up and which one are we going to end up choosing well we want the smallest choosing well we want the smallest numbers so we're going to choose the numbers so we're going to choose the smallest smallest value right so we're going to start off value right so we're going to start off with choosing the number one with choosing the number one so now that i put the number one we need so now that i put the number one we need to get rid of this to get rid of this from our list so just to kind of show from our list so just to kind of show that we got rid of it i'm going to that we got rid of it i'm going to underline it underline it okay so i'm underlining 1 there great so okay so i'm underlining 1 there great so now let's go on to our next step over now let's go on to our next step over here here what are the numbers we have left we've what are the numbers we have left we've already used up 1 so the numbers we have already used up 1 so the numbers we have left left are 2 and 3. so what are we going to put are 2 and 3. so what are we going to put here here well again we're going to put 2 because well again we're going to put 2 because 2 is smaller and we want to have the 2 is smaller and we want to have the smallest number smallest number and finally what are we going to be and finally what are we going to be having what are we going to be left with having what are we going to be left with well so we used up 2 i'm going to well so we used up 2 i'm going to underline it and the only number we have underline it and the only number we have left is the number 3. left is the number 3. so the only option we have is three so the only option we have is three so think of this as being our first so think of this as being our first combination combination one two three is the first combination one two three is the first combination we have we have and what is the next permutation for and what is the next permutation for this sequence of numbers going to be this sequence of numbers going to be well let's look at it step by step do we well let's look at it step by step do we have have any other number that we can put in this any other number that we can put in this place over here place over here well the answer is no we don't have any well the answer is no we don't have any other number that we could put there other number that we could put there because the only other option we have because the only other option we have was the number three was the number three so let's move back one more step let's so let's move back one more step let's go over here go over here so over here do we have any other so over here do we have any other numbers and the answer is yes numbers and the answer is yes so over here we could have either put so over here we could have either put the number two or we could have put the the number two or we could have put the number three number three and we chose to put the number two well and we chose to put the number two well because well it's smaller because well it's smaller but we've already looked at all of the but we've already looked at all of the combinations combinations we've exhausted all the possible we've exhausted all the possible combinations for two combinations for two in this place right and the only in this place right and the only combination was combination was well three so what we're going to do now well three so what we're going to do now is we're going to replace this with the is we're going to replace this with the other combination other combination so let's just get rid of this over here so let's just get rid of this over here and we also get rid of the three and we also get rid of the three okay and instead of the two we're gonna okay and instead of the two we're gonna do the three do the three so i'm circling three i'm gonna put so i'm circling three i'm gonna put three here so now we've used up one three here so now we've used up one and we've also used up three so what is and we've also used up three so what is the number we have left the number we have left well two so the only other option we can well two so the only other option we can put here is two put here is two so this is going to be our next so this is going to be our next combination one combination one three and two so this is where things three and two so this is where things change change what is going to happen over here well what is going to happen over here well over here over here we've exhausted all the possible we've exhausted all the possible combinations so we're done with that combinations so we're done with that in this position we've also tried both in this position we've also tried both the combination we've tried the the combination we've tried the combination of two combination of two and we've tried the combination of three and we've tried the combination of three so what we're going to do is we're going so what we're going to do is we're going to go to go back to the very beginning and over here back to the very beginning and over here we have three combinations we have three combinations so as it is we're done with all of the so as it is we're done with all of the possible combinations possible combinations of the number one right so we're done of the number one right so we're done with all of the combinations for the with all of the combinations for the number number one so now what we're going to do is one so now what we're going to do is we're going to try out the next possible we're going to try out the next possible value value which is well it's two so let's just get which is well it's two so let's just get rid of this real quick rid of this real quick okay so instead of one since we've tried okay so instead of one since we've tried all of its combinations we're going to all of its combinations we're going to have 2. have 2. well what are we going to have over here well what are we going to have over here and the other two numbers we have left and the other two numbers we have left are 1 and 3 are 1 and 3 and we're going to end up choosing 1 and we're going to end up choosing 1 since 1 is smaller and then the only since 1 is smaller and then the only other option we have other option we have is 3. so 2 1 and 3. so these are how is 3. so 2 1 and 3. so these are how permutations work permutations work and if you look at this at least when i and if you look at this at least when i saw this the first thing that i thought saw this the first thing that i thought of of was to use recursion in order to try all was to use recursion in order to try all of the possible combinations of the possible combinations until we find our next answer but until we find our next answer but as you think uh this would actually take as you think uh this would actually take up a lot of time up a lot of time which is very much unnecessary but which is very much unnecessary but instead there's actually a pattern that instead there's actually a pattern that we can look we can look forward to so let me just go back one forward to so let me just go back one step real quick step real quick so over here we have one three and two so over here we have one three and two well what is the number we ended up well what is the number we ended up changing changing the number we ended up changing is the the number we ended up changing is the value one value one and this actually comes in permutation and this actually comes in permutation so the thing is so the thing is once we reach a number or once we find once we reach a number or once we find some sort of descending pattern some sort of descending pattern so when you're going from one to three so when you're going from one to three we're increasing what we're we're increasing what we're in ascending order right but when you go in ascending order right but when you go from three to two from three to two we're descending right two is less than we're descending right two is less than three so what that means three so what that means is that you've exhausted all of the is that you've exhausted all of the possible combinations there are possible combinations there are because when you're at the biggest because when you're at the biggest number that means you've tried out all number that means you've tried out all the combinations because look the combinations because look over here we first write out two and over here we first write out two and then we tried out three then we tried out three so once we reach 3 it means that we've so once we reach 3 it means that we've already tried out the number 2 already tried out the number 2 and now we're at the last combination so and now we're at the last combination so once you find once you find any sort of descending pattern that any sort of descending pattern that means that that's going to be the end of means that that's going to be the end of that combination that combination so in this case we found a descending so in this case we found a descending pattern over here so starting from three pattern over here so starting from three all the way to two there's a descending all the way to two there's a descending pattern so what is going to be changed pattern so what is going to be changed well the numbers that's going to be well the numbers that's going to be changed changed is whatever is right before the is whatever is right before the descending pattern descending pattern and that's the value one and this is and that's the value one and this is what we actually ended up changing what we actually ended up changing so after all this we actually ended up so after all this we actually ended up making this making this two and then this became one and this two and then this became one and this became three became three so this is the pattern that we're going so this is the pattern that we're going to be following okay so let's say that to be following okay so let's say that we're given this number over here as we're given this number over here as our input and what we need to do is we our input and what we need to do is we need to find out the next need to find out the next possible permutation for it right possible permutation for it right and how could we do this well let's and how could we do this well let's follow the same step we need to first follow the same step we need to first look for some sort of descending pattern look for some sort of descending pattern and we need to change the number right and we need to change the number right before the descending pattern starts before the descending pattern starts so because of that i'm going to start so because of that i'm going to start off with putting a pointer off with putting a pointer at the last but one element and why am i at the last but one element and why am i doing the last but one element doing the last but one element well the reason for that is because we well the reason for that is because we actually want to find the position actually want to find the position of the element before the descending of the element before the descending order changes which is why i'm choosing order changes which is why i'm choosing this element this element okay and what are we going to compare okay and what are we going to compare this to we're going to compare it to this to we're going to compare it to its uh pre or its next element so its uh pre or its next element so in this case we're converting four to in this case we're converting four to three so our pointers currently has four three so our pointers currently has four and we're going to compare it with and we're going to compare it with three if four is less than three or in three if four is less than three or in other words if the previous element other words if the previous element is less than the next element then in is less than the next element then in that case that means we're in an that case that means we're in an ascending pattern ascending pattern but in this case this is not the case but in this case this is not the case four is greater than three that means four is greater than three that means that we have a descending pattern that we have a descending pattern and we're going to keep doing this until and we're going to keep doing this until we reach a point we reach a point where we find the end of this pattern so where we find the end of this pattern so we're going to move our pointer to 9 we're going to move our pointer to 9 and 9 is greater than 4 so that means and 9 is greater than 4 so that means we're still in a descending pattern we're still in a descending pattern now let's move it again so now we're at now let's move it again so now we're at 10 10 10 is still greater than 9 so we're 10 is still greater than 9 so we're still not done with our descending still not done with our descending pattern pattern and now we're moving it again and now we and now we're moving it again and now we have 2 have 2 and 2 is less than 10. so 2 and 2 is less than 10. so 2 is going to be kind of our turning point is going to be kind of our turning point so so after 2 is when the descending pattern after 2 is when the descending pattern starts and that makes sense starts and that makes sense we're going from 10 to 9 to 4 to 3 which we're going from 10 to 9 to 4 to 3 which is the downhill descending pattern is the downhill descending pattern and 2 is kind of our turning point so we and 2 is kind of our turning point so we know that know that 2 is the number that is going to change 2 is the number that is going to change and and what number is it going to change with what number is it going to change with so i'm kind of just going to divide this so i'm kind of just going to divide this over here over here and what is the number that it's going and what is the number that it's going to change with well the answer over here to change with well the answer over here is is we're going to take the next possible we're going to take the next possible number to 2 number to 2 and how do we know what the next and how do we know what the next possible number to two is possible number to two is well that's actually pretty simple to well that's actually pretty simple to find out we're going to look for find out we're going to look for whatever possible number we have whatever possible number we have which is right after two so what comes which is right after two so what comes right after two right after two in this case well it's the number three in this case well it's the number three and just to just for the sake of this and just to just for the sake of this example i'm going to add one more example i'm going to add one more element over here element over here which is going to be zero we need to which is going to be zero we need to find out what is going to be the number find out what is going to be the number that replaces two that replaces two and to do that we're going to start off and to do that we're going to start off from the ending so first we have the from the ending so first we have the number number zero so is the number going to be 0 well zero so is the number going to be 0 well no no because 2 is greater than 0 and that because 2 is greater than 0 and that means that means that technically we've already looked at 0 so technically we've already looked at 0 so we need to look at the next possible we need to look at the next possible number number then we have the number 3 and 3 is then we have the number 3 and 3 is greater than 2. greater than 2. so this is going to be the number that so this is going to be the number that is going to take the place of two is going to take the place of two so what we're going to end up doing is so what we're going to end up doing is we're going to replace these two we're going to replace these two so 2 is going to go in the place of 3 so 2 is going to go in the place of 3 and 3 is going to go in the place of 2. and 3 is going to go in the place of 2. so real quickly let's just do that so real quickly let's just do that okay so we're gonna add three over here okay so we're gonna add three over here and we're gonna put the two over here and we're gonna put the two over here so now we've replaced their positions so now we've replaced their positions well but this is still not well but this is still not our answer yet so now what we're gonna our answer yet so now what we're gonna do is since do is since we change the value from two to three we we change the value from two to three we change everything to the right change everything to the right as well a quick example is like when we as well a quick example is like when we saw one two and three saw one two and three and from one when we changed it to two and from one when we changed it to two we changed the next two positions as we changed the next two positions as well well the same way we're going to change the same way we're going to change everything to the right well how are we everything to the right well how are we actually going to change it actually going to change it and the answer to that is pretty simple and the answer to that is pretty simple we need to sort this we need to sort this in ascending order because well we want in ascending order because well we want the smallest the smallest to largest that's all we're doing right to largest that's all we're doing right and when you sort it you're going to get and when you sort it you're going to get 0 0 and this is going to become 2 this is and this is going to become 2 this is going to become 4 this is going to going to become 4 this is going to become 9 become 9 it's going to be 10. and over here you it's going to be 10. and over here you can notice one thing can notice one thing sorting it is the same as reversing it sorting it is the same as reversing it right so this is nothing else but right so this is nothing else but descending order descending order so all we could do is we can just so all we could do is we can just reverse it 10 9 4 2 0 reverse it 10 9 4 2 0 sorted is the same as when you reverse sorted is the same as when you reverse 1094 to 0. 1094 to 0. so instead of sorting it we can just so instead of sorting it we can just reverse it which actually takes place reverse it which actually takes place faster and that's what we're going to do faster and that's what we're going to do and once you reverse it this is what and once you reverse it this is what you're going to get you're going to get and you're going to end and you're going and you're going to end and you're going to end up replacing that to end up replacing that the original values with these new the original values with these new values on top values on top and this is going to be our answer so 0 and this is going to be our answer so 0 1 3 0 2 4 1 3 0 2 4 9 10 is our next iteration so i think 9 10 is our next iteration so i think once you understand this once you understand this it's the code part is actually the it's the code part is actually the simple part yeah so anyways let's get simple part yeah so anyways let's get right into the code right into the code okay so what i'm going to do is i'm okay so what i'm going to do is i'm going to start off by initializing going to start off by initializing a variable which holds the length of our a variable which holds the length of our numbers and the purpose that i'm doing numbers and the purpose that i'm doing that is because we're going to be that is because we're going to be calling the length calling the length quite a few times so we might as well quite a few times so we might as well call it once and just use the variable call it once and just use the variable instead instead okay so what i'm going to start off by okay so what i'm going to start off by doing is we're going to check doing is we're going to check a base gate so if our length is less a base gate so if our length is less than than or equal to 2 right so if our or equal to 2 right so if our the numbers is either a length of 1 0 the numbers is either a length of 1 0 or 2 then in that case we can just or 2 then in that case we can just directly return directly return the reverse of numbers so we can just do the reverse of numbers so we can just do num start reverse num start reverse and we can return that value and the and we can return that value and the reason for that is when you only have reason for that is when you only have two elements or even one in that case two elements or even one in that case you can just reverse it and give it back you can just reverse it and give it back because you only have because you only have two possibilities the first one is as it two possibilities the first one is as it is given in the input is given in the input and the second one as well is just going and the second one as well is just going to be the reverse so that's going to to be the reverse so that's going to take care of our base case take care of our base case and now what we're going to do is i'm and now what we're going to do is i'm going to assign a pointer going to assign a pointer and this is going to be the same pointer and this is going to be the same pointer that we were talking about that we were talking about in our example and the pointer is going in our example and the pointer is going to start off to start off at the last but 1 element so what is at the last but 1 element so what is that that's that that's going to be length minus 2. that's the going to be length minus 2. that's the last but one element last but one element so now what i'm going to do is i'm going so now what i'm going to do is i'm going to try to so now we're going to move to try to so now we're going to move our pointer until we find the ending of our pointer until we find the ending of some sort of descending some sort of descending right so how are we going to do that so right so how are we going to do that so first we need to check first we need to check if we reach the zeroth element right so if we reach the zeroth element right so while pointer while pointer is less greater than or equal to zero is less greater than or equal to zero so that checks for that and the second so that checks for that and the second thing we need to check is whether the thing we need to check is whether the current element we are on current element we are on is greater than or equal to the next is greater than or equal to the next element so what we're going to do is element so what we're going to do is we're going to do nums pointer we're going to do nums pointer so that's going to be the current so that's going to be the current element we're on and we're going to element we're on and we're going to check check if that is greater than or equal to nums if that is greater than or equal to nums pointer and we want to check the next pointer and we want to check the next number right so nums number right so nums pointer plus one sorry i cannot type pointer plus one sorry i cannot type okay there we go pointer plus one knobs okay there we go pointer plus one knobs pointer pointer all right so now that we go inside of all right so now that we go inside of this while loop each time we go inside this while loop each time we go inside of it we're gonna decrease the value of it we're gonna decrease the value of pointer and there you have it right of pointer and there you have it right but there might be a point where our but there might be a point where our pointer pointer reaches all the way to the zeroth index reaches all the way to the zeroth index and at that point the pointer is going and at that point the pointer is going to have a value to have a value of negative one and what does that mean of negative one and what does that mean so so let's say so we have the numbers three let's say so we have the numbers three two two and one right and in this case our and one right and in this case our pointer is going to end up having a pointer is going to end up having a value of negative one value of negative one because we're going to start off at the because we're going to start off at the first index then we're going to go to 3 first index then we're going to go to 3 and then we're going to and then we're going to decrease it one more time and we're decrease it one more time and we're going to start at leave going to start at leave end off with a value of negative one and end off with a value of negative one and when that happens that means that this when that happens that means that this is the last is the last iteration in this case as well 3 2 1 is iteration in this case as well 3 2 1 is the last iteration the last iteration and since it started we had a downward and since it started we had a downward descent descent and what that means is that we've and what that means is that we've exhausted all of the possible exhausted all of the possible combinations combinations and now we're going to go back all the and now we're going to go back all the way to the very first way to the very first combination and the very first combination and the very first combination is going to be the lowest in combination is going to be the lowest in value value and since we have the highest well the and since we have the highest well the lowest is just going to be the reverse lowest is just going to be the reverse of this of this so in this case if nums sorry yeah if so in this case if nums sorry yeah if our pointer is equal to negative one and in that case we're going to return nums dot reverse since we're just going to reverse it get it in ascending order and that's what we're going to return so now over here what we want to do is we want to try to look for the number so now our pointer is at some number and we want to look at the number that comes after it and to do that we need to iterate from the ending to the until the pointer so to do that we can just go inside of a for loop so for x in range and where is it going to start from it's going to start from the last number so to do that we can just do length minus 1 that gets us the index of the last number and we're going to go all the way up to the pointer so all the way up to but not including the pointer and how are we going to iterate through this we're going to decrease each time so negative 1. okay so inside of this for loop we're going to keep iterating through it until we reach a condition and this condition is when if nums pointer so whatever our number at the pointer is is less than whatever our value at this x index is and what this means is so we've currently found a number which is greater than our pointer and this is going to be whatever is the next number for our iteration so in this case uh we're going to re do that replacement right and to replace it we're going to replace num pointer and what are we going to so what are we replacing num pointer with well we're replacing that with the x value and similarly we also need to return replace the x value with the value of num's pointer so nums x is going to be equal to nums pointer nums and if you still don't what this is doing in simple words is that we found whatever is at the pointer and we found its next element and now we're just taking those two and we're replacing them right we're just switching their position that's all that's doing and after we do this we're done so we can go out of our for loop and we're going to break out of this so now we're out of our for loop and we do one last thing which is we need to take everything after our pointer and we do change that and reverse it so as it is everything after our pointer is in descending order so now we need to change it in ascending order and how can we do that well all we're going to do is we're going to first iterate through that so nums pointer plus one right we don't want to include the actual pointer but we want to include everything after that so everything first where the descending starts from and all the way to the end so the semicolon represents all the way to the end and what are we going to do to this well we're going to reverse it so we talked about this earlier all we're doing is we're reversing it and reversing it is the same as sorting it since it's already in descending order okay so real quickly how are we gonna so we're gonna do reversed and what are we gonna call the reverse function on well we're gonna call them the exact same thing which is numbs pointer uh plus one all the way to the ending and that should be it for our solution all right so now let's try submitting our okay and as you can see we got 83 faster okay and as you can see we got 83 faster than most people than most people and uh i don't know how this actually and uh i don't know how this actually works sometimes it says 96 sometimes 83 works sometimes it says 96 sometimes 83 okay anyway so our solution was accepted okay anyway so our solution was accepted and thanks a lot for watching guys do and thanks a lot for watching guys do let me know if you have any questions let me know if you have any questions i'll try my best to help you i'll try my best to help you and don't forget to like and subscribe and don't forget to like and subscribe if this video helped you thank you | 2024-03-20 08:37:12 | 31 | Next Permutation | Leet code 31 | Theory explained + Python code |
|
qy3kjvlZLpc | Question No. 981 & D Question In this time based key value, what do you remember from the value of the store? time based key value, what do you remember from the value of the store? If you code in Python, If you code in Python, then you must be remembering the dictionary from the key value. then you must be remembering the dictionary from the key value. Okay, if you Okay, if you do it in Aisi Plus, then from the key value. do it in Aisi Plus, then from the key value. do it in Aisi Plus, then from the key value. be the basis? How does Hashmat reduce? There is only one value and its corresponding values are stored. Now the value can be a unique value or a wait or a similar value or it can also be a list. What type of value is there on What type of value is there on What type of value is there on us, we can also store the class of the club, we us, we can also store the class of the club, we can store anything right, it depends on the can store anything right, it depends on the object, basically we can store the object, object, basically we can store the object, so the same thing is here, so the same thing is here, right, so this is understood, its question right, so this is understood, its question time. proved that right can store single value for that proved that right can store single value for that and what to do for the same, then it must be and what to do for the same, then it must be storing multiple values also, storing multiple values also, then it is the same thing, okay then it is the same thing, okay brother, I have understood the thing, after that it is written that brother, I have understood the thing, after that it is written that multiple values for D come from multiple values for D come from multiple values for D come from This line is important Different Times Stumps Now here let's discuss a little about what are the different time stands Okay so the way it is for example man take any course of yours is ok There is a video course you have different different time in it But if you want to make a note, then what you take a man on time, three units are being you take a man on time, three units are being added on time, okay, by doing this, you have your added on time, okay, by doing this, you have your value, okay then, okay nine, let's see, if you value, okay then, okay nine, let's see, if you look at me, what do you do when you make me laugh? look at me, what do you do when you make me laugh? We tell in it, brother, is it of integer type We tell in it, brother, is it of integer type or is it of string type, for us or is it of string type, for us string is right, string type is key and string is right, string type is key and value, what is value, integer string, value, what is value, integer string, something like this, but here I don't know what is there in the whole list, something like this, but here I don't know what is there in the whole list, one, his correspondent has made a list and one, his correspondent has made a list and do right. do right. do right. value is the string. After that we are waiting for it. See, from time to time we have our wait. So what can you do in Java. What you can do is this. We can do that with one foot class. There are gate There are gate There are gate values and one is by getting the key, it is okay, values and one is by getting the key, it is okay, so I take it that if my value is done or so I take it that if my value is done or my time stamp is done, then my time stamp is done, then what will be the value, anything of yours is fine, the what will be the value, anything of yours is fine, the value will be done, by doing this we can do something. value will be done, by doing this we can do something. Or you can create a custom class yourself, it's okay for you, whatever you want is up to you, whatever you want is up to you, right, something like this is happening here, now right, something like this is happening here, now look a little below it, what is written, look a little below it, what is written, we have to create a constructor, it's okay from time to time, the we have to create a constructor, it's okay from time to time, the hashtag that was created. hashtag that was created. hashtag that was created. refine the same, then we have to create a set function, okay, which will set it. Now the point comes that what kind of input do we have, man, take it as we have added outside right bar day, we have The time we were in will always be in The time we were in will always be in The time we were in will always be in increasing order, what will happen, what will increasing order, what will happen, what will not happen, so if you are getting an interview then this is a not happen, so if you are getting an interview then this is a very good question to ask, you very good question to ask, you can ask in your interview sir, can ask in your interview sir, I am I am getting the input in increasing order. getting the input in increasing order. getting the input in increasing order. random then what will be in it? If we get random then you can make it a tree map. To shortcut it, why do we have to write short b? For the get function, we will also discuss that, so let's reduce it by one. Let's quickly go into the question and see its constunt. What is written in the constunt, we will be getting all the content from D in time only, so we do not have to take the tension of sorting at all. Okay, here one thing is sorted, brother, we do not have to take tension of sorting, if there is So So So what has to be done in the gate, which is the gate, it will return itself, it will what has to be done in the gate, which is the gate, it will return itself, it will return, it will retain the value which is the time stem, which is the previous time, look, it is a simple thing, is three, now if we call the gate, what do we do in the is three, now if we call the gate, what do we do in the gate? gate? gate? so what will it do, if it is sorted inside it, then sorted bomb, can it be done? Either if you do linear search, then the end will open, if you do binary, then what will be the complexity? Okay, If we do binary search in the city, then If we do binary search in the city, then If we do binary search in the city, then what will happen by doing binary search? I what will happen by doing binary search? I found a van, I returned it, it had a value of ₹ 100, it was found a van, I returned it, it had a value of ₹ 100, it was fine outside, it was returned, now there is fine outside, it was returned, now there is no question here, so what does it mean, for What is the value inside then What is the value inside then what to do in case if you did not get me then I want you written d just un mean un just lower value just lower times time is ok for example if you did not get me then I want you written d just un meaning un just lower value just lower times time is ok for example if you did not get me then I want you written d just un meaning Yes, I Yes, I Yes, I will retain that, what is there in this, there is a van here, will retain that, what is there in this, there is a van here, instead of you, I get 4, okay, instead of you, I get 4, okay, what does it do for four, there is no pay for four here, but it is just a what does it do for four, there is no pay for four here, but it is just a small catch from four, so I small catch from four, so I part for three, you return here, okay part for three, you return here, okay If so, this thing is written in this line, okay, If so, this thing is written in this line, okay, I have got it and if I have got it and if no value is found in it, then no value is found in it, then what swing empty string do we have to retain in that case? what swing empty string do we have to retain in that case? Now which case is this? No value is found in it, Now which case is this? No value is found in it, Yadu's. Yadu's. Yadu's. I said food, food is not there, brother, what will you retain in our key, will you make a return? Or did you say that brother, it starts from my time, which is by the way, it If there is a If there is a If there is a five, then I have given a van, five, then I have given a van, you are closest to the van, but you are not small, so you are closest to the van, but you are not small, so I cannot return anything, in this I cannot return anything, in this also we will retain an empty string, so also we will retain an empty string, so all these are a few inches, so let's reduce one, let's quickly all these are a few inches, so let's reduce one, let's quickly move on to our code. move on to our code. move on to our code. and this is some of its importance. See, it is a construct. You have seen that set and gate have verified right and these are all gate verified right and these are all gate functions. So, if the first one is doing it outside. functions. So, if the first one is doing it outside. functions. So, if the first one is doing it outside. gate van, it is returned outside, then it is not there, does the van exist inside it, then if it is what is just smaller than five, then it is okay, there is a method to it, after doing the gate floor, then just Or we return equal value, Or we return equal value, Or we return equal value, okay, that is also an option, okay, that is also an option, but okay, in Hashmat, operation of Van More is but okay, in Hashmat, operation of Van More is done in people, so there done in people, so there can be some issue, friend, in this also we can be some issue, friend, in this also we do binary search, people in it will definitely happen. do binary search, people in it will definitely happen. do binary search, people in it will definitely happen. no problem, it's fine, it's our inbuilt class, it does it, if you want, you can make it custom, you must have given in the discussion how to make it custom [music] and I can do it directly for him. I had also told in the video that I can simply is my daughter, is my daughter, sorry, I am just explaining myself. 45 sorry, I am just explaining myself. 45 Absent, if it does not exist, then Absent, if it does not exist, then add us now, it is passing through it, add us now, it is passing through it, brother, what to add on it, first of all, brother, what to add on it, first of all, list. list. list. give arraylist of feet okay feet feet so what will I do [music] look feet is the key value and two values [ values of both are the pick of the gate which is values of both are the pick of the gate which is string string string what will be there in it, what will be the first value right what will be there in it, what will be the first value right here, what to do here list will be created, we have to give according to that and [ music] Han give the previous less equal one, so if I am looking for the time I am looking for the time I am looking for the time that I can do binary search inside it. that I can do binary search inside it. Okay, so we will do binary search. You Okay, so we will do binary search. You can do it by creating a function and we have to can do it by creating a function and we have to modify it a little bit. When you code the binary search, modify it a little bit. When you code the binary search, you will understand how we are you will understand how we are modifying it. That is correct right, after that when am now what do we have to do after this I have now what do we have to do after this I have you checked like now we have to apply some searching you checked like now we have to apply some searching algorithm so that we get that time algorithm so that we get that time algorithm so that we get that time what can I do inside this, I will return us a list, so first of all, let's take the list, okay, so map.get, what did I get here, if I got my list, search, okay. search, okay. search, okay. left and one right then left will start from zero and whatever is in right will start from or right index is ok ok give less equal to right and after this let Upon Upon Upon plus right - left is the data type, its maximum is 100 days and my right is at 100 and my left is at 50. When I sum it and divide it, then first sum will be on the right and what will be the sum of 100 never gone above 100, so this never gone above 100, so this method will also help you in the interview to find the method will also help you in the interview to find the middle, after that I have to middle, after that I have to check F Made becomes value then taking integer value when answer is found one is less and one is what is getting in the get we stored in the result what to do after that maybe maybe possible possible possible pinhocho somewhere before that so what you want you do this is what you want you increase a left you from zero you mid + 1 ok and what to do in this there is nothing to do in this It is big, it is big, so it It is big, it is big, so it It is big, it is big, so it cannot be my answer, so cannot be my answer, so I will simply equalize my rights, now what do I have to do, whatever I get the latest you went here, what do we have to do after this, you went here, what do we have to do after this, return return return return result Very good. Like I got the answer here or else I got the equal, I have to stop after doing adrevise and it will run till the entire meaning and the entire operation is completed, then the final will give its own result, then it and something else. and something else. and something else. you will understand. Have we taken the risk of creating a value based list, value is our list, why we had discussed that inside it we had to store two things, one value at a time, so for that I changed the class. That done, you can create a custom class if you want. If you want, you know how to create a custom class. What do we do in the map set? If we do not find our class, Par Par Par values time write gate gate has its own values time write gate gate has its own cool, in this we have first written the basic result cool, in this we have first written the basic result which can be the minimum which is an which can be the minimum which is an empty string, we have written that, empty string, we have written that, after that we check whether it exits, if it after that we check whether it exits, if it exists then reduce it. exists then reduce it. exists then reduce it. direct retain empty string, we had discussed that it is being returned in two cases, either our time stamp is smaller than the given one does not exist or our key does not exist, right then If it If it If it exists, then you want to do it, exists, then you want to do it, first of all we fetched the list and then first of all we fetched the list and then applied binary search in it. Okay whoever applied binary search in it. Okay whoever our very dancer can be, okay in this our very dancer can be, okay in this case give equal to all of them, we case give equal to all of them, we stored them in the result now. stored them in the result now. stored them in the result now. we got a valid answer, then we updated it. Well, not this, if we got another answer, then we read it and finally we have returned the result here. This The runtime of the part can be improved a bit, The runtime of the part can be improved a bit, The runtime of the part can be improved a bit, but the but the overall complexity is going to be different, overall complexity is going to be different, so there is no problem about it, no, we so there is no problem about it, no, we have it, it is fine, so people will do it, but this one is the gate function in the particular Has Map which we have created for If the one is going to be ok then I think the If the one is going to be ok then I think the If the one is going to be ok then I think the dates are good, submit it and see, it will be done now, dates are good, submit it and see, it will be done now, I had tried it, it is ok, gas, I hope you like the I had tried it, it is ok, gas, I hope you like the video, so please like, comment video, so please like, comment and subscribe, do it, and if there is any and subscribe, do it, and if there is any doubt, do it with me, thank you. | 2024-03-25 14:26:04 | 981 | JAVA | 981. Time Based Key-Value Store | HINDI | LeetCode Daily |
|
3hT80Pq8JM4 | hello developers let's start developing today we're going to take on The Daily today we're going to take on The Daily pration for on lit code for the 5th of pration for on lit code for the 5th of March so it's task 1750 we need March so it's task 1750 we need to we have a string and we need to keep to we have a string and we need to keep deleting the same parts of it until we deleting the same parts of it until we are left within unmanageable kernel are left within unmanageable kernel so let's start the minut so let's start the minut it's a relatively it's a relatively simple setup so we are given a string simple setup so we are given a string and we should return a number let's see and we should return a number let's see if our thingy if our thingy works so it's 1750 we're going to start works so it's 1750 we're going to start it and see if our test cases are running come on they should be yep they are running and basically even a sto clock is wrong is correct twice a day so for the second task we are supposed to get zero we are getting a zero we can easily change this to minus one but let's skip that part and let's see what we can actually do here so first thing is we're going to need to have a left and a say and first thing performance wise say and first thing performance wise that occurs to me is that string are that occurs to me is that string are kind of expensive to create and do so kind of expensive to create and do so instead of um managing it the creating new strings all the time we will just keep an index of the string where we are on the left or on the right so we're going to say that our left index initially is on the first thing the right will be on the second thing so we have two cases where we can return so yeah while left is less than the right I will delete this because I don't need that that will be my job to write need that that will be my job to write so one way that we're going to finish is so one way that we're going to finish is if this if this left becomes equal to if this if this left becomes equal to right if left becomes equal to right right if left becomes equal to right then we just need to then we just need to return return zero or do we I think we will have a zero or do we I think we will have a special case here so let's add another because if we a not that good guess but if we just a not that good guess but if we just have this then the result shouldn't be have this then the result shouldn't be zero it should be zero it should be one and it should be the same if we have one and it should be the same if we have not this but something like a a b b c CA not this but something like a a b b c CA and then we have CBA the result should be one because this a should not be removed but let's see what happens so we have on it on the left we have it on the right and then so if the left and the right are different then it's easy break the cycle and then we return yeah something like that because if the left is on one and the right is on zero then we have a string of length two so we are counting both of them so that's why we need to have that plus otherwise so if they're different no we otherwise so if they're different no we say they are the say they are the same so let's see if we can move on the same so let's see if we can move on the left so I will say left so I will say while yeah something like this while the while yeah something like this while the left is equal to the one after it move left is equal to the one after it move it and do the same thing with the right so yeah this will do so yeah this will do something now we will need to do something now we will need to do something else as well so in this case something else as well so in this case what we're going to have we're going to what we're going to have we're going to have a and a they are similar so now we have a and a they are similar so now we need to move the left here and need to move the left here and this so by the time we get here now it this so by the time we get here now it means that we are on this a and on this means that we are on this a and on this a so what we are going to do is now a so what we are going to do is now going to move them once more so we say going to move them once more so we say we are done with the A and move them we are done with the A and move them once more so increase left and in once more so increase left and in decrease decrease right let's see what does this code do yeah so we're going all the way until we there they not the same they're not in the same chain on letters and they that and we've gotten off somewhere so that and we've gotten off somewhere so the other test cases passed only the the other test cases passed only the test case when we were supposed to get test case when we were supposed to get to this failed why so we have C we have to this failed why so we have C we have C we have a we have a we have B and then C we have a we have a we have B and then we get the string a a hm let's isolate we get the string a a hm let's isolate that so if we have AA then the result that so if we have AA then the result should be actually zero we might need to repeat this code here or we might U actually give a hack or something like this that says well if you run past each other zero zero yep so in this case the left took this two a the right took this two a from the other side they removed them both and our right became zero our left become became two and now their difference is minus happens if if I say well if it's less happens if if I say well if it's less than zero then it's most likely zero this is a bit of a heck we're not we did not fix our algorithm basically we just ignored any values that we didn't like so it's not always a good take but in this case for these test take but in this case for these test cases it says it's okay and now comes cases it says it's okay and now comes the moment of Tru the moment of Tru how do we submit on lit code we take how do we submit on lit code we take this code we put it into the code tab of this code we put it into the code tab of lit code actually we can write it right lit code actually we can write it right here and yeah we have the same test here and yeah we have the same test cases always run your code first never cases always run your code first never submit directly because you might have submit directly because you might have some forgotten console logs some uh some forgotten console logs some uh other things that uh will basically other things that uh will basically break your code here or maybe you're break your code here or maybe you're using a another uh function or whatnot using a another uh function or whatnot but anyway until you see that all your but anyway until you see that all your test cases that you're working with are test cases that you're working with are accepted it makes no sense to submit you accepted it makes no sense to submit you will will just get a wrong answer or some kind of just get a wrong answer or some kind of other weird error so let's see if this other weird error so let's see if this works and yes this time we got lucky our works and yes this time we got lucky our algorithm algorithm basically even with the hecky uh basically even with the hecky uh Behavior actually Behavior actually worked our run times are not so bad you worked our run times are not so bad you can see that sometimes if I run it can see that sometimes if I run it differently it I might get a different differently it I might get a different uh result because to be honest there's uh result because to be honest there's not too much difference between 54.4 not too much difference between 54.4 megabytes and megabytes and 54.5 megabytes but note that we are not 54.5 megabytes but note that we are not uh allocating any strings we are not uh allocating any strings we are not doing anything we're just managing some doing anything we're just managing some integers integers so something like that so that's all for today we have our problem of the day solved and this is marked as a medium task but to be honest I find it quite quite easy it is a bit of a issue until you understand what's actually needed but once you do it is kind of on the easy side so keep developing don't forget to Mouse those button except the bed button don't touch | 2024-03-22 11:47:39 | 1,750 | LeetCode 1750: Minimum Length of String |
|
l6CEYty38b8 | hi all welcome back to another video from welcome back to another video from cracking the fang interviews cracking the fang interviews today i'm going to be talking about lead today i'm going to be talking about lead code 746 which is code 746 which is minimum cost of climbing stats minimum cost of climbing stats this is a popular problem from amazon this is a popular problem from amazon google google microsoft and netflix interviews microsoft and netflix interviews if you haven't already please check out if you haven't already please check out the climbing stairs problem the climbing stairs problem which is not the minimum cost which is not the minimum cost problem so this problem is an extension problem so this problem is an extension to that problem i'll leave a to that problem i'll leave a link to the problem in the description link to the problem in the description below below it builds on this problem builds on the it builds on this problem builds on the fundamentals we have established in that fundamentals we have established in that problem problem uh yep let's look at the problem uh yep let's look at the problem uh again here i have a snippet from lead uh again here i have a snippet from lead code code so what we've been given is a staircase so what we've been given is a staircase where each step has a cost associated where each step has a cost associated with it so if i were to draw this for with it so if i were to draw this for you you [Music] [Music] the way it would look like is step the way it would look like is step step one has a cost of zero you can step one has a cost of zero you can index this step index this step 0 in programming step 0 in programming step 1 or step 2 but let me let me just refer 1 or step 2 but let me let me just refer to indexes to keep it simple to indexes to keep it simple step 1 has a cost of 15 and step 2 has a step 1 has a cost of 15 and step 2 has a cost of 20. cost of 20. two and what they're asking you to do is two and what they're asking you to do is uh you you can the constrain here is uh you you can the constrain here is you start here or you start here you start here or you start here and you're allowed to take uh one step and you're allowed to take uh one step or two steps at once or two steps at once so if you start at 10 you can directly so if you start at 10 you can directly go to 20 go to 20 or you can go to 15 and then 20 or you can go to 15 and then 20 essentially essentially this is the concern of the problem what this is the concern of the problem what they want you to do is they want you to do is pick where to start first of all so pick where to start first of all so start start if you if you want to start at index 0 if you if you want to start at index 0 or 1 or 1 make that decision and once you decide make that decision and once you decide that that you essentially you know you essentially you know find the minimum cost uh sequence find the minimum cost uh sequence so if you remember in the previous so if you remember in the previous problems i've mentioned whenever you problems i've mentioned whenever you hear the words like number of subsets or minimum cost or anything with minimum or longest any superlative words right like minimum maximum longest smallest you need to be exhausted meaning to find what is the minimum you need to figure out everything else right if that makes sense logically so the only method you can use for that and recursion is uh is essentially and recursion is uh is essentially exponential time algorithm so it could exponential time algorithm so it could be u of 2 power n be u of 2 power n as previous problems that we have solved as previous problems that we have solved and the way you convert this into more and the way you convert this into more like a polynomial runtime meaning like a polynomial runtime meaning optimize optimize is dynamic programming and again if you haven't checked out my previous videos i highly encourage you to start with the recursion and dynamic programs programming series which this video is a part of the i have videos where i cover fundamentals with the fibonacci program then climbing stairs and then this minimum cost climbing states uh so this is a dynamic programming question and to quickly summarize the reason i um i think it is dynamic programming is i've been asked a global answer minimum right um so i have to figure out all permutations of climbing to to say which one is will will give me awesome so let's dive into the code awesome so let's dive into the code um so as i've always um so as i've always suggested whenever you're writing suggested whenever you're writing code with a dynamic programming solution you always need a base case and this base case is comes from the recursion right so think about it this way you you you you have this sequence of steps given to you and i'm going to quickly draw this again the and what you're doing is you're and what you're doing is you're essentially uh essentially uh this can also be represented in an array this can also be represented in an array so so for step one two the cost is 10 15 and for step one two the cost is 10 15 and 20. 20. what you're asked to do is essentially what you're asked to do is essentially uh find out what is the cost uh find out what is the cost to get to two the final step to get to two the final step and the constraints given were you can and the constraints given were you can take one step or you can take two steps take one step or you can take two steps at once at once if that makes sense so let's if that makes sense so let's try to you know since we said this is try to you know since we said this is recursion and we are recursion and we are now directly writing optimized code for now directly writing optimized code for dynamic programming dynamic programming we need to solve some problems so what i we need to solve some problems so what i mean is sub problem could be just mean is sub problem could be just you're given three steps just think of you're given three steps just think of one step at a time right one step at a time right so for this step what is the minimum so for this step what is the minimum cost cost you are you are you are required to you are you are you are required to start either here start either here at the zeroth step or the first step so at the zeroth step or the first step so the minimum cost here is going to be 10 the minimum cost here is going to be 10 because because you know you don't have any other you know you don't have any other alternative if you're just looking at alternative if you're just looking at this sub problem this sub problem but now if you are at index 15 uh what but now if you are at index 15 uh what is the minimum cost of getting to index is the minimum cost of getting to index 15 15 so the minimum cost could be directly so the minimum cost could be directly jumping jumping starting from 15 itself or starting from starting from 15 itself or starting from 10 and then going to 10 and then going to uh to 15 right so that's how i've uh to 15 right so that's how i've represented this here represented this here if the cost is 10 you can either if the cost is 10 you can either have the cost for the step one as 15 have the cost for the step one as 15 plus 10 plus 10 or 15 meaning you start at 15. or 15 meaning you start at 15. so you calculate that using this so you calculate that using this formulation in this case the minimum formulation in this case the minimum cost it will make sense to directly cost it will make sense to directly start from start from the index 15 rather than come from ah the index 15 rather than come from ah jump from 10 jump from 10 because it's going to add its own cost because it's going to add its own cost all right all right so we solved this um you know the sub so we solved this um you know the sub problem till here now problem till here now by solving the first sub problem by solving the first sub problem for 10 then the second sub problem for for 10 then the second sub problem for 15. 15. now let's solve the third third sub now let's solve the third third sub problem or the problem of uh problem or the problem of uh getting to 20 again getting to 20 again for getting to 20 right the for getting to 20 right the minimum uh cost minimum uh cost uh is could be um uh is could be um starting at 10 and then taking two steps starting at 10 and then taking two steps you can take two steps you can take two steps jumping to 20 or starting at 15 and then jumping to 20 or starting at 15 and then taking one step taking one step so the answer would look something like so the answer would look something like minimum 20 plus minimum of minimum 20 plus minimum of uh cost i minus 1 and uh cost i minus 1 and cos i minus 2 if that makes sense where cos i minus 2 if that makes sense where cos cos i minus 2 is the previous minus 1 and i minus 2 is the previous minus 1 and minus 2 are the previous two solutions minus 2 are the previous two solutions um and that's exactly what i've written um and that's exactly what i've written here here if you see as i go through uh the if you see as i go through uh the the array uh and the array uh and what i'm essentially doing is uh in this what i'm essentially doing is uh in this case the case the what would make sense is starting at 10 what would make sense is starting at 10 and taking uh and taking uh two steps and directly going to 20. so two steps and directly going to 20. so the cost will be 30 the cost will be 30 versus it could have been 35 if you had versus it could have been 35 if you had started started uh picked up from 15. uh picked up from 15. so essentially uh what we are doing is so essentially uh what we are doing is we are looping we are looping we set up the base cases first the base we set up the base cases first the base cases and then we start from index 2 so this is 0 1 2 we start from index 2 because the base cases for the previous two steps are set up and we iterate to n plus one which means uh uh we trade till n step n and if we are at the last index we we essentially just pick uh you know uh uh the the cost of the previous two meaning if you're jumping here which is the last index n so the question is actually asking us to go beyond these three steps um here so there's one extra step you need to make here if you just look at the example in the previous question but i've also seen a variant where they want you to get to the top step so both of these questions are valid um that's why you have an extra n plus one in the solution here itself and what you're doing is uh you know um essentially um just picking your current cost and evaluating based on previous sub problems from where should i pick or jump uh to get minimum minimum cost so you are looking for minimum you you solved all possible sub problems you are combining that to get your final result so the runtime for this is going to be time complexity is going to be o of n again here we directly wrote the optimized dynamic programming solution you could also have return recursive solution and then optimized it as we discussed with dynamic programming but the concept and the expression remains the same yeah i hope you liked the video thank you for watching cracking the fang interviews please like subscribe and share the video with your friends and leave a comment down below if you | 2024-03-21 12:21:35 | 746 | [Leetcode - 746] MINIMUM Cost Climbing Stairs [Dynamic Programming][Recursion] |
|
SjPfPzHuDLw | hey guys it's off by one here and today we're going to be solving container with we're going to be solving container with most water in this problem we're given most water in this problem we're given an integer array height of length n and an integer array height of length n and in this problem each index represents a in this problem each index represents a line that when drawn has the endpoints I line that when drawn has the endpoints I zero and I of height I so for example zero and I of height I so for example let's say we start at this point here let's say we start at this point here which is called that index 0 and the which is called that index 0 and the coordinates would be zero zero and 0 1 coordinates would be zero zero and 0 1 because that would be the height of this because that would be the height of this one right here one right here and then in this problem what they want and then in this problem what they want us to do is find two lines that together us to do is find two lines that together form a container and that this container form a container and that this container contains the most water contains the most water and in the end they wanted to return the and in the end they wanted to return the maximum amount of water that a container maximum amount of water that a container can store can store so for example here let's just take so for example here let's just take these two lines for example this one and these two lines for example this one and this one then the max water that can be this one then the max water that can be contained here is just here because we contained here is just here because we kind of have water that goes all the way kind of have water that goes all the way up to here up to here so basically What's Happening Here is so basically What's Happening Here is that we're forming a container using the that we're forming a container using the minimum of the two heights so if we know minimum of the two heights so if we know we're going to be calculating area let's we're going to be calculating area let's just get our formula so the way to just get our formula so the way to calculate the area of a rectangle is calculate the area of a rectangle is length times the height and our height length times the height and our height is just going to be the minimum between is just going to be the minimum between Bar number one and Bar number two let's Bar number one and Bar number two let's say we're doing the first and second say we're doing the first and second index so let me just write that down index so let me just write that down here height is equal to the min here height is equal to the min of our bars and for length what we're of our bars and for length what we're going to do is calculate the distance going to do is calculate the distance between this point and this point so for between this point and this point so for this example here we're only doing one this example here we're only doing one jump and that means that our length is jump and that means that our length is going to be one going to be one and if we were calculating these that and if we were calculating these that means we were doing two jumps here which means we were doing two jumps here which would make our length two would make our length two so our length is going to be the so our length is going to be the distance between distance between our lines our lines so now that we have that we can just so now that we have that we can just write this into some pseudo code write this into some pseudo code so our actual code would look something so our actual code would look something like this where the index of the second like this where the index of the second bar minus the index of the first bar bar minus the index of the first bar times the minimum of the two heights is times the minimum of the two heights is going to give us our area so let's say going to give us our area so let's say this is our first iteration this would this is our first iteration this would be I and let's say we're checking the be I and let's say we're checking the height of this one this would be J height of this one this would be J so now that we know how to calculate the so now that we know how to calculate the area let's see if we can think of a area let's see if we can think of a solution solution The Brute Force approach would be to The Brute Force approach would be to just just take the first iteration and check each take the first iteration and check each number in the array and keep track of number in the array and keep track of the max that way and then once you're the max that way and then once you're done going through the array once you do done going through the array once you do it again for the next number and then it again for the next number and then check for example e times six eight check for example e times six eight times two eight times five and then you times two eight times five and then you do that for every single element in the do that for every single element in the array and update the max as we go but array and update the max as we go but the problem with that is that it takes the problem with that is that it takes all of N squared time and this problem all of N squared time and this problem can actually be solved in linear time can actually be solved in linear time instead of going straight into the oven instead of going straight into the oven solution let's explore this all of N solution let's explore this all of N squared solution and see if we can get squared solution and see if we can get to it from here because I feel like that to it from here because I feel like that would be more useful than just telling would be more useful than just telling you the answer you the answer so to start our first Loop is iterating so to start our first Loop is iterating from zero to the end so or I would start from zero to the end so or I would start here here and then for our J you're going to start and then for our J you're going to start at I plus 1 all the way to the end and at I plus 1 all the way to the end and for each time we're iterating 3j we want for each time we're iterating 3j we want to find the area to find the area so our J will start here now I'm going so our J will start here now I'm going to write the result of the for Loop out to write the result of the for Loop out and then we can analyze them to see how and then we can analyze them to see how we can optimize our search we can optimize our search and here are the results so for I equals and here are the results so for I equals 0 we see that we start here at 1 and 0 we see that we start here at 1 and then our J will be initialized to here then our J will be initialized to here pointing to 30. so according to our area pointing to 30. so according to our area formula we do J minus I times the Min of formula we do J minus I times the Min of both Heights so for here we do J which both Heights so for here we do J which is one minus zero times the Min of one is one minus zero times the Min of one and thirty and the Min of 1 and 30 is and thirty and the Min of 1 and 30 is just one just one so we can see that we didn't even use so we can see that we didn't even use this 30 for any of these calculations this 30 for any of these calculations because we're bounded by our lower bound because we're bounded by our lower bound so what does this tell us well we can so what does this tell us well we can see here that our Max is 3 and that see here that our Max is 3 and that comes from looking at these edges comes from looking at these edges so maybe a smarter approach would be to so maybe a smarter approach would be to start by calculating the area for the start by calculating the area for the first and last index and then working first and last index and then working our way inwards our way inwards so let's try that here I've written a so let's try that here I've written a new example that contains different new example that contains different numbers and like we said we're going to numbers and like we said we're going to start start by calculating the area for these two by calculating the area for these two and the way that would be is is index 0 and the way that would be is is index 0 and this is index three and this is index three so our formula would be three minus zero so our formula would be three minus zero times the Min of three and four which is times the Min of three and four which is equal to three times three which would equal to three times three which would be nine be nine so now which pointer do we want to move so now which pointer do we want to move like I said earlier we are bounded by like I said earlier we are bounded by our lowest number so we want to move our lowest number so we want to move this three pointer to be pointing to ten this three pointer to be pointing to ten so we can just do that here and then so we can just do that here and then this would be the first index and then this would be the first index and then now we calculate our area again now we calculate our area again so index three minus index one times the so index three minus index one times the min min of of 10 and 4 well now our remain is going to 10 and 4 well now our remain is going to be 4 and this is going to be 2. so we be 4 and this is going to be 2. so we have 2 times 4 which would be 8. have 2 times 4 which would be 8. and then now we want to move the and then now we want to move the pointers again pointers again well this is now our bigger number so we well this is now our bigger number so we want to move our lower bound which will want to move our lower bound which will be this be this so now this pointer would be moved to so now this pointer would be moved to here here and then now we can calculate this area and then now we can calculate this area so we would have 2 minus one so we would have 2 minus one times the Min of 10 and 13. which is times the Min of 10 and 13. which is equal to 10. equal to 10. so now we can see that this gives us the so now we can see that this gives us the correct Max height and that this is the correct Max height and that this is the algorithm we can work with so let's just algorithm we can work with so let's just summarize what we learned here so we summarize what we learned here so we know we want to initialize the pointer know we want to initialize the pointer over here over here for our left point and a pointer over for our left point and a pointer over here for our right point and the way we here for our right point and the way we want to move the pointers is by seeing want to move the pointers is by seeing which of these points to the lowest which of these points to the lowest number so in this scenario left would be number so in this scenario left would be moved to the right by one moved to the right by one because it is lower than four and then because it is lower than four and then after calculating the area between 10 after calculating the area between 10 and 4 then we want to move our right and 4 then we want to move our right pointer to the left because we see that pointer to the left because we see that 10 is greater than four 10 is greater than four and at this point we would stop and at this point we would stop iterating because we don't want our left iterating because we don't want our left and right pointer to be put into the and right pointer to be put into the same spot so basically we want to Loop same spot so basically we want to Loop while left is left and right and if left while left is left and right and if left is pointing to a value that is smaller is pointing to a value that is smaller than the rate then we want to move our than the rate then we want to move our left pointer to the right because we left pointer to the right because we know that having a lower value does not know that having a lower value does not help us get a higher area help us get a higher area and we want to move our right pointer to and we want to move our right pointer to the left if right is pointing to a lower the left if right is pointing to a lower value so our code would look something value so our code would look something like this here and what we managed to do like this here and what we managed to do now is reduce these two four Loops to now is reduce these two four Loops to just a while loop using our two pointer just a while loop using our two pointer method and the way the while loop is method and the way the while loop is going to work is you find the area first going to work is you find the area first and then we check which of these has the and then we check which of these has the lower number and we update the pointer lower number and we update the pointer accordingly but what happens in a accordingly but what happens in a scenario where nums of left and nums are scenario where nums of left and nums are right are equal right are equal so here I've written an example that'll so here I've written an example that'll probably help us solve this case probably help us solve this case so I've already done the area for this so I've already done the area for this first iteration where left is at the first iteration where left is at the leftmost point and right is at the leftmost point and right is at the rightmost point and we can see that the rightmost point and we can see that the area is three area is three but now let's try and move our right but now let's try and move our right pointer to the left one because we're pointer to the left one because we're trying to figure out what happens so if trying to figure out what happens so if our right pointer is there now we want our right pointer is there now we want to calculate our area to calculate our area and we see that this is equal to two now and we see that this is equal to two now so we don't really get a bigger number so we don't really get a bigger number so let's just try and move them the so let's just try and move them the other way other way so a right pointer is not pointing to so a right pointer is not pointing to one again and now we're going to shift one again and now we're going to shift our left pointer to see if that makes our left pointer to see if that makes any difference any difference and the area for this would be and the area for this would be one one and we can see that it doesn't really and we can see that it doesn't really make a difference which pointer we move make a difference which pointer we move because in the end both pointers are because in the end both pointers are going to end up pointing to going to end up pointing to 4 and 6 and if we calculate the area for 4 and 6 and if we calculate the area for that we see that that we see that we get a new Max area of four we get a new Max area of four so what this lets us conclude is that it so what this lets us conclude is that it doesn't matter which pointer we move so doesn't matter which pointer we move so for our example we can just cross out for our example we can just cross out this condition and just move the right this condition and just move the right pointer to the left one now that we've pointer to the left one now that we've finished our pseudo code let's get into finished our pseudo code let's get into the real code the real code to start we just wanted to initialize to start we just wanted to initialize our left pointer to be equal to zero and our left pointer to be equal to zero and our right pointer to be equal to the our right pointer to be equal to the length of nums minus one or I guess it's length of nums minus one or I guess it's height in this problem and additionally we want to initialize a global Max and this is how we're going to keep track of our maximum area and we're just going to start with zero since we're promised in a problem that we're not going to have any negative numbers and then from here we just do what we did in this middle code so while left is left and right and from here we're going to use our and from here we're going to use our formula so right minus left formula so right minus left times the Min of height of left times the Min of height of left and height of right and height of right and this is going to give us the current and this is going to give us the current area for whatever we're pointing to and area for whatever we're pointing to and then from here we just want to check if then from here we just want to check if current area is greater than our Global current area is greater than our Global Max we just want to update our Global Max we just want to update our Global Max to be equal to our current area Max to be equal to our current area and once that's done all we want to do and once that's done all we want to do is check if height at the left is check if height at the left is less than height at the right is less than height at the right this means that this means that our height at the left is smaller and we our height at the left is smaller and we want to shift that because there's no want to shift that because there's no use in using that anymore so left is use in using that anymore so left is going to increment by one going to increment by one otherwise we just want to decrement our otherwise we just want to decrement our right pointer and that's pretty much it right pointer and that's pretty much it after that we just want to return our after that we just want to return our Global Max and that should work Global Max and that should work so as you can see this solution is so as you can see this solution is pretty efficient and now we'll step pretty efficient and now we'll step through the code manually through the code manually so to start we just want to initialize so to start we just want to initialize our pointers and our variable to keep our pointers and our variable to keep track of the max which I've done here track of the max which I've done here and named it Max and our variables for and named it Max and our variables for left and right are initialized to zero left and right are initialized to zero and eight and I'm going to write them and eight and I'm going to write them here just so we can see them a little here just so we can see them a little clearer too clearer too so now we want to do wild left to left so now we want to do wild left to left and right which it currently is we and right which it currently is we calculate the area using right minus calculate the area using right minus left and the Min of whatever the height left and the Min of whatever the height we're at so for this current one we have we're at so for this current one we have seven and we have one the Min between seven and we have one the Min between those two is just one those two is just one and right minus left is eight so our and right minus left is eight so our current area is eight and we see that current area is eight and we see that the current area is greater than our the current area is greater than our Global Max so we're going to update that Global Max so we're going to update that as well and now we check is the height as well and now we check is the height at left less than the height at rate at left less than the height at rate yes because 1 is less than seven so now yes because 1 is less than seven so now we can move our left pointer to the we can move our left pointer to the right one right one and now we start over our current area and now we start over our current area is now going to be eight minus one for is now going to be eight minus one for right minus left and the mid height is right minus left and the mid height is going to be going to be 7 because 8 is greater than 7 and so now 7 because 8 is greater than 7 and so now our area is going to be 7 times 7 which our area is going to be 7 times 7 which is 49. is 49. so our current area is Now 49 and that's so our current area is Now 49 and that's greater than our Global Max as well so greater than our Global Max as well so we're going to update that and now we we're going to update that and now we check is the height at left left and check is the height at left left and height at right no so we want to height at right no so we want to decrement our right pointer by one decrement our right pointer by one now we go to the next iteration now we go to the next iteration current area right minus left which is current area right minus left which is let me update this as well let me update this as well seven minus one and that will give us 6. seven minus one and that will give us 6. and the minimum between eight and three and the minimum between eight and three is three so we would have six times is three so we would have six times three which is eighteen three which is eighteen and that is not greater than our Global and that is not greater than our Global Max so we're not going to update it and Max so we're not going to update it and now we check is the height at left last now we check is the height at left last and height at right no because 8 is and height at right no because 8 is greater than three so now we decrement greater than three so now we decrement our right pointer by one our right pointer by one and now we calculate our area again so and now we calculate our area again so right minus left would be six minus one right minus left would be six minus one which is five and we multiply that by which is five and we multiply that by the Min of the height of left and height the Min of the height of left and height of right which would be eight of right which would be eight so it would be five times eight which so it would be five times eight which will give us 40. and now we check is our will give us 40. and now we check is our current area greater than our Global Max current area greater than our Global Max no because our current area is 40. so no because our current area is 40. so now we just go to the next if statement now we just go to the next if statement so if height of left is less than a so if height of left is less than a height or right which is not because height or right which is not because they're equal and like we mentioned it they're equal and like we mentioned it doesn't matter how we decrement our doesn't matter how we decrement our pointer for this code we just decrement pointer for this code we just decrement it the right by one it the right by one so I'm going to do that so now our right so I'm going to do that so now our right pointer is here and now we do this code pointer is here and now we do this code again again current area is equal to right minus current area is equal to right minus left which is four left which is four and we multiply that by the Min of eight and we multiply that by the Min of eight and four which is four and that will and four which is four and that will give us 16. give us 16. and that is not greater than our Max and that is not greater than our Max height so we're going to check if height height so we're going to check if height of left is less than the height of right of left is less than the height of right and it's not because 8 is greater than and it's not because 8 is greater than four now we just shift our right pointer four now we just shift our right pointer to the left one and now we check the to the left one and now we check the area again red minus left that will be area again red minus left that will be three and the Min between eight and five three and the Min between eight and five is five and that will give us a current is five and that will give us a current area of 15. and that is not greater than area of 15. and that is not greater than our Global Max so now we just check is our Global Max so now we just check is height at left less than the height at height at left less than the height at right no because 8 is greater so we do right no because 8 is greater so we do decrement or right pointer again decrement or right pointer again and now we have current areas equal to and now we have current areas equal to right minus left which is 2 times the right minus left which is 2 times the Min between eight and two which is two Min between eight and two which is two so our current area is four which is not so our current area is four which is not greater than our Global Max so now we greater than our Global Max so now we just check where we move our pointer just check where we move our pointer hide it left is not less than height of hide it left is not less than height of two so two so we just decrement the right pointer by we just decrement the right pointer by one one and now we do our last check current and now we do our last check current area is equal to right minus left which area is equal to right minus left which is one is one and the mean between eight and six to and the mean between eight and six to six and this will give us a current area six and this will give us a current area of six which is not greater than our of six which is not greater than our Global Max and now we just shift our Global Max and now we just shift our right pointer to the left one again right pointer to the left one again and says our pointers are now equal this and says our pointers are now equal this while statement exits out and we return while statement exits out and we return the global Max which is 49 and that is the global Max which is 49 and that is true because that is one of the examples true because that is one of the examples we had we had this video helped you in any way don't this video helped you in any way don't forget to like And subscribe thanks for forget to like And subscribe thanks for watching and I'll see you in the next watching and I'll see you in the next video | 2024-03-19 12:33:56 | 11 | Container With Most Water - Leetcode 11 - Blind 75 Explained - Arrays - Python |
|
0_ItVVrqFmA | hello guys today's problem for lead code is minimum today's problem for lead code is minimum number of Arrow to burst a balloon number of Arrow to burst a balloon so they will be given 2D array of Point so they will be given 2D array of Point uh X starting point from X X start and uh X starting point from X X start and ending point ending point okay so there will be a balloon which okay so there will be a balloon which starts from uh starts from uh start from 0 till end okay so it always start from 0 till end okay so it always this should be lower and this should be this should be lower and this should be higher we got this point from this higher we got this point from this denote a balloon whose horizontal denote a balloon whose horizontal diameter stretches between so between X diameter stretches between so between X star so whatever the number you start star so whatever the number you start till end you don't need to uh know the till end you don't need to uh know the exact y coordinate okay so no needs for exact y coordinate okay so no needs for y coordinate Arrow can be sought up y coordinate Arrow can be sought up directly vertical so directly vertical directly vertical so directly vertical we can sort we can sort from different point of exercises from different point of exercises a balloon with X array a balloon with X array and x x start and accent is busted by an and x x start and accent is busted by an arrow stood at x if x dot is less than arrow stood at x if x dot is less than or equal to X or less than or equal to x or equal to X or less than or equal to x n day is n day is no limit to the number of arrow that can no limit to the number of arrow that can be sought a short Arrow keeps traveling be sought a short Arrow keeps traveling with the infinite bursting any volume in with the infinite bursting any volume in the part okay okay so we are given here the part okay okay so we are given here so so there is 10 16 2 8 1 6 1 7 2. so the there is 10 16 2 8 1 6 1 7 2. so the auto took like the solution took six and auto took like the solution took six and he busted two eight and one six how we he busted two eight and one six how we passed it to uh have you busted to it so passed it to uh have you busted to it so it's middle of between between two and it's middle of between between two and six middle like in this equation they six middle like in this equation they told if it is mid in between so it will told if it is mid in between so it will get busted and here also it is an edge get busted and here also it is an edge so it will get busted so here is equal so it will get busted so here is equal so if so if that's that's the reason it so if so if that's that's the reason it will get burst so another point the will get burst so another point the shooter took is 11. why he took 11 so it shooter took is 11. why he took 11 so it is between 10 and 16 and is between 7 is between 10 and 16 and is between 7 and 12. so 11 is an ideal uh idle point and 12. so 11 is an ideal uh idle point to suit and arrow so how we can solve to suit and arrow so how we can solve this this so first approach is to sort that so first approach is to sort that how to sort the array so let's see we how to sort the array so let's see we will sort the array by using Lambda will sort the array by using Lambda function function Dot Dot thought so I'm telling you why I took thought so I'm telling you why I took sort sort we will sort the array points we will sort the array points comma so how should I sort it uh I comma so how should I sort it uh I should sort it in Lambda function should sort it in Lambda function so 0.1 comma point two so here integer we have to compare if it so here integer we have to compare if it is more integer is more integer Dot Dot compare we understood a problem what I am doing here you have to approach it huh compare P of 1 of P of uh what if you have to compare we have to compare the first element of every element so you know we have to compare the last element what is the last element of this array so compare one and comma P comma 2 to compare 1. so what does this does here so here these are given error 10 16 2 8 1 6 and 7 2 in the 2D array the 10 question is two weight is there uh 160 167 7 12 step so what I did here spend right here what I did here I used array Source I used points P1 and P2 and I used this Lambda function here after compending here it sorted in in the ascending order so wait but it started from like six is uh lower than eight eight n to where n16 without even considering this I use the Lambda function to compare only this element this element I compare only this element so it got sorted into the this range it got sorted this so the results are this much so 1 6 2 8 7 2 and 10 16. so I how I'm approaching this solution I will take uh I will take 6 has a main point I will take 6 has a main point it will suit the arrow it it will suit this Arrow it will also suit this Arrow but it can't suit this Arrow so I have to use another arrow here I will take this Arrow as 12. I will take this Arrow exercise to it so this also will get sorted and this also will get sorted so what I am doing here I will take a first element first element is 6 so I have to take I have to take the how much error should be sorted how much error should be suit so first Arrow should always shoot and I have to take the X X Point has I have to take X point x zero comma the maximum element is 1. the zero comma the maximum element is 1. the ending point we have to take call this ending point we have to take call this then I have to iterate to every solution then I have to iterate to every solution for for I I equal to 1 I less than points so I took lemon here so I took lemon here you have to attract to everyone so I you have to attract to everyone so I have to see if the what is advertise have to see if the what is advertise advertising here if this element is less advertising here if this element is less than uh is is more than this element than uh is is more than this element then it will be sorted you have to check then it will be sorted you have to check if if my x-axis my x-axis is less than is less than point point of I comma 0. so if that is the case I will have to foreign after that the x-axis will be will have a new value which I took here the new value is 12. so x axis will be the x axis will be point the maximum element it will take so I comma 1. and after finishing this Loop we have to return how much arrows is has been background so let's see yes it's running in all the test case so it got submitted it got submitted so if you have any doubt regarding the so if you have any doubt regarding the solution please message me please solution please message me please comment me and I will reply to it comment me and I will reply to it and if you like this video please do and if you like this video please do like it and do subscribe to my channel like it and do subscribe to my channel it will be great help thank you | 2024-03-22 14:22:43 | 452 | Minimum Number of Arrows to Burst Balloons #452|| Leetcode Daily Challenge Solution Java||#Java |
|
EVr0x96Wbec | hello everyone welcome to day 19th of august lootco challenge and today's august lootco challenge and today's question is question is maximum product or splitted binary tree maximum product or splitted binary tree in this question we are given a binary in this question we are given a binary tree and we need to find out the maximum tree and we need to find out the maximum products that can be generated by products that can be generated by splitting this tree at one possible end splitting this tree at one possible end and and how will you calculate uh the product it how will you calculate uh the product it would be equal to would be equal to the sum of the left subtree that you are the sum of the left subtree that you are splitting splitting into the sum of the right subtree that into the sum of the right subtree that you're splitting you're splitting without much to do let's look at the without much to do let's look at the presentation that i have created for presentation that i have created for this and i'll be explaining the question this and i'll be explaining the question as well as algorithm there itself maximum possible product or spitted binary tree lead code 1339 let's take the same example that was specified in the question we have a binary tree one two three four five six and let's hypothetically assume that we are making a split at this particular edge so what is the product if you make a split at this particular edge what one half of the tree is this one and other half of the tree is this one so what is the total sum of this part of the tree it is six what is the total sum of this part of the tree one plus three is four four plus two is six 6 plus 4 is 10 10 plus 5 is 15. so the product becomes 15 into 6 which is 90. so one possibility is 90. let me just erase it i think this 90 will go away let's store it somewhere we have 90. let's hypothetically assume we are making a split at this particular edge what is the sum of uh this subtree some of this up tree is nine sum of this part of the tree is 1 plus 2 is 3 3 plus 4 is 7 7 plus 5 is 12 so this is 12 and 12 into 9 is 1 0 8. so the other possibility is one zero eight so this is higher than the previous possibility so we got a better product as one zero eight let's try more possibilities and let's try and break the tree at this particular edge what is the sum of its uh right tree it is one plus three plus six is ten what is the sum of its left part of the tree it is four plus two plus five it's 11 so 11 into 10 is 110 which is greater than 108. so the max product becomes 108 so far and let's try for the other possibilities as well let me just erase it let's break the tree at this particular edge what is the sum of this part this part of the tree 1 plus 2 is 3 3 plus 5 is 8 8 plus 6 is 14 14 plus 3 is 17 so this is 17 this is 4 17 into 4 is 56 it's pretty small let's ignore it let's break the tree at this particular edge what is the sum of this part of the tree so 4 plus 2 is 6 6 plus 1 is 7 7 plus 3 is 10 10 plus 6 is 16 16 into 5 gives us 80 which is again lower than 110 so the maximum possible product that can be generated in this complete tree is 110 and where are you splitting the tree you're splitting the tree at this particular edge i hope you got the context now let's talk about how can we actually build the algorithm so let me just clear this up and please note that the maximum possible product is 110 let's get started the first thing that i'm going to do is to count the total sum that is there in this complete tree what is the total sum 6 plus 3 9 9 plus 1 10 10 plus 2 12 12 plus 5 is of 17 17 plus 4 is 21 so the total sum of this 3 is 21 and what i'm gonna do next i will try to calculate the sum of each subtree so let's try and calculate the sum of each subtree this is one subtree so the sum of the subtree is four sum of this subtree ending starting at two is four plus uh four plus two plus five which is 11 so the sum is 11. what is the sum of this subtree the sum of this subtree is 5 the sum of this 3 is 21 we have already calculated it the sum of this subtree including both these elements is 9 and the sum of this subtree is 6. we will be using this information to find out the maximum possible product and how will we do that let's assume we are making a break at this particular edge so one part of the tree will hold the sum as 4 the other part of the tree will hold the sum 21 minus 4 which is 17 so you got one possibility of the product let's assume we are breaking the tree at this particular edge so the sum of this subtree is 11 what is the remaining sum of the other part of the tree is 21 minus 11 which is 10 so you got the other part of the tree sum as 10 this product is higher than the previously calculated product 17 into 4 is lower than 10 into 11 therefore the max product value gets updated to 110 and we will do it across all the possibilities so let's assume we are making the cut at this particular edge the sum of one half of the tree is five the other half of the tree is 21 minus five which is 16 so the possibility for this splitting product is 16 into 580 80 is lower than 10 110 we will not update the max product value let's do it for the other possibilities as well let's assume we are making a break at this particular edge what is the sum of its left part of the three one half of the tree is nine the other would be twenty one minus nine which is twelve so twelve into nine is one zero eight which is lower than one one zero therefore we'll ignore it the other possibility is you are breaking the tree at this particular edge one half of the tree has the sum as six the other half of the tree will have a sum twenty one minus six which is 15 15 into 6 is 90 you will ignore this value because it is lower than 1 0. as we i traded through all the possibilities the maximum product that was generated in the system is 1 0 and that becomes our answer now let's talk about the coding section how will we actually code it up we'll exactly follow the same steps as i have told here the first thing that i have done is to define two variables the total sum variable that exists in the binary tree the other variable is a max product variable that will help me calculate my max possible product in this tree as a first step i have invoked my dfs method on the root so as to calculate the total sum that exists in the tree this is pretty straightforward method it is basically iterating the tree in a post order traversal fashion first the children and then the root and calculating the total sum you can use any other traversal for updating the total sum variable and once i have calculated the total sum i calculate the possible sum of all subtrees that are there in the binary tree and let's talk about this method so it is also iterating in a post order fashion it first calculates the total sum of the subtree starting with the its left root left child then its right side and then calculate the total uh subtree sum for the current root which is equal to left plus right plus root dot value and once i have that this value with me the total sum of the tree starting at the root i will calculate the possible product that would be equal to subtree sum into total sum minus subtree sum so this gives me one possibility of the product and as i iterate through all possibilities of subtrees my this variable will automatically will be chosen to the maximum possible value and in the end i simply return this subtree sum so as to process the other iterations accepted accepted once i have i am done with this once i have i am done with this iteration uh my maxim product variable iteration uh my maxim product variable will be updated and i have the performed will be updated and i have the performed modulus of dendrites number nine plus modulus of dendrites number nine plus seven seven as specified in the question as specified in the question i hope you got the context and enjoy i hope you got the context and enjoy today's session if you did please don't today's session if you did please don't forget to like share and subscribe to forget to like share and subscribe to the channel thanks for viewing it have a the channel thanks for viewing it have a great day ahead and stay tuned for more great day ahead and stay tuned for more updates from coding decoded see you updates from coding decoded see you tomorrow with another fresh question tomorrow with another fresh question till then good bye | 2024-03-20 12:33:13 | 1,339 | Maximum Product of Splitted Binary Tree | Leetcode 1339 | Live coding session 🌳🌳🌳🌳 |
|
1DkVU2i3sOA | Problem Maximum Points Pen Cards From Defense According to Looter Film Institute Actually course relatives and From Defense According to Looter Film Institute Actually course relatives and dedicated number of points deposit dedicated number of points deposit sediments in the interior sediments in the interior that in one step in the phone call from the that in one step in the phone call from the beginning and from the end through this trick 18 to beginning and from the end through this trick 18 to it Dr 10,000 points of cards it Dr 10,000 points of cards it Dr 10,000 points of cards taken in the interior records and educated Amazing School Question A I Want Global Economic Total Key Elements From This Ansh Mein Doctors And Waste Maximize System Navodaya Entrance Test How Twenty-20 Elements With This Element Song Start From Delhi And Sorry For Example In this case btake in all its In this case btake in all its In this case btake in all its elements from end submission is wealth elements from end submission is wealth that in this moment imported 221 limit we that in this moment imported 221 limit we start one element from end and two start one element from end and two elements of mother end and two elements of elements of mother end and two elements of observation made before in this case you have to take observation made before in this case you have to take off but from this off but from this Minister Yashwant ji's leader take this one and Minister Yashwant ji's leader take this one and Dasvand Someshwar and classic example Dasvand Someshwar and classic example from these parties you can 302 elements from these parties you can 302 elements from the last and one element from the beginning from the last and one element from the beginning and through the limits of mother and and through the limits of mother and submission date 212 so let's make this month year boy submission date 212 so let's make this month year boy death Sampur death Sampur death Sampur case that Bigg Boss to force vacancy for elements sweater the possible way in which they can take place for elements i.e. 16 same from the start and distance from Delhi and fungus start with 0 elements after beneficial for all elements Configuration Sugar Talking About Configuration Sugar Talking About Configuration Sugar Talking About Next Clarification Kutbi Technique One Next Clarification Kutbi Technique One Element We Start And Elements From And Don't Element We Start And Elements From And Don't Elements From Starting To Elements From Starting To Elements From And Learn From Start From Elements From And Learn From Start From And Stand For 200 Form And And Stand For 200 Form And A B C And D Possibilities In Which They Can A B C And D Possibilities In Which They Can Take Hadith's Elements And Right Take Hadith's Elements And Right Take Hadith's Elements And Right Most Wanted Whisper Choice Most Wanted Whisper Choice Configuration Vaikuntha Solution So this is the Configuration Vaikuntha Solution So this is the worst condition and definition of all the worst condition and definition of all the elements from the given in Physics 2ND Year elements from the given in Physics 2ND Year for elements of and definition of this and for elements of and definition of this and comes after 10 minutes Source of Information comes after 10 minutes Source of Information 20 Translation for Admissions 20 Translation for Admissions 20 Translation for Admissions variables this is the star solution design and mission so this was talking in this month and again starting elements of elements the worst element and three and elements of that are in the northern this vansh video channels pe 34 this vansh video channels pe 34 this vansh video channels pe 34 And Timings Of Finding This Mission Switch Off Finding Submission Of K Elements With Big Boss Time Inside And K Is Given Equal To And So Is Bhigo Friendship That Yesterday Morning Avengers Contributions And Its Contribution Stigma Of End Times Vikas soak fans Vikas soak fans Vikas soak fans on world notification screen system in on world notification screen system in the question also app lock messages sapoch hai the question also app lock messages sapoch hai so ifin vibration that they something baby notice for all are yaar morning have to give its formation and submission hua hai that somvanshi calculate the solution 2014 commission Elements and Starts Elements and Starts Elements and Starts Admission into Submission of Government Service Admission into Submission of Government Service 2013 Something is System Value Element Solution This is the Shyam 120 Ltd Plus Form of CON for B.Ed Admission Dates of Fact This Element Member Vikram Procedure and similar vaikunth add that of one to boy and subtraction from j&k of six sudhir and love you baby final submission in bhigo after fun to 100MB left and contributions which are being discussed like this and contributions known for its contribution to calculate the Fun Time For The Solution Fun Time For The Solution Fun Time For The Solution Will Welcome Bigger Of N Will Welcome Bigger Of N Which Improve Near Consent Which Improve Near Consent Mere Dil Se Poochhe That Tomorrow Also Sliding Mere Dil Se Poochhe That Tomorrow Also Sliding Window Ask Records Were Sliding Window Window Ask Records Were Sliding Window Late To Bigg Boss Window Base Line Late To Bigg Boss Window Base Line Window Ball Simrely Wednesday Element And Window Ball Simrely Wednesday Element And Use's Settings Beach Sexual Is This Use's Settings Beach Sexual Is This Use's Settings Beach Sexual Is This Windmills Flight From He Ya Dal 100 Million For This A Process Called Sliding Window Producer And Researcher In 100 Programming Problems Next To Nothing Sacred Waters Penance To Have In This Green Color Edge Sliding Window Will Consider To White Vinegar Sliding Window Self This regards This regards This regards 9 and gives winners 4 a 9 and gives winners 4 a number of elements between sliding doors and 5 - number of elements between sliding doors and 5 - producer 500 1000 considered as deadline to nine instead of producer 500 1000 considered as deadline to nine instead of maximizing sliding maximizing sliding window which will ask 100 maximizing between sliding window which will ask 100 maximizing between sliding doors and will right to minimize while doors and will right to minimize while sliding window sliding window is 8 and window described is 8 and window described is 8 and window described so 202 floor benefits flight from 125 danil flight from 216 in liquid and gas that however handling this is amazing submission sleep from this mission such an initial a very good condition will affect of zero from the same blood of five this episode configuration Deserve This Commission Which Comes Deserve This Commission Which Comes Deserve This Commission Which Comes Next Issue Collect Contribution Next Issue Collect Contribution Will Attract K Of Vansh Will Add 820 Suggestions Will Attract K Of Vansh Will Add 820 Suggestions Soen It Interesting You But Instead Of Having Soen It Interesting You But Instead Of Having No One Has Seen In The White Vinegar No One Has Seen In The White Vinegar Sliding Window And Sweet Minimize Sliding Window And Sweet Minimize Divided Into Divided Into A A Improve Maximize Dhanwant A A Improve Maximize Dhanwant Ki Nau Ki Nau Ki Nau solution by clearing big fan of the most difficult which will be so in this year brings implementing the which will be so in this year brings implementing the approach in which were approach in which were taking brightness setting Bluetooth switch on taking brightness setting Bluetooth switch on * Minimize sum of divide and edit * Minimize sum of divide and edit step will step will step will Will Be The Total Submission Vestige Mission - Dasham Se Dasham Is The Samudra Sliding Window Which White In Color Member Clan Is Video Ko Phanda 152 Submissions And Submission And Starts Admission And Will Keep Adding To The And from and And from and And from and submission a wicked sub setting on shadow submission a wicked sub setting on shadow time and will change the start and in witch time and will change the start and in witch state I state I finally Vitava aapse ha thank you finally Vitava aapse ha thank you digit pollution ki thi | 2024-03-21 01:20:06 | 1,423 | Maximum Points You Can Obtain from Cards |
|
OVrgu4u3TnQ | hey hey everybody this is Larry this is day 27 of the legal daily challenge hit day 27 of the legal daily challenge hit the like button hit the Subscribe button the like button hit the Subscribe button drama and Discord let me know what you drama and Discord let me know what you think about this part I mean apparently think about this part I mean apparently I haven't done before so yay let's do I haven't done before so yay let's do something fun uh or something like that something fun uh or something like that uh yeah I hope everyone's have a great uh yeah I hope everyone's have a great weekend having a great weekend uh when weekend having a great weekend uh when do we swing forward I feel like the time do we swing forward I feel like the time something I don't know but in any case something I don't know but in any case hope everyone's having a good week hope everyone's having a good week coming up uh and let's get started on coming up uh and let's get started on today's fun today's fun please buy Miss 427 construct quiet please buy Miss 427 construct quiet trees tree trees tree given an N by n Matrix of zeros and ones given an N by n Matrix of zeros and ones we want to represent the grid with a we want to represent the grid with a quad tree we turn the root of a quad quad tree we turn the root of a quad tree representing the grid does this tree representing the grid does this notice that you can assign the right of notice that you can assign the right of a node to true or false when it's Leaf a node to true or false when it's Leaf is first and both are accepting the is first and both are accepting the answer okay I mean I I kind of know what a quad tree is so that's why I thought I've done this before but maybe not on lead code or is that a dad or maybe there's like a constructed quad 3-2 that I've done instead of this one but yeah let's take a look so if you have a grid of n by n and basically the idea behind a quad tree and we'll see if it's like uh divided by divisible by okay yeah divisible by two or something like this because basically the idea behind a cloud tree is kind of almost the same idea as uh a regular binary tree that goes only left and right um the way that I want to think about it it's kind of like divide and conquer right actually they actually have an image here but but the idea here is that okay you know we're a binary tree you know or or if you think about like um yeah binary representing say a One D away then you know um yeah something like that uh uh you know you could do it by half and then half the way would be you know and then you kind of compress it that way in a way the goal of this is to um well a couple of things maybe wait okay yeah yeah so uh because there are a okay yeah yeah so uh because there are a couple of ways you can think about it couple of ways you can think about it depending on the implementation or the depending on the implementation or the specification but the idea is that you specification but the idea is that you know you can kind of think about it as a know you can kind of think about it as a as a rudimentary uh compression scheme as a rudimentary uh compression scheme right where you know all the zeros are right where you know all the zeros are together then we can just eliminate the together then we can just eliminate the leaves right and then kind of divide and leaves right and then kind of divide and conquer conquer um um and that's the part of conquering so and that's the part of conquering so let's kind of let's let's get started I let's kind of let's let's get started I don't think there's anything that um don't think there's anything that um you know that tricky about it or or you know that tricky about it or or whether I think that the implementation whether I think that the implementation will kind of make the divide and conquer will kind of make the divide and conquer clear clear so so yeah let's get to it clear clear so so yeah let's get to it um also if you're watching now uh I'm I um also if you're watching now uh I'm I am going to do a bonus uh legal problem am going to do a bonus uh legal problem afterwards today I've guess I felt uh uh afterwards today I've guess I felt uh uh I feel a little bit better I don't know I feel a little bit better I don't know so yeah so we'll definitely do that so so yeah so we'll definitely do that so definitely hit the Subscribe button wait definitely hit the Subscribe button wait for that video and let me know what you for that video and let me know what you think uh because I feel like I don't think uh because I feel like I don't know if you don't like it then I don't know if you don't like it then I don't do it anymore right that's the end of do it anymore right that's the end of the day right or even if people like it the day right or even if people like it but they don't watch it then you know but they don't watch it then you know what's the point right uh okay so yeah what's the point right uh okay so yeah um um so basically we can maybe do something so basically we can maybe do something like oh constructions over here like oh constructions over here construct helper maybe I don't know construct helper maybe I don't know uh right and basically now you know if uh right and basically now you know if the way that I always think about these the way that I always think about these things like I kind of already did is by things like I kind of already did is by doing the 1D version and it just kind of doing the 1D version and it just kind of like spring go in an extra Dimension like spring go in an extra Dimension right so here you know maybe if we think right so here you know maybe if we think about you know a one day away where we about you know a one day away where we have the left bang and the right barrel have the left bang and the right barrel and then when you do right in Congo you and then when you do right in Congo you just take the middle and then you know just take the middle and then you know separate out that way separate out that way um in here we'll do the same thing um in here we'll do the same thing except for now we have except for now we have um um um up so upper left and the bottom right um up so upper left and the bottom right kind of um defines a square and from kind of um defines a square and from that square we can kind of construct it that square we can kind of construct it you can also do it in other ways with you can also do it in other ways with kind of um kind of um you know uh uh with like some sort of you know uh uh with like some sort of numbering system that's a base four numbering system that's a base four probably probably um you can probably construct it that um you can probably construct it that way similar to how you would con think way similar to how you would con think about a binary tree about a binary tree um you know you have zero two two X plus um you know you have zero two two X plus one zero two X plus two or something one zero two X plus two or something like this right on each of the notes you like this right on each of the notes you can kind of think about it that way and can kind of think about it that way and maybe do it maybe do it you know that that way with quad tree as you know that that way with quad tree as well uh not I'm not gonna do that but well uh not I'm not gonna do that but I'm giving you some ideas in case you I'm giving you some ideas in case you wanted to so yeah so let's just say we wanted to so yeah so let's just say we have left uh Left Right top bottom right have left uh Left Right top bottom right oops oops uh uh yeah and you can even maybe think of yeah and you can even maybe think of this like 8x this like 8x um maybe this is a little bit cleaner um maybe this is a little bit cleaner you know a x a y or something like this you know a x a y or something like this uh and then bxby or something same thing uh and then bxby or something same thing really right so then now here if left is really right so then now here if left is equal to top then we assume that you equal to top then we assume that you know know right is equal to oh wait that doesn't right is equal to oh wait that doesn't make sense hang on sorry whoops oh if make sense hang on sorry whoops oh if left is equal to right then top is going left is equal to right then top is going to bottom because we always divided by to bottom because we always divided by two anyway right on each of those two anyway right on each of those Dimensions so that means that this has Dimensions so that means that this has one element and then basically now we one element and then basically now we want to return a new node um of what's top left oh that's the note okay what's top left oh that's the note okay sorry I got a little confused I was like sorry I got a little confused I was like oh what is this but yeah basically the oh what is this but yeah basically the value will be grid of value will be grid of um um left top as we said this is uh they're left top as we said this is uh they're all going to be equal to each other all going to be equal to each other right left as you go to the right top as right left as you go to the right top as you go to bottom so so this is just one you go to bottom so so this is just one node right uh we have a sleeve so this node right uh we have a sleeve so this is going to be a leaf and then is going to be a leaf and then I think yeah I think yeah otherwise what do we do right well now otherwise what do we do right well now we just try to figure out the mid in we just try to figure out the mid in both ways both ways um I'm a little bit um I'm a little bit have to be a little bit careful about have to be a little bit careful about this one this one uh just because I'm really bad about it uh just because I'm really bad about it but plus I think this is good but it may but plus I think this is good but it may be off by one something like that right be off by one something like that right so mid X as you go to this uh mid y as so mid X as you go to this uh mid y as you go to uh right um and the way that I always like to think about it um is I use a use real numbers because I to to handle it off by ones right meaning that um and these are always going to be powers of two ish or off so so let's say 0 to 15 right um then the num the half is going to be seven so you want that zero seven and then eight to fifteen um both of which will contain eight elements right so that means that we won this myth to be part of the left so then you have a construct helper um left to top mid X um but why um and now this is just about well going through the cases right so yeah uh so let's just say so this is going to be the top left yeah maybe back up right um top right is going to be the same thing except for now um it's gonna be mid X plus one and then this is going to go to the right all right yeah okay yeah I just want to make sure and the way that I I didn't make this explicit but now I will right this is uh all coordinates uh inclusive you don't have to do it inclusively that's just the way that I do it um because I don't know you can definitely uh play around the other way but yeah bottom left is going to be mid y plus one oh wait whoops from the left Midwife plus one um it's going to go to the right no no no it's gonna go to Mid X and then it's going to go to the this as well oh you know this is right bottom yeah yeah okay and then bottom right is to go to to the same thing kind of but mid X plus one um it y plus one uh right and then bottom right okay so then now if top left that so now all the values are together then we we merge them right so that's basically then we just return a new super note of then we just return a new super note of you know this and then now it's gonna be you know this and then now it's gonna be a sleeve a sleeve uh or if it's gonna be true because now uh or if it's gonna be true because now it's a new Leaf it's a new Leaf um oh wait I have to check something um oh wait I have to check something do I have to check that the oil leaves yeah I guess we should check that they're all leaves okay okay then now now we just you know the okay then now now we just you know the value is going to be all the same as we value is going to be all the same as we know this is now a new leaf and then know this is now a new leaf and then yeah we don't have any leaves otherwise yeah we don't have any leaves otherwise otherwise we just return a node of otherwise we just return a node of um I guess the values don't matter right um I guess the values don't matter right that's what they say to true or false friendly oh wait is why you true or false is that no no it's just one and zero this is way no no it's just one and zero this is way weird that's they sometimes use true and weird that's they sometimes use true and force and then sometimes they use zero force and then sometimes they use zero and ones in the thing so I'm getting a and ones in the thing so I'm getting a little confused but either way it's the little confused but either way it's the same thing right so here it doesn't same thing right so here it doesn't really matter but by by uh notation of really matter but by by uh notation of us we just keep the uh thing and then us we just keep the uh thing and then you just top left top right bottom left you just top left top right bottom left bottom right right and that should be bottom right right and that should be good so now we do construct helper uh good so now we do construct helper uh from zero to n minus one zero uh oh wait from zero to n minus one zero uh oh wait no zero zero to n minus one and minus no zero zero to n minus one and minus one and I think this should be good one and I think this should be good hopefully if not then you know we have hopefully if not then you know we have to debug uh isn't that the syntax no that's awkward like this visualization kind of means like this visualization kind of means nothing to me to be honest so that's why nothing to me to be honest so that's why it's a little bit weird it's a little bit weird um and I guess this no what is what is um and I guess this no what is what is it printing it printing like tell me what is it printing is it like tell me what is it printing is it the value and then it's leave or the value and then it's leave or something no it's uh it's leaf and then something no it's uh it's leaf and then the the node value I guess because this the the node value I guess because this is telling me it's wrong but then I have is telling me it's wrong but then I have no idea how to look at this right no idea how to look at this right um is it not merging correctly um is it not merging correctly uh I think maybe I have to add a uh I think maybe I have to add a programs maybe some of this was a little programs maybe some of this was a little bit weird bit weird I don't know the order of operation but I don't know the order of operation but okay at least that's fixed okay at least that's fixed do I do the country did I did a math one all right so this claims that this but but really I think all these don't really um it's hard to tell what is actually wrong uh okay let's see if I haven't off by one maybe this is the bottom and it goes to the bottom left goes to Mid X but and then Midwife expose the bottom this oh what no this looks okay um um unless I'm doing it off by one somewhere unless I'm doing it off by one somewhere but hmm but hmm what is going on what is going on seems like I have a seems like I have a a much a node I decided how I didn't really leave it okay let's look at oh yeah this is one oh I see so zero one the value doesn't oh I see so zero one the value doesn't matter because it's not uh yeah so this matter because it's not uh yeah so this one doesn't matter it's a little bit one doesn't matter it's a little bit deceptive one one zero and this is really hard to tell how to and this is really hard to tell how to debug uh because I don't know what's debug uh because I don't know what's wrong with the or like wrong with the or like it's definitely not should be a zero it's definitely not should be a zero did I do the older one did I do the older one top left top right top left top right top left top right top left top right top right yeah bottom left bottom right top right yeah bottom left bottom right seems like I'm doing it right yeah I mean unless I mixed them I think that was the only thing maybe but hmm bottom left oh oh I see I think I mixed up my x's and y's my coordinates are flipped um um is that true am I lying to you I mean that's true I think that's probably why all right let's see how do I fix that because I use my left SX that's why okay okay so then we just hmm foreign now we have to change other things too I now we have to change other things too I think um all right I think I just confused my X and y's because I think my my my my left and right should be wise right so let's actually just go through that way so okay let's fix this and then now this means that this is y and this is X um okay I think that's okay and I think that's one okay and I think that's one ah I did confuse myself okay well that ah I did confuse myself okay well that did not fix it unfortunately but at least we can maybe look up one one no then hmm x to the bottom y one to the bottom right okay okay I think that I have I think this at least makes more sense now it's kind of embarrassing I don't think it's kind of embarrassing I don't think this is that hard but I'm just this is that hard but I'm just struggling with struggling with just kind of making sense of what this just kind of making sense of what this data is really to be honest but because okay so this is the root that's because okay so this is the root that's things things and then I don't know what these none and then I don't know what these none what these all these nodes mean because what these all these nodes mean because it doesn't match four of these right it doesn't match four of these right this is just such a terrible this is just such a terrible visualization scheme visualization scheme but uh is there any way to show this no but uh is there any way to show this no okay fine uh okay fine uh I think maybe it's time I give up on the I think maybe it's time I give up on the thing and then just thing and then just um and then maybe like you know okay so what I did was that I was trying to create a very simple case where I didn't have that symmetry so it would have to give me something well um so I guess hmm I mean this one doesn't matter what they say so it goes top left top right right top right is that hmm hmm top left is one top right top left is one top right huh huh so mid why it is screaming so it goes to so mid why it is screaming so it goes to zero one uh yeah so one inclusive so zero one uh yeah so one inclusive so this is going to oh I see because that's the thing that I oh I see because that's the thing that I didn't fix didn't fix because I got the wrong thing okay silly because I got the wrong thing okay silly Larry I fixed most of the other things Larry I fixed most of the other things but yeah it was just mixing up X and y's but yeah it was just mixing up X and y's that's the point that's the point and then I I fixed in all these code and then I I fixed in all these code except for I forgot about the base case except for I forgot about the base case that's why um because I was looking at that's why um because I was looking at the one one uh cell the one one uh cell um right well um right well uh what is the complexity here right uh what is the complexity here right um I mean it's gonna be linear time you um I mean it's gonna be linear time you look at each cell once look at each cell once um there are it's not true um there are it's not true yeah I mean maybe you can say there's a yeah I mean maybe you can say there's a lock for a log base for lock for a log base for um component no it gets each one gets merged not based four times I guess no no no because at verse it is going to no no no because at verse it is going to be linear because be linear because each cell okay yeah yeah so this is each cell okay yeah yeah so this is linear time linear space linear time linear space um the way that I think about it even um the way that I think about it even though it is a little bit complex it's though it is a little bit complex it's the same as uh as um the same as uh as um as the binary tree right so even though as the binary tree right so even though there are like n levels like base 2N there are like n levels like base 2N levels levels um but but actually the summation is um but but actually the summation is something like something like um you know and on the lowest lowest um you know and on the lowest lowest thing plus n over two plus n over four thing plus n over two plus n over four plus n over a plus dot dot dot right plus n over a plus dot dot dot right amount of work amount of work um and of course that sums to 2N and um and of course that sums to 2N and that is going to be all of n right that is going to be all of n right um and in this case it's going to be n um and in this case it's going to be n plus n over four plus n over 16 which is plus n over four plus n over 16 which is not even going to be 2N I don't think so not even going to be 2N I don't think so I don't actually don't know what it I don't actually don't know what it converges to but it'll be uh converges to but it'll be uh is that true hmm is that true hmm yeah I don't know but I I imagine it's yeah I don't know but I I imagine it's it's you know whatever right uh my math it's you know whatever right uh my math today is really bad I mean those of you today is really bad I mean those of you Google Notes convergent series note that Google Notes convergent series note that this converges but it's going to this converges but it's going to converge less than two times N I think converge less than two times N I think but yeah still all of n in either case but yeah still all of n in either case is my point so yeah linear time linear is my point so yeah linear time linear space and that's all I have with this space and that's all I have with this one let me know what you think hope you one let me know what you think hope you didn't make that silly mistake like I didn't make that silly mistake like I did but yeah stay good stay healthy take did but yeah stay good stay healthy take your mental health I'll see you later your mental health I'll see you later take care bye bye | 2024-03-22 11:16:33 | 427 | 427. Construct Quad Tree - Day 27/28 Leetcode February Challenge |
|
IIxoo93bmPQ | in this video we'll go over lead code question number 15 threesome now if you question number 15 threesome now if you haven't already seen my video on twosome haven't already seen my video on twosome I highly recommend you go watch that I highly recommend you go watch that first because threesome is very similar first because threesome is very similar to twosome but it's a bit harder the to twosome but it's a bit harder the link is in the description so please go link is in the description so please go ahead and watch that first okay now ahead and watch that first okay now here's the problem statement for here's the problem statement for threesome given an integer array nums we threesome given an integer array nums we need to return all the triplets num's I need to return all the triplets num's I nums J and nums K such that I J and K nums J and nums K such that I J and K are all different from each other and are all different from each other and the three values we pick must sum up to the three values we pick must sum up to zero the solution set also must not zero the solution set also must not contain any duplicate triplets so a contain any duplicate triplets so a Brute Force solution would run an O of n Brute Force solution would run an O of n Cube time so we're definitely not going Cube time so we're definitely not going to do that however you can see that this to do that however you can see that this is similar to twosome but there are a is similar to twosome but there are a few key differences first we need to sum few key differences first we need to sum up three values to zero instead of two up three values to zero instead of two values to a custom Target second we are values to a custom Target second we are returning the array values themselves returning the array values themselves not the indices and third and most not the indices and third and most importantly there can now be multiple importantly there can now be multiple Solutions and we need to return all of Solutions and we need to return all of them not just one as a result of this them not just one as a result of this new rule we also cannot return any new rule we also cannot return any duplicate Solutions and so this is going duplicate Solutions and so this is going to be the main differentiator from to be the main differentiator from Tucson if there was only one unique Tucson if there was only one unique solution like in twosome we could use an solution like in twosome we could use an outer loop to fix the number at index I outer loop to fix the number at index I and then just use the same exact and then just use the same exact solution as twosome with a hash table solution as twosome with a hash table the problem with this method is that our the problem with this method is that our solution for twosome doesn't account for solution for twosome doesn't account for multiple Solutions so we would end up multiple Solutions so we would end up returning duplicates for example if this returning duplicates for example if this is the array then our answer would is the array then our answer would include the array negative 1 negative 1 include the array negative 1 negative 1 and 2 2 since those three numbers add up and 2 2 since those three numbers add up to zero and also negative one zero and to zero and also negative one zero and one notice that the order in which the one notice that the order in which the numbers are in doesn't matter now numbers are in doesn't matter now there's another way to get zero here there's another way to get zero here which is to use these three numbers but which is to use these three numbers but we shouldn't include it in our answer we shouldn't include it in our answer because it's a duplicate of this answer because it's a duplicate of this answer so how will we find all solutions so how will we find all solutions without including duplicates well I'm without including duplicates well I'm going to be showing you a method that going to be showing you a method that first sorts the array then uses a first sorts the array then uses a two-pointer approach to solve this in O two-pointer approach to solve this in O of n Square time now let's look at the of n Square time now let's look at the code and solve this in Python let's say code and solve this in Python let's say this is the numbers array that we are this is the numbers array that we are given the first thing we're going to do given the first thing we're going to do is sort nums and you'll see why this is is sort nums and you'll see why this is important in a second next we'll create important in a second next we'll create an array that will hold our final answer an array that will hold our final answer then let's start the outer loop that then let's start the outer loop that fixes the first number using index I fixes the first number using index I notice that we only Loop until the notice that we only Loop until the length of nums minus two or in this case length of nums minus two or in this case 7 minus 2 which is 5 because we always 7 minus 2 which is 5 because we always need at least three numbers to sum up need at least three numbers to sum up now I'm going to explain this this line now I'm going to explain this this line a little more later but for now I is a little more later but for now I is equal to zero so this is false and we equal to zero so this is false and we just move on here we finally start the just move on here we finally start the two-pointer approach we're going to two-pointer approach we're going to initialize the two pointers L for left initialize the two pointers L for left and R for right and this is going to be and R for right and this is going to be our starting triplet the numbers at our starting triplet the numbers at index i l and R we're now going to start index i l and R we're now going to start the inner loop and keep going as long as the inner loop and keep going as long as the left pointer is less than the right the left pointer is less than the right pointer the first thing we're going to pointer the first thing we're going to do is calculate the total by adding up do is calculate the total by adding up the numbers at the three pointers so the numbers at the three pointers so that's going to be negative 4 plus that's going to be negative 4 plus negative 2 plus 5 which is negative one negative 2 plus 5 which is negative one now at this point three things can now at this point three things can happen the total could be less than zero happen the total could be less than zero greater than zero or if it's not either greater than zero or if it's not either of those then it must be equal to zero of those then it must be equal to zero right now negative one is less than zero right now negative one is less than zero so you can see that what we're about to so you can see that what we're about to do is increment L but let's take a do is increment L but let's take a second and think about why we're doing second and think about why we're doing this so because the array has been this so because the array has been sorted we know that the left pointer is sorted we know that the left pointer is pointing to the smallest number in the pointing to the smallest number in the array to the right of I and on the other array to the right of I and on the other side we know that the right pointer is side we know that the right pointer is pointing to the largest number in the pointing to the largest number in the array so if the total is less than zero array so if the total is less than zero then we need to make the sum larger if then we need to make the sum larger if we move the right pointer down then that we move the right pointer down then that would only make the total smaller again would only make the total smaller again because the array is sorted we're also because the array is sorted we're also keeping I fixed for now so the only keeping I fixed for now so the only thing we can do here is move the left thing we can do here is move the left pointer up to make the total larger so pointer up to make the total larger so let's go ahead and increment l now we let's go ahead and increment l now we loop again and calculate the new Total loop again and calculate the new Total which is negative four plus negative one which is negative four plus negative one plus five which is zero that means that plus five which is zero that means that we found the solution so we'll go into we found the solution so we'll go into this else block and create an array this else block and create an array called triplet that has our solution called triplet that has our solution which is negative four negative one and which is negative four negative one and five we're then going to append that five we're then going to append that triplet to our answer array and we've triplet to our answer array and we've now successfully found our first now successfully found our first solution then we're going to move the solution then we're going to move the left and right pointers inwards but left and right pointers inwards but we're also going to check for a few we're also going to check for a few extra things so first we make sure that extra things so first we make sure that L is still less than R and we also check L is still less than R and we also check if the number at L is equal to the if the number at L is equal to the number at index 1 of the triplet which number at index 1 of the triplet which is the number we just added to the is the number we just added to the answer that was at index l in this case answer that was at index l in this case negative one and so if it is equal to negative one and so if it is equal to that number then we're going to that number then we're going to increment l so in other words we want to increment l so in other words we want to keep incrementing L until it no longer keep incrementing L until it no longer points to negative one and it goes to a points to negative one and it goes to a different number and the reason we do different number and the reason we do this is to avoid adding duplicate this is to avoid adding duplicate Solutions now we check again we can see Solutions now we check again we can see that L still points to negative one so that L still points to negative one so if we just calculated the total again we if we just calculated the total again we would end up appending the same solution would end up appending the same solution So to avoid that we're going to So to avoid that we're going to increment L again now when we check we increment L again now when we check we see that L points to zero so we can see that L points to zero so we can finally move on since we moved L to a finally move on since we moved L to a different number we know that these different number we know that these three numbers are definitely not going three numbers are definitely not going to equal zero so we can also move R and to equal zero so we can also move R and we'll check for the same thing except we'll check for the same thing except we'll look at the number at index 2 of we'll look at the number at index 2 of the triplet which is 5. right now R the triplet which is 5. right now R still points to five so let's decrement still points to five so let's decrement R now we're finally at a different R now we're finally at a different number so we can finally calculate the number so we can finally calculate the new Total negative four plus zero plus new Total negative four plus zero plus three equals negative one which is less three equals negative one which is less than zero so we'll move the left pointer than zero so we'll move the left pointer up but now notice that the two pointers up but now notice that the two pointers have met in the center that means we're have met in the center that means we're done with the inner loop and we've done with the inner loop and we've checked all the numbers so we can now go checked all the numbers so we can now go back up to the outer loop increment I back up to the outer loop increment I and do it all over again and do it all over again here I is greater than zero but the here I is greater than zero but the number at index I negative two is not number at index I negative two is not equal to the number at index I minus 1 equal to the number at index I minus 1 which is negative four so this is still which is negative four so this is still false and we skip it then we'll set up false and we skip it then we'll set up our left and right pointers again and our left and right pointers again and start checking all the numbers the total start checking all the numbers the total is negative two plus negative one plus is negative two plus negative one plus five which is two this time the total is five which is two this time the total is greater than zero so by the same logic greater than zero so by the same logic as last time since we need to make the as last time since we need to make the total smaller the only thing we can do total smaller the only thing we can do is decrement the right pointer next the is decrement the right pointer next the total is negative 2 plus negative one total is negative 2 plus negative one plus three which is zero so we found plus three which is zero so we found another solution let's create the another solution let's create the triplet array again and append it to our triplet array again and append it to our answer then we're going to move the answer then we're going to move the pointers inwards again L gets pointers inwards again L gets incremented and since it's still incremented and since it's still pointing to negative one we increment it pointing to negative one we increment it again again next we'll decrement R but now both next we'll decrement R but now both pointers have met again so we're done pointers have met again so we're done with the inner loop again and we can with the inner loop again and we can increment I increment I this condition is still false because this condition is still false because negative one does not equal negative two negative one does not equal negative two but you'll see this become useful very but you'll see this become useful very soon so again we set up L and R and then soon so again we set up L and R and then calculate the total which is three this calculate the total which is three this is too large so let's decrement r is too large so let's decrement r next the total is one which is still too next the total is one which is still too large so we'll decrement R again now the large so we'll decrement R again now the total is negative two which is now too total is negative two which is now too small so we'll increment L the two small so we'll increment L the two pointers have now met which means that pointers have now met which means that there were no solutions to be found and there were no solutions to be found and we'll move on to the next I however now we'll move on to the next I however now notice that this condition is true the notice that this condition is true the number at index I is negative one and so number at index I is negative one and so is the number at index I minus 1. when is the number at index I minus 1. when this happens we're going to hit this this happens we're going to hit this continue keyword and what continue means continue keyword and what continue means is to skip the rest of this iteration is to skip the rest of this iteration and continue with the next one so we're and continue with the next one so we're going to skip everything below this and going to skip everything below this and just increment I again just increment I again so the reason we do this is because we so the reason we do this is because we don't want duplicate Solutions with don't want duplicate Solutions with index I at the same number it's the same index I at the same number it's the same idea as the left and right pointers we idea as the left and right pointers we keep moving it forward until we hit a keep moving it forward until we hit a different number different number now I points to zero so this is false now I points to zero so this is false and we can proceed let's set up L and R and we can proceed let's set up L and R and total is going to be 8 which is and total is going to be 8 which is clearly too big so R gets decremented clearly too big so R gets decremented they meet in the middle so we're done they meet in the middle so we're done with the inner loop but notice that that with the inner loop but notice that that was also the last iteration for the was also the last iteration for the outer loop as well because remember if outer loop as well because remember if we moved up I to index 5 then we we moved up I to index 5 then we wouldn't have enough numbers to form a wouldn't have enough numbers to form a triplet so now we're also done with the triplet so now we're also done with the outer loop which means the only thing outer loop which means the only thing left to do is to return the answer which left to do is to return the answer which contains our two solutions and we're contains our two solutions and we're done now I'm going to mention this as a done now I'm going to mention this as a bonus but if you really wanted to bonus but if you really wanted to optimize then before starting each Loop optimize then before starting each Loop you could check if the number at index I you could check if the number at index I is greater than zero and if it is then is greater than zero and if it is then just break out of the loop right away just break out of the loop right away and return the answer the reason this and return the answer the reason this works is because since the array is works is because since the array is sorted we know that the number at index sorted we know that the number at index I is going to be the smallest out of the I is going to be the smallest out of the three numbers so if the number at index three numbers so if the number at index I is already greater than zero 0 then I is already greater than zero 0 then there's no way that any of the other there's no way that any of the other numbers which are all larger are going numbers which are all larger are going to sum up to zero so in the case that to sum up to zero so in the case that you were given a very long array with you were given a very long array with lots of positive numbers this piece of lots of positive numbers this piece of code right here would allow you to exit code right here would allow you to exit early and save some time | 2024-03-19 15:31:49 | 15 | LeetCode #15: 3Sum | Coding Interview Question |
|
DBJPWJr5zZ4 | and welcome back to the cracking fang youtube channel today we're going to be youtube channel today we're going to be solving lead code problem 818 race car solving lead code problem 818 race car your car starts at position 0 and speed your car starts at position 0 and speed plus 1 on an infinite number line your plus 1 on an infinite number line your car can go in negative positions your car can go in negative positions your car drives automatically according to a car drives automatically according to a sequence of instructions a for sequence of instructions a for accelerate and r for reverse when you accelerate and r for reverse when you get an instruction a your car does the get an instruction a your car does the following its position is increased by following its position is increased by the speed its current speed and the the speed its current speed and the speed is multiplied by two if you get an speed is multiplied by two if you get an instruction to reverse your car does the instruction to reverse your car does the following if your speed is positive then following if your speed is positive then your speed becomes minus one otherwise your speed becomes minus one otherwise your speed becomes one your speed becomes one and your position will stay the same and your position will stay the same given a target position target return given a target position target return the length of the shortest sequence of the length of the shortest sequence of instructions to get there instructions to get there so let's look at an example and try to so let's look at an example and try to figure out how we might do this we're figure out how we might do this we're given a target 6 which is what we want given a target 6 which is what we want to end up at and we see that our output to end up at and we see that our output should be five but how do we get that should be five but how do we get that well we know that our speed in the well we know that our speed in the beginning beginning is going to be one right because it is going to be one right because it tells us it's positive one and our tells us it's positive one and our position is going to be zero right so position is going to be zero right so let's kind of draw our number line so we let's kind of draw our number line so we are at zero and we want to get to six are at zero and we want to get to six somehow somehow so we know that we're so we know that we're going forward in a positive manner right going forward in a positive manner right so so we are going straight so the first we are going straight so the first instruction for us to do to reach six is instruction for us to do to reach six is obviously we need to go forward so to do obviously we need to go forward so to do that we have to tell ourselves to that we have to tell ourselves to accelerate so that means that we're accelerate so that means that we're gonna go forward so we're gonna issue an gonna go forward so we're gonna issue an accelerate command accelerate command and the accelerate command is going to and the accelerate command is going to basically basically you know our position is going to be you know our position is going to be equal to whatever our previous position equal to whatever our previous position was plus the speed so now we're going to was plus the speed so now we're going to end up at one end up at one and you know and you know so our position now becomes one and so our position now becomes one and speed is doubled so now speed is two speed is doubled so now speed is two so now we're at one well we still want so now we're at one well we still want to get to six so we need to accelerate to get to six so we need to accelerate so we're going to issue another so we're going to issue another accelerate command accelerate command here here and what we're gonna do is we are you and what we're gonna do is we are you know gonna end up where well what know gonna end up where well what happens when you accelerate so the happens when you accelerate so the position is going to be equal to you position is going to be equal to you know plus equals to the speed so we're know plus equals to the speed so we're going to end up at position three now going to end up at position three now because we add our speed which is two because we add our speed which is two and we multiply our speed by two so our and we multiply our speed by two so our speed is four so we end up at three so speed is four so we end up at three so three is still not six so what do we three is still not six so what do we wanna do wanna do well we need to essentially keep well we need to essentially keep accelerating so we're gonna issue accelerating so we're gonna issue another accelerate command and now our another accelerate command and now our position is going to be equal to you position is going to be equal to you know we're going to add our current know we're going to add our current position plus the speed so we end up at position plus the speed so we end up at 7. so we're actually going to end up at 7. so we're actually going to end up at 7 from here 7 from here and our speed is now going to get and our speed is now going to get multiplied so it's 8. so obviously we've multiplied so it's 8. so obviously we've gone too far now because we're at seven gone too far now because we're at seven but we need to be at six so we can't but we need to be at six so we can't keep going forward otherwise we're just keep going forward otherwise we're just gonna get further and further away from gonna get further and further away from six six so from here we need to issue a reverse so from here we need to issue a reverse command command so so we're gonna issue a reverse command and we're gonna issue a reverse command and what happens when we issue a reverse what happens when we issue a reverse command command so our speed is positive so that means so our speed is positive so that means our speed now becomes minus one our speed now becomes minus one and our position stays the same so we're and our position stays the same so we're still at minus seven still at minus seven okay so that means that okay so that means that our speed is minus one so we wanna go to our speed is minus one so we wanna go to the left so what we need to do is we now the left so what we need to do is we now need to need to uh issue an accelerate command because uh issue an accelerate command because now we're reversed right our speed is now we're reversed right our speed is minus -1 so that means that we'll be minus -1 so that means that we'll be traveling backwards so we need to traveling backwards so we need to do that do that so remember that when we issue the so remember that when we issue the acceleration command our speed gets acceleration command our speed gets multiplied by two so it's minus two so multiplied by two so it's minus two so we're going minus two i guess miles or we're going minus two i guess miles or kilometers whatever in the opposite kilometers whatever in the opposite direction direction and our position is gets added to the and our position is gets added to the speed so speed so since it's the previous speed was minus since it's the previous speed was minus one we actually end up at six which is one we actually end up at six which is our final answer so we can see that the our final answer so we can see that the sequence we had to do is a sequence we had to do is a a a a a r a and that's five commands which is r a and that's five commands which is how we got the final answer of five so how we got the final answer of five so looking at it it's pretty intuitive you looking at it it's pretty intuitive you know if you had to work it out you could know if you had to work it out you could probably figure this out drawing it out probably figure this out drawing it out but this is a coding problem we need to but this is a coding problem we need to actually put actually put this into some sort of solution and this into some sort of solution and figure it out so let's think about an figure it out so let's think about an intuitive way that we can solve this intuitive way that we can solve this problem problem okay so we looked at an example but it okay so we looked at an example but it wasn't really clear how we can translate wasn't really clear how we can translate that simple example into actual code that simple example into actual code so this problem is a hard problem and so this problem is a hard problem and it's asked by google so you're probably it's asked by google so you're probably immediately going to jump to we immediately going to jump to we have to use dynamic programming and have to use dynamic programming and we're not going to do that i hate we're not going to do that i hate dynamic programming i don't do dynamic dynamic programming i don't do dynamic programming so we're going to solve it programming so we're going to solve it another way which is actually so much another way which is actually so much simpler and probably results in less simpler and probably results in less lines of code and less you you know lines of code and less you you know wanting to jump off a bridge somewhere wanting to jump off a bridge somewhere because dynamic programming is the worst because dynamic programming is the worst thing on earth thing on earth so let's think about this we have our so let's think about this we have our start position start position let's kind of draw it here and we have let's kind of draw it here and we have some end position right some end position right and we'll say that's another dot and you and we'll say that's another dot and you know there's certain you know places so know there's certain you know places so if this is zero right and this is six if this is zero right and this is six for our kind of target well let's say for our kind of target well let's say this is one this is two this is one this is two and we're kind of just drawing them in and we're kind of just drawing them in arbitrary places it doesn't really arbitrary places it doesn't really matter exactly where they are um you matter exactly where they are um you know these little dots but what you know these little dots but what you begin to realize is that you know begin to realize is that you know getting from zero to one to two to three getting from zero to one to two to three to four to five to six or maybe you go to four to five to six or maybe you go from one to three to five to six or from one to three to five to six or whatever whatever you can actually represent this as a you can actually represent this as a graph right these are really just nodes graph right these are really just nodes that you can traverse between that you can traverse between and what are we asked to find we're and what are we asked to find we're asked to find the shortest sequence asked to find the shortest sequence of instructions from how to get from of instructions from how to get from point a start to point e well point a start to point e well if we can think about traversing from if we can think about traversing from start to end as traversing a graph which start to end as traversing a graph which it really is right because each one of it really is right because each one of the nodes that we can reach i guess from the nodes that we can reach i guess from zero to infinity obviously we probably zero to infinity obviously we probably don't want to go to infinity we want to don't want to go to infinity we want to go to whatever our target is go to whatever our target is those are all nodes in our graph and we those are all nodes in our graph and we can reach them you know from one we can can reach them you know from one we can reverse to go back to zero from one we reverse to go back to zero from one we could somehow end up at three we could could somehow end up at three we could end up at four so really all of these end up at four so really all of these nodes are connected nodes are connected so so and we're asked to find the shortest and we're asked to find the shortest sequence which should immediately scream sequence which should immediately scream to you that we want to use a breath to you that we want to use a breath first search first search so if we can initialize a breadth-first so if we can initialize a breadth-first search and basically maintain our kind search and basically maintain our kind of cue structure of cue structure to get us closer and closer to the end to get us closer and closer to the end every time then we should be able to every time then we should be able to find the shortest path and if we just find the shortest path and if we just count the amount of steps it took to get count the amount of steps it took to get to you know our end from the start we to you know our end from the start we know that breadth first search will know that breadth first search will always give us the shortest path so we always give us the shortest path so we don't have to go down all the possible don't have to go down all the possible routes like we would with the depth routes like we would with the depth first search or you know something with first search or you know something with dynamic programming we can actually just dynamic programming we can actually just do a bfs and we'll get there in the do a bfs and we'll get there in the fastest possible time fastest possible time so obviously this diagram is horribly so obviously this diagram is horribly messy it's like spaghetti right now but messy it's like spaghetti right now but let's go to the code editor and write let's go to the code editor and write this out because it's a whole lot this out because it's a whole lot simpler than you might think and i think simpler than you might think and i think it's only about maybe 12 lines of code it's only about maybe 12 lines of code so so let's do that instead of trying to make let's do that instead of trying to make sense of this jumble diagram which sense of this jumble diagram which admittedly looks terrible so i'll see admittedly looks terrible so i'll see you in the code editor okay we're back you in the code editor okay we're back in the code editor let's write the code in the code editor let's write the code so this is a breadth first search so this is a breadth first search solution which means that we're going to solution which means that we're going to need a queue and we're going to need to need a queue and we're going to need to initialize that queue with our initial initialize that queue with our initial position so we're going to say q position so we're going to say q equals collections.deck equals collections.deck and remember that we need to keep track and remember that we need to keep track of a few things those being our current of a few things those being our current number of moves which obviously we've number of moves which obviously we've made zero moves in the beginning our made zero moves in the beginning our current position which is zero and our current position which is zero and our current speed which is one current speed which is one so so we also want to use a visited set here we also want to use a visited set here to make sure that we don't accidentally to make sure that we don't accidentally visit visit combinations of position and speed that combinations of position and speed that we've already been to because then we'll we've already been to because then we'll just end up recalculating things so just end up recalculating things so let's set up a visited set to make sure let's set up a visited set to make sure that we that we can prune search paths that we've can prune search paths that we've already been down already been down so now we do our breath first search so so now we do our breath first search so we're going to say while q we're going to say while q we're going to say the current moves we're going to say the current moves we've made the position and our current we've made the position and our current speed is going to be q the pop left speed is going to be q the pop left and now let's double check that we are and now let's double check that we are not at our solution so we're going to not at our solution so we're going to say if position say if position equals to our target that means that equals to our target that means that we're done we've reached our target and we're done we've reached our target and since it's a breath first search we know since it's a breath first search we know that we're going to reach it in the that we're going to reach it in the shortest possible sequence so we can shortest possible sequence so we can just return our moves just return our moves otherwise this means that we're not at otherwise this means that we're not at our target and we need to continue going our target and we need to continue going so let's check that we actually haven't so let's check that we actually haven't been here before so we're going to say been here before so we're going to say if position if position and and speed in speed in visited so if we've already been here visited so if we've already been here and the way that we track it is if we've and the way that we track it is if we've been at this position been at this position with the current speed with the current speed uh obviously this combination if it's in uh obviously this combination if it's in visited that means that we've been there visited that means that we've been there before we can just continue to the next before we can just continue to the next iteration of our breadth first search iteration of our breadth first search otherwise this is a new position in otherwise this is a new position in speed combination for us so we need to speed combination for us so we need to explore it so we're going to say explore it so we're going to say visited.add visited.add and we're going to add the position and and we're going to add the position and speed speed cool cool now what we want to do is we need to now what we want to do is we need to decide what to do so decide what to do so we always basically want to try to go we always basically want to try to go forward if we can forward if we can so so let us go forward and the way that we're let us go forward and the way that we're going to do that obviously we're going going to do that obviously we're going to make a move forward so that would to make a move forward so that would increase our moves our position remember increase our moves our position remember when we go forward is position plus when we go forward is position plus equals to speed so we're going to say equals to speed so we're going to say plus plus the speed is our new position and we go the speed is our new position and we go speed times two speed times two right because the speed doubles when we right because the speed doubles when we uh accelerate uh accelerate so so obviously we can't just keep obviously we can't just keep accelerating forever because eventually accelerating forever because eventually we're gonna hit a point where we we're gonna hit a point where we shouldn't have accelerated and we shouldn't have accelerated and we basically need to go back right we can basically need to go back right we can overshoot our target so like in this overshoot our target so like in this example that we looked at earlier we got example that we looked at earlier we got to seven but our target was six so at to seven but our target was six so at this point we need to reverse this point we need to reverse so so what we only want to reverse in a few what we only want to reverse in a few situations the first situation is that situations the first situation is that you know we've overshot our you know we've overshot our current position right since we're current position right since we're moving forward at every iteration of our moving forward at every iteration of our kind of search here kind of search here eventually we will overrun it it's very eventually we will overrun it it's very unlikely that every single time we're unlikely that every single time we're just going to reach the target just going to reach the target you know perfectly most likely we're you know perfectly most likely we're going to overshoot because obviously the going to overshoot because obviously the speed is doubling each time and that speed is doubling each time and that means that the position is increasing um means that the position is increasing um you know exponentially so what we need you know exponentially so what we need to do is check how we overrun our to do is check how we overrun our position in which case we need to position in which case we need to reverse reverse or are we not quite at our position so or are we not quite at our position so for example if the target is 6 and we're for example if the target is 6 and we're at four but we're actually going at four but we're actually going backwards then obviously in that case we backwards then obviously in that case we wanna reverse because we don't wanna wanna reverse because we don't wanna just keep going in the opposite just keep going in the opposite direction so those are our two cases direction so those are our two cases where we actually wanna issue a reverse where we actually wanna issue a reverse command so we're gonna say if the command so we're gonna say if the position position plus the speed plus the speed uh would actually take us over the uh would actually take us over the target target and our speed is positive obviously if and our speed is positive obviously if the speed is negative it's okay that the speed is negative it's okay that we've overshot our target because now we we've overshot our target because now we can just start going in the opposite can just start going in the opposite direction so this is the case where direction so this is the case where we're at seven but we're still we're at seven but we're still continuing forward so we'd end up at continuing forward so we'd end up at like you know eight nine ten eleven we like you know eight nine ten eleven we actually wanna go the opposite direction actually wanna go the opposite direction so this is checking whether or not we so this is checking whether or not we actually overshot our target and that actually overshot our target and that our speed is still positive which means our speed is still positive which means that we'd be going even further away the that we'd be going even further away the second condition is that we're actually second condition is that we're actually below our target so we're going to say below our target so we're going to say position plus speed it's actually less position plus speed it's actually less than the target than the target but the speed is actually negative so but the speed is actually negative so for example like on a number line if we for example like on a number line if we were at four and our target was six but were at four and our target was six but we were actually going you know to the we were actually going you know to the left right left right that would take us further and further that would take us further and further away from six we actually need to away from six we actually need to reverse so we can start going to the reverse so we can start going to the right and getting closer to that six so right and getting closer to that six so in those are the two cases where we in those are the two cases where we actually need to issue that reverse actually need to issue that reverse command command and let's calculate what our new speed and let's calculate what our new speed is right so if the speed when we issue is right so if the speed when we issue the reverse is positive then the speed the reverse is positive then the speed becomes -1 otherwise the speed becomes becomes -1 otherwise the speed becomes one so one so let's say that the new speed is going to let's say that the new speed is going to equal to -1 if the current speed is equal to -1 if the current speed is greater than zero otherwise it becomes greater than zero otherwise it becomes one now we can add to our q one now we can add to our q the new you know direction that we're the new you know direction that we're traveling so we're going to say q the traveling so we're going to say q the append uh moves oops moves plus one append uh moves oops moves plus one uh our position remember the position uh our position remember the position stays the same when you issue a reverse stays the same when you issue a reverse command and our new speed which we just command and our new speed which we just calculated so we'll say speed cool let calculated so we'll say speed cool let me just run this make sure i didn't make me just run this make sure i didn't make any syntax errors cool it looks like it any syntax errors cool it looks like it works so let's submit this and it flies works so let's submit this and it flies cool so cool so what is the time and space complexity what is the time and space complexity for this algorithm for this algorithm this one is quite tricky this one is quite tricky if if our speed was constant so every time we our speed was constant so every time we were just moving by one then it's a were just moving by one then it's a breath first search it would take us breath first search it would take us probably big o of end time in the worst probably big o of end time in the worst case to reach our case to reach our you know target but because every time you know target but because every time we issue an acceleration command and we issue an acceleration command and we're always accelerating basically we're always accelerating basically we always multiply our speed by two we always multiply our speed by two so because the speed is doubling each so because the speed is doubling each time time uh uh our space our time complexity is our space our time complexity is actually going to be log n actually going to be log n or i guess log t uh where t is the or i guess log t uh where t is the target basically target basically so that is the time complexity and the reason for it again it's a little bit confusing but basically because our speed is doubling each time uh that's why it's log two and it's actually log base two of t uh not yeah i guess log whatever you guys it's normally log base two anyway um so it's yeah log base two similar to how you know in binary search our search space halves every time in this problem our speed is doubling each time which is why we're able to reach it in basically you know log uh log t times so space complexity for this one you know again if our speed was one each time then it would be big o of t where i guess t is the target um but because again we double each time we're actually not going to visit every single place so the space complexity is also going to be log base 2 of t so that is how you sell race car this is an interesting one because a lot of the solutions are actually dynamic programming but like i said earlier in the video i absolutely hate dynamic programming i think it's the worst thing on earth i don't think any interviewer should ever ask this garbage way of solving questions i think it's total bs and you know this is a much simpler much more intuitive breadth-first search solution which is really easy to code up easy to understand and if your interviewer doesn't accept this then they're really mean and they should reconsider their life choices because it's a bit of a dick move to only want the dynamic programming solution so that's how you solve race car with a bfs solution if you enjoyed this video please leave a like and a comment it really helps with the youtube algorithm if you want to see more videos like this if you're prepping for your google interview your facebook interview your insert big company here you're going to want to watch my videos subscribe so you don't miss future uploads otherwise thank you so much for watching this video and have a great | 2024-03-22 14:22:58 | 818 | RACE CAR | LEETCODE # 818 | PYTHON BFS SOLUTION |
|
yPdfjEB8TvQ | Hello hello everyone welcome to date 20th family four interpress question research indicates what is family four interpress question research indicates what is a country and in this a country and in this question give a thought if chosen by one of the selected question give a thought if chosen by one of the selected and selected item withdrawal withdrawal in more subscribe and subscribe this Video plz subscribe Channel subscribe our Place to this site is created for Place to this site is created for Place to this site is created for kids in the search for direct oo aleikum kids in the search for direct oo aleikum members join date 20th and spine more the members join date 20th and spine more the country which of this example of short country which of this example of short dresses subscribe this Video plz dresses subscribe this Video plz subscribe Video in case your target subscribe Video in case your target element great Indian middle element middle element great Indian middle element middle element this subscribe element this subscribe element this subscribe Thursday Off Units Development Unit Thursday Off Units Development Unit Certificate Vikram Subscribe Problem Is The Certificate Vikram Subscribe Problem Is The Police Tried To Support There Gold Police Tried To Support There Gold From Now For Life For The Difficult From Now For Life For The Difficult Question To Give Vote The Two Parts Question To Give Vote The Two Parts Identify Weather Your Life In More Vidmate At index mist subscribe At index mist subscribe At index mist subscribe The Channel And subscribe The Amazing The Channel And subscribe The Amazing spider-man 2 that is my target element Life without boundaries this and this I will reduce middle high point - side increase point to make flying dual elements and include the that and in this that and in this that and in this Target Element subscribe The Amazing subscribe Subscribe Loot-Loot Report Subscribe Subscribe Loot-Loot Report Subscribe Now Start - 151 - Subscribe To Now Start - 151 - Subscribe To This Contest This Contest This Contest Sequence To Norms Middle Element Oil Awards Press Returns Through S Hai Na Tu Kab Se Prasad Logic Sirf Mez To Know Mid-1960s Who Is The I Left Time Set Alarm Targets In Index Loop number at nine and half according to a and metal index tight means and detergent live in this they will remove all my online lives on that jis pot dash plunder andal move hide two minus one subscribe subscribe and notifications no Loot Andheria Check Weather Return Gift Is Out Of Bounds Not Target Hotspot Of The Fat Bonding Hai Tiffin Us Of Lo Who Tiffin Us Of Lo Who Is Greater Than Number Format Do It Means Tried It Is Greater Than Number Format Do It Means Tried It Software & Electronics Right Under The Thing Target Subscribe Button Subscribe To Subscribe To Ayyappa No Right To Life It's A Maximum Ayyappa No Right To Life It's A Maximum Video Clip Next Flight Hai And Sunao The Limits That Accepted 16 Images Pocket Two That Accepted 16 Images Pocket Two Algorithms For That Everything Comes Algorithms For That Everything Comes Clear With Specific To Deep Discussed A Clear With Specific To Deep Discussed A Distant View of Declaring and Points Distant View of Declaring and Points Sandwich Subscribe Our Video Friends Video subscribe and subscribe the Channel subscribe and subscribe the Note After Landslide Arvind is Case and Reduce Amazing at How to Do Subscribe My Channel Subscribe My Middle and Lower Middle Class is Finnish Acid Finnish Acid Finnish Acid President President liked The Video President President liked The Video then subscribe to the Page if you liked then subscribe to the Page if you liked The Video then subscribe to subscribe The Video then subscribe to subscribe for Live Video Lutab School Subscribe for Live Video Lutab School Subscribe That Thank You For Watching My Video | 2024-03-21 13:24:03 | 154 | Search in Rotated Sorted Array II | Leetcode Nov 2020 Day 20 | Leetcode 81 |
|
HAuqbJojVPk | hi everyone welcome to my channel let's solve the lit code problem maximum jar solve the lit code problem maximum jar of two numbers of two numbers in an array so given a non empty array in an array so given a non empty array of numbers a 0 of numbers a 0 a 1 a 2 and a n minus 1 where all the a 1 a 2 and a n minus 1 where all the numbers i lie between numbers i lie between 0 to 2 to the power 31 so we have to 0 to 2 to the power 31 so we have to find find the maximum result of ai or aj such that the maximum result of ai or aj such that inj lies between the range 0 to n inj lies between the range 0 to n and we have to come up the solution of o and we have to come up the solution of o and runtime solution and runtime solution so solving this in o of n square so solving this in o of n square solution just nest the two solution just nest the two try to create all the pairs of ai aj try to create all the pairs of ai aj and get the maximum over them of their and get the maximum over them of their jar jar which is very straightforward but this which is very straightforward but this solution is of n solution is of n square and the problem is asking for we square and the problem is asking for we have to come up with the o of and have to come up with the o of and solution so how we will solve this solution so how we will solve this problem in problem in o of n so this is the first example o of n so this is the first example given here given here so let's understand how we will solve so let's understand how we will solve this problem this problem so over here i have write down the so over here i have write down the binary representation binary representation of all the numbers and these number is of all the numbers and these number is the biggest number the biggest number so its binary representation is occupied so its binary representation is occupied 5 digit 5 digit 5 bits so i have extended others numbers 5 bits so i have extended others numbers in the 5 bit representation as well so in the 5 bit representation as well so first of all first of all let's understand what is your so if we let's understand what is your so if we are doing two jar are doing two jar so the truth table of jar if we do zero so the truth table of jar if we do zero g dot zero we will get zero g dot zero we will get zero one jar one is also zero and the one jar one is also zero and the opposite bits like one yard zero and opposite bits like one yard zero and zero zero or one this is the truth table of the or one this is the truth table of the jar operation so we will get the one jar operation so we will get the one so for the maximum jar we will try to so for the maximum jar we will try to achieve achieve as maximum one from starting from the as maximum one from starting from the left side left side of the number so if all the numbers in of the number so if all the numbers in the memory is represented as a 32-bit the memory is represented as a 32-bit binary representation 32 bits binary representation 32 bits so this is just i have for explanation so this is just i have for explanation write it down on in write it down on in all the five bits representation so all the five bits representation so we will look for the two numbers they we will look for the two numbers they have the different have the different bits basically most of the opposite bits bits basically most of the opposite bits so that we will always get this one so that we will always get this one one like this so if we go here in the one like this so if we go here in the first first so we have this number which has the so we have this number which has the first bit first bit is one and other number is can we is one and other number is can we support this number support this number so we can get at least so we can get at least the one and other four let's say 0 so we the one and other four let's say 0 so we can get maximum at least this number can get maximum at least this number which is corresponding decimal of 16. which is corresponding decimal of 16. similarly once we get the first set similarly once we get the first set tweet we will tweet we will also look for if we can get like one also look for if we can get like one one and then other whatever we will look one and then other whatever we will look bit wise bit like first we started from bit wise bit like first we started from this this bit uh like the if in the five fifth bit bit uh like the if in the five fifth bit basically or zeroth bit from the left basically or zeroth bit from the left side side then second weight and so on so if we then second weight and so on so if we try for this try for this so we will check we have uh this so we will check we have uh this is out of picture this number and this is out of picture this number and this number is also out of picture number is also out of picture but if we do jar of 25 with rest of the but if we do jar of 25 with rest of the number 2 5 3 number 2 5 3 we can get this so this will be we can get this so this will be corresponding to the number corresponding to the number is i think 24 yeah 16 plus 8 which is 24 is i think 24 yeah 16 plus 8 which is 24 so we can get so we can get max 24 if we do then we will max 24 if we do then we will go further one more step down which is go further one more step down which is we will look for we will look for is is it possible to get 1 1 0 0 is is it possible to get 1 1 0 0 in our number or not so this is the in our number or not so this is the approach we will try approach we will try now how to solve this as a programically now how to solve this as a programically this is the understanding this is the understanding so for programmabically solving this so for programmabically solving this first of all first of all to finding a particular bit like set to finding a particular bit like set width or the bit number at width or the bit number at a checking bit at particular number we a checking bit at particular number we will will use a mask so we will use a mask which use a mask so we will use a mask which will will we will use mask and we will shift we will use mask and we will shift that many bits time one of left shift so that many bits time one of left shift so left shape is basically if we start left shape is basically if we start with one this will be the like number with one this will be the like number zero zero zero zero and so on zero zero zero zero zero zero and so on zero zero one if i do one if i do let's say three time left shift of this let's say three time left shift of this one then this will give me one then this will give me one zero zero basically we will shift one zero zero basically we will shift three time this left so this is like three time this left so this is like this so 0 0 0 0 so this is how this so 0 0 0 0 so this is how lefsef operative works now lefsef operative works now if we start so let's say right now we if we start so let's say right now we have 5 bit so we will start look for have 5 bit so we will start look for this so we will do the this so we will do the left shift of this basically total n left shift of this basically total n which is 5 minus 1 which is 5 minus 1 so 4 times if we do 4 time we will get a so 4 times if we do 4 time we will get a first mass 1 0 0 first mass 1 0 0 0 0 so this is a mass which is in 0 0 so this is a mass which is in decimal is 16 basically decimal is 16 basically so we will do the j bitwise and with all so we will do the j bitwise and with all of the number of the number so if we do the bitwise and with all of so if we do the bitwise and with all of the number we will get only d the number we will get only d here two things one is zero and here two things one is zero and if with all of the rest of the number if with all of the rest of the number except this except this number because this number 1 1 will number because this number 1 1 will match so we will get 1 0 0 0 match so we will get 1 0 0 0 0 from this so this number will give us 0 from this so this number will give us 16 which is 16 which is corresponding to 1 0 0 0 so corresponding to 1 0 0 0 so first we will create this and store as a first we will create this and store as a prefix in our one of the data prefix in our one of the data structure we are set we will store these structure we are set we will store these both of them both of them first we store now we will look for the first we store now we will look for the fifth bit fifth bit the maximum jar we will generate the the maximum jar we will generate the maximum jar maximum jar so we will initialize maximum jar again so we will initialize maximum jar again from the variable zero and then from the variable zero and then we will check is there we will check is there two numbers in our set which has two numbers in our set which has basically basically prefix like opposite to so starting this prefix like opposite to so starting this we will use a one temp we will use a one temp variable again the same as the we will variable again the same as the we will do the bitwise shift and take do the bitwise shift and take or with the current max so we will do or with the current max so we will do the current max or with the the current max or with the and the number of time we will again and the number of time we will again save to this guy to set that bit save to this guy to set that bit one so ith time so here it is will be one so ith time so here it is will be initially it will become one zero zero initially it will become one zero zero again again now we will use this stamp now we will use this stamp and iterate all the element in our set and iterate all the element in our set so let's say so let's say we will iterate all the element as a we will iterate all the element as a prefix prefix in our set so this is my set which has in our set so this is my set which has in the first like 0 and 16 in the first like 0 and 16 so if i trade so let's say if i got 0 so so if i trade so let's say if i got 0 so 0 means 5 0 0 means 5 0 for 5 bit representation and the temp is for 5 bit representation and the temp is 1 0 0 0 1 0 0 0 0 0 so if we do the bit wise like this 0 0 so if we do the bit wise like this jar of these two jar of these two thing we will get these stills and we thing we will get these stills and we will check if will check if the set contains which means it's the set contains which means it's confirmed that we have two number which confirmed that we have two number which has the opposite bits has the opposite bits at this place the at this place the eighth number like fifth bit like first eighth number like fifth bit like first bit from the left bit from the left so we will set this bit break this and so we will set this bit break this and max chat our maximum at least max chat our maximum at least with this number temp current time and with this number temp current time and then we then we further this is we did for the first bit further this is we did for the first bit here here now we go one more down the line the now we go one more down the line the we update our mask so in the mask we update our mask so in the mask also we will keep the previous width so also we will keep the previous width so we will do bit wise we will do bit wise or with the new mask or with the new mask bitwise or with the current mask and the bitwise or with the current mask and the shift this now three times so the shift this now three times so the current over bit mask is one zero zero current over bit mask is one zero zero zero zero and we will do bitwise mask zero zero and we will do bitwise mask with one zero with one zero zero zero and zero will be here so this zero zero and zero will be here so this will become will become one one zero 0 0 so this is our now one one zero 0 0 so this is our now new mask then we will do the bitwise new mask then we will do the bitwise and with all the number and store in the and with all the number and store in the set now set now in set if we store we will get the 3 in set if we store we will get the 3 number like 0 number like 0 8 and the 16 8 and the 16 this is corresponding to five zeros in this is corresponding to five zeros in bitwise in bit representation this is bitwise in bit representation this is corresponding to 0 1 0 corresponding to 0 1 0 0 how we will get if we do bitwise end 0 how we will get if we do bitwise end of this mask with this of this mask with this two number like eight and ten we will two number like eight and ten we will get this get this eight similarly if we do b25 we will get eight similarly if we do b25 we will get one one zero zero zero so one one zero one one zero zero zero so one one zero zero so this is not sixteen it is twenty zero so this is not sixteen it is twenty four basically this time four basically this time so now so now if same thing we will use it so now we if same thing we will use it so now we have three elements in our set which is have three elements in our set which is like 0 like 0 8 and 24 now we 8 and 24 now we use again our tam which will become use again our tam which will become max or the initially max we have 1 max or the initially max we have 1 0 0 0 and then we will again shift this 0 0 0 and then we will again shift this bit here 1 with bit here 1 with 3 3 time so this will become r with 1 0 3 3 time so this will become r with 1 0 0 0 and 0 is here so this will again 0 0 and 0 is here so this will again become become the temp is same as like mass basically the temp is same as like mass basically so this so this is now we will do the bitwise or of each is now we will do the bitwise or of each of the number of the number and check if this guy is contained if we and check if this guy is contained if we do bitwise do bitwise jar with this so the we will get this jar with this so the we will get this itself which is 24 and this our side is itself which is 24 and this our side is contained contained so we found the prefix that two number so we found the prefix that two number which has the opposite two bits which has the opposite two bits so this will be our next maximum so we so this will be our next maximum so we will update maximum so this will update maximum so this is the basic approach to solve this is the basic approach to solve this problem is problem is uh using the bitwise operator uh using the bitwise operator so let's start the implementation first so let's start the implementation first then i will explain the time complexity then i will explain the time complexity and space complexity for this solution and space complexity for this solution so initially we need a one mass which is so initially we need a one mass which is initialized from zero and also the initialized from zero and also the max variable which is will hold the bits max variable which is will hold the bits of our of our max joint then we will iterate from it i max joint then we will iterate from it i is equal to 31 by 31 because our number is equal to 31 by 31 because our number is represented in the memory integers is is represented in the memory integers is in the 32 bit so we start from the 31 we in the 32 bit so we start from the 31 we will go to till the will go to till the uh 0th bit so this is 0 i minus minus uh 0th bit so this is 0 i minus minus so now first of all we will generate our so now first of all we will generate our mask mask so this mask will be mask so this mask will be mask is equals to mask bitwise or with the is equals to mask bitwise or with the left shift of 1 at how many times left shift of 1 at how many times i times so this is how we i times so this is how we generated the mask first now let's generated the mask first now let's define a define a set which will hold all the prefixes set which will hold all the prefixes which we generate with the bitwise which we generate with the bitwise and with the mask so this will be let it and with the mask so this will be let it call set call set new hashtag now we trade all the nums in num in nums array every time and store that set dot add the mask bitwise end with the num so we will add that in prefixes in now for the eighth bit of our max we will look for so initializer time variable max or again the same as like 1 with max or again the same as like 1 with y shift i time now we y shift i time now we iterate all the prefix which we iterate all the prefix which we generated in our pref generated in our pref chat which is let's say call prefix chat which is let's say call prefix into the set then we will also check if into the set then we will also check if our set contains the prefix contains the prefix from the temp bitwise jar with the uh current prefix number if this is there like two number which is sharing the different bits in that case we will update our max with the current attempt and break here for this bit at least we found the number and we will do for all the 32 bits and in the end we just return whatever bit sets we found in our max which is our maximum job so let's compile this code and see if it is compiling and we are getting correct answer yes we are getting correct and it is accepted so now let's and it is accepted so now let's understand what is the time complexity understand what is the time complexity so if you see over here so if you see over here we are doing this uh array iteration we are doing this uh array iteration every time for every time for all of the 32 bits so this the time all of the 32 bits so this the time complexity of this solution is o complexity of this solution is o of 32 n n is the length of our of 32 n n is the length of our i so this 32 is constant as we can i so this 32 is constant as we can doing big o of so we can also say that doing big o of so we can also say that this time complexity is o of n and the this time complexity is o of n and the space complexity of the solution space complexity of the solution is it's like depend how many is it's like depend how many we are getting like in the first case we we are getting like in the first case we will get the two element only in the set will get the two element only in the set and the second case we can get more 4 and the second case we can get more 4 but in worst case in the end we can get but in worst case in the end we can get an element in our set so that we can say an element in our set so that we can say space complexity is often space complexity is often so this is a solution try it out it is so this is a solution try it out it is not that easy to come up with this kind not that easy to come up with this kind of solution unless you are familiar with of solution unless you are familiar with bitwise problems orbit wise operators so bitwise problems orbit wise operators so try it out give a try there are try it out give a try there are very like other problems try them out very like other problems try them out like one of the like one of the similar kind of problem is hamming similar kind of problem is hamming distance two problem distance two problem which is like solution is which exactly which is like solution is which exactly i can say is kind of i can say is kind of similar to this solution so try that out similar to this solution so try that out as well i as well i will provide the link so if you like my will provide the link so if you like my solution hit the like button solution hit the like button and subscribe to my channel thanks for and subscribe to my channel thanks for watching | 2024-03-22 11:06:15 | 421 | maximum xor of two numbers in an array leetcode | leetcode 421 | bitwise solution |
|
wvpd_FvSNzo | Hello Hi Everyone Welcome To My Channel It's All The Problem Summary Ranges So You Are All The Problem Summary Ranges So You Are Tunic Interior Anthems Returned As Tunic Interior Anthems Returned As Molested List Of Ranges Is That Cover All Molested List Of Ranges Is That Cover All Numbers In The Land Of Blood And Subscribe Numbers In The Land Of Blood And Subscribe One Of The World With Me If This Are Sorted One Of The World With Me If This Are Sorted Unique Unique Unique receive new updates from 400 500 Here's 56001 929 Verizon Adheen dhlo len dr eid to 56001 929 Verizon Adheen dhlo len dr eid to kal morning questions page subscribe kal morning questions page subscribe if you start start number of the end of if you start start number of the end of the subscribe start from the subscribe start from the subscribe start from That Sister What I Will Do Inlaid With Sacrifice next9news Is Anek Number Sunf Min Se I Plus One Who Is Equal To Two Numbers Of I A Plus One Officer Case Will Keep Increasing Genes Power Rangers Which Is Like This Is Limit for doing this will also Limit for doing this will also Limit for doing this will also not the best of the con is on not the best of the con is on start position of power current ranges number start position of power current ranges number 5 ft ki 5 ft ki and e will keep trying to attain it is possible and also will and e will keep trying to attain it is possible and also will support and support and attractive no deposit amount of vs attractive no deposit amount of vs number of elements subscribe now to number of elements subscribe now to number of elements subscribe now to subscribe but more will follow subscribe share and subscribe our subscribe ranges from start that harold gender current and systems for a day to olive enum cleaning notification victory destructive list and will keep continue strongest and show the video and Celebs Kim Pigmentation Mother Celebs Kim Pigmentation Mother Celebs Kim Pigmentation Mother Quotes For The List Of Births Subscribe The Quotes For The List Of Births Subscribe The Amazing Nor Will Run From A Number Of Amazing Nor Will Run From A Number Of Elements Of Elements And A Plus Thursday Ko Hai Elements Of Elements And A Plus Thursday Ko Hai Na Ho First Vinod Sony Staff Power Rangers Witch Will V95 Nobody Will Keep Ninth Ninth Ninth And Have Na Dhoye Is Equal To Numbers Of And Have Na Dhoye Is Equal To Numbers Of Sonam Plus One Five Plus One Medium Subscribe The Amazing List Dhoye Representation Like This And Updated On That Otherwise It Is Not The Case Will Just Add I Secure Pimp Code Implementation And I Secure Pimp Code Implementation And Tried To Compile Wait Tried To Compile Wait Tried To Compile Wait For Different Cases Are With Women Are That No That Is No Difference Navya Confident Enough But That No That Is No Difference Navya Confident Enough But Can Submit D Code Can Submit D Code Yo Yo Honey Tips Accepted S What Is The Yo Yo Honey Tips Accepted S What Is The Time Complexity Of Dissolution Severe Time Complexity Of Dissolution Severe One For One For One For Run From Over Time Complexity of subscribe The Video then subscribe to | 2024-03-22 11:05:26 | 228 | Summary Ranges | summary ranges | summary ranges leetcode | leetcode 228 | linear |
|
IIshwbQtcVY | what is up guys Xavier LAN here I'm prepping for interviews so I'm doing a lot of leak code videos so please subscribe to my channel if you haven't already I'm gonna be posting fairly frequently today I'm going over searching sorted a rotated sorted array so the description reads suppose an array sorted in ascending order is rotated at some pivot point unknown to you beforehand basically they just move like the elements along spaces you are given a target value to search if found in the array return it to index otherwise return negative one you may assume no duplicates exists in the array and your algorithms run time complexity most on the order of o log n so right here when I see o login I immediately think binary search so that should be a huge huge hint so the examples they have here is the target is 0 so they're returning the 4th index and target is 3 there's no 3 in here so they return negative 1 so the way I solve this is basically we want to calculate the mid sorry my dogs going crazy calculate the mid so if the target is target is 3 we're gonna calculate the mid by doing / - so we're gonna get 7 plus 0 divided / - so we're gonna get 7 plus 0 divided by two equals three point five it's a by two equals three point five it's a gonna be an int so it's going to round gonna be an int so it's going to round up to four so that's going to give us up to four so that's going to give us the mid of right here the mid of right here the fourth index that's just how it the fourth index that's just how it works works and then we're going to check to see if and then we're going to check to see if start is less than the mid then we know start is less than the mid then we know that this part of the array is sorted that this part of the array is sorted but that's not the case start is but that's not the case start is actually greater than so it's greater actually greater than so it's greater than so it's not sorted so we're gonna than so it's not sorted so we're gonna not check that one first and we're gonna not check that one first and we're gonna see if mid is less than and which it is see if mid is less than and which it is so we know this is sorted and then we're so we know this is sorted and then we're going to check this to see if the going to check this to see if the targets in there and we're just going to targets in there and we're just going to keep doing that so that's how I solved keep doing that so that's how I solved it it let's code it out hold on so we have start is zero and then int and equals numbs dot length minus one because of 0th index and we're gonna have our mid we're not going to initialize it yet so we're gonna do well start is less than or equal to end so we're going to loop through all the indexes basically and if nums let's start is less than lumps of mid then we know the start to end is sorted so that's what this means and that's where we're going to want to check for the target so then then we're just going to check for the target so if numbers of mid is um oh and I forgot to actually the first thing we want to target equals numbers amid this is what target equals numbers amid this is what we're checking for then we return we're we're checking for then we return we're returning the index you know this over returning the index you know this over here return all right and then back if here return all right and then back if numbers of mid is less than or greater numbers of mid is less than or greater than the target and num start is less than the target and num start is less than two target less than or equal to than two target less than or equal to the target that means the target is in the target that means the target is in that sorted array because it's mid is that sorted array because it's mid is greater than let me show you on my iPad mid is gonna be so it's gonna be let's see if we do this one this is gonna be the mid start so we're gonna be checking this array because it's sorted target is 3 so we have move this over we have tons of mid is greater than the target that's 7 is greater than 3 and then as a start 7 is greater than 3 and then as a start is less than or equal to the target well is less than or equal to the target well yeah it is it's equal to the target so yeah it is it's equal to the target so that still holds true and if that's the that still holds true and if that's the case we're going to adjust the high two case we're going to adjust the high two because we know now we know the target because we know now we know the target is in that array that portion of the is in that array that portion of the array so we're gonna do and equals mid array so we're gonna do and equals mid minus 1 and then else that means the minus 1 and then else that means the time if the other case is the target is time if the other case is the target is in the other side of the array so we're in the other side of the array so we're going to do start equals mid plus 1 and going to do start equals mid plus 1 and then we just have an else so so it's just basically the same thing except flipped so if nums of mid all numbers of ends this time is greater numbers of ends this time is greater than or equal to the target and the than or equal to the target and the reason we use great add the equal sign reason we use great add the equal sign is because it's never going to equal is because it's never going to equal numbers of mid because we already check numbers of mid because we already check it up here so we don't add that but we it up here so we don't add that but we do at it for here because it can equal do at it for here because it can equal it like I showed you in the last sample it like I showed you in the last sample the start did equal the target but we're the start did equal the target but we're returning the mid not we can't return returning the mid not we can't return the start so so in this case we're doing the start so so in this case we're doing we have to adjust the in this case we we have to adjust the in this case we have to adjust the the mid so we're have to adjust the the mid so we're moving them or no the start I'm sorry moving them or no the start I'm sorry we're gonna move the start to mid plus we're gonna move the start to mid plus one so it starts going to go here and one so it starts going to go here and still here and we do for mid is and so still here and we do for mid is and so two or seven plus five divided by two two or seven plus five divided by two gives you a 12 plus or 12 divided by 2 gives you a 12 plus or 12 divided by 2 is 6 so this is the sixth index so this is 6 so this is the sixth index so this is going to be the new mid yeah and is going to be the new mid yeah and that's the case for a different target that's the case for a different target if we had a different target number I if we had a different target number I know I'm a target up here but I was just know I'm a target up here but I was just showing you guys that so hopefully that showing you guys that so hopefully that makes sense and so like I said we need makes sense and so like I said we need to move start in this case so we're to move start in this case so we're gonna use this same statement their gonna use this same statement their statements are just going to be flipped statements are just going to be flipped because the targets in this part of the because the targets in this part of the array instead so and then else and array instead so and then else and equals mid minus one because if the target isn't in that then we need to it's in the other part so we're checking the sorted arrays because that's what we need to check and yeah that's about it and then if we if the start ends surpasses the end we and we kick out of the while loop that means we did not find the number so let's return yeah oh and I did not calculate mid just yeah oh and I did not calculate mid just that's dumb a me and divided by 2 that's dumb a me and divided by 2 all right so yeah this is the correct all right so yeah this is the correct code this is actually gonna work code this is actually gonna work oh sweet all right and then the so the oh sweet all right and then the so the running time is like it it even says in running time is like it it even says in the description Oh login so that's the description Oh login so that's binary search that's why that's that we binary search that's why that's that we didn't have to create any data didn't have to create any data structures so the space come yeah the structures so the space come yeah the space complexity is o of 1 it's constant space complexity is o of 1 it's constant and that's about it please subscribe if and that's about it please subscribe if you guys haven't already and thanks for you guys haven't already and thanks for watching and if you guys have any watching and if you guys have any questions at all please just don't don't questions at all please just don't don't hesitate to contact me I will answer hesitate to contact me I will answer love to answer any questions and if you love to answer any questions and if you guys have any problems you actually want guys have any problems you actually want me to post videos on let me know and I me to post videos on let me know and I will do that as well so thanks for will do that as well so thanks for watching | 2024-03-20 08:43:07 | 33 | LeetCode 33 | Search in Rotated Sorted Array | Algorithm Explained (Java) |
|
eoBo6zuFAjw | that's all from 1935 maximum number of words you can type this lead good words you can type this lead good problem says that you'll be given two problem says that you'll be given two experts one is a experts one is a string uh string which would be a string uh string which would be a sentence okay the second string will be sentence okay the second string will be the list of the list of characters and we need to characters and we need to find how find how many words in the sentence many words in the sentence so if the sentence is called text so how so if the sentence is called text so how many words in the many words in the sentence do not include any of those sentence do not include any of those characters from the second string so characters from the second string so second string in this case would be call second string in this case would be call broken broken letters and broken letters for example letters and broken letters for example is is a a um T right so and this is the first r um T right so and this is the first r in purchase the sentence so we can in purchase the sentence so we can certainly consider hello as one word certainly consider hello as one word which doesn't include any character from which doesn't include any character from broken letters okay second the second broken letters okay second the second word contains D which is there in broken word contains D which is there in broken letter so we cannot consider this so in letter so we cannot consider this so in that case we return one because only one that case we return one because only one can can be uh one word out of the sentence do be uh one word out of the sentence do not include any character this similarly not include any character this similarly in the second in the second example the broken letters are lnt so example the broken letters are lnt so and the sentences lead space and the sentences lead space code so the first word contains lnt so code so the first word contains lnt so we we cannot count that but the second word cannot count that but the second word doesn't contain any character which just doesn't contain any character which just there in broken letters we can count there in broken letters we can count that so we WR one that so we WR one one the third example the broken letters one the third example the broken letters include e and e is there in all the include e and e is there in all the words of the sentence so in that case we words of the sentence so in that case we would return zero so how am I going to would return zero so how am I going to solve this very simple what I can do is solve this very simple what I can do is I I can convert the broken letters into a can convert the broken letters into a set okay set okay so convert broken so convert broken letters in a set called B and then I'll letters in a set called B and then I'll go through each go through each character in character in text and I'll check text and I'll check if C is equal to if C is equal to space then in that case I'll do a couple space then in that case I'll do a couple of things I'll increment count with current so I'll initialize both those variables now let's count I'll initialize with zero and current I'll initialize with one okay and I'll toggle current to 1 if if if if current if current and current is equal to one and CN B then in that Quest I'll set current to zero okay so this I can write it as like this as well so if current and c and b then current is equal to zero okay and then at the end I'll return count plus current what will this program do is every time it encounters the space it will check or it will add whatever the value of current is there and add it into count also we'll have to reset current here to one okay so after every space and at the beginning of the sentence I'll set current to one and anytime I can counter a character which is there in broken letters I will set current to zero so when the next space is found it adds zero to count if that word had any character which is in B else it will the current will remain one and it will add one to count okay I'll reset current one after every word and ends and here at the end I'm adding current to the count because after the last word there is no space so in that case it will not consider it will never go here and consider the last word so that's why I'm add adding it at the end and returning it let's this and see if this works fine and that worked for the three test submitted and that worked for all of submitted and that worked for all of them | 2024-03-25 13:28:56 | 1,935 | Leetcode 1935. Maximum Number of Words You Can Type |
|
_8WLoYLidTE | hello everyone welcome or welcome back to my channel so today we are going to to my channel so today we are going to discuss another problem but before going discuss another problem but before going forward if you have not liked the video forward if you have not liked the video please like it subscribe to my channel please like it subscribe to my channel and hit the bell icon so that you get and hit the bell icon so that you get notified whenever post a new video so notified whenever post a new video so without any further ado let's get without any further ado let's get started started problem is remove duplicate letters problem is remove duplicate letters we are given a string and we need to we are given a string and we need to remove the duplicate letters so that remove the duplicate letters so that every letter appear only once every letter appear only once you make sure you make sure that your result is the smallest in the that your result is the smallest in the lexographical order lexographical order lexographical order lexographical order means when we have ascending order so means when we have ascending order so like this is a string so if there are like this is a string so if there are all permutations of the string and those all permutations of the string and those are arranged in the are arranged in the ascending order so our string whatever ascending order so our string whatever string we will make that should be in string we will make that should be in the the like the smallest in the lexographical like the smallest in the lexographical order meaning it should be the smallest order meaning it should be the smallest among all possible results among all possible results okay okay so so uh let's see how we can approach this uh let's see how we can approach this problem here c this test case problem here c this test case b c a b c b c a b c so here what we are doing is we are so here what we are doing is we are taking a first taking a first then we are taking b then we are taking b and then we are taking c and then we are taking c we are not taking this b why because uh we are not taking this b why because uh here there is a here there is a so so we are taking this a we are taking this a and we are not taking we are a taking and we are not taking we are a taking this a and we are taking this b we are this a and we are taking this b we are not taking this b not taking this b so let's take this test case and just so let's take this test case and just let's let's see how we can approach the let's let's see how we can approach the problem problem so we have b so we have b c c abc abc fine fine now now see over here see over here uh uh we have b here but b also we have here we have b here but b also we have here here we have c but c we have here also here we have c but c we have here also so so either we can take this b either we can take this b when we take this b then we go to the c when we take this b then we go to the c then we go to this a then we go to this a this string we can make this string we can make or what we can do is we do not take this or what we can do is we do not take this b b we take this b we take this b this b this b so uh we can have a so uh we can have a this b this b and then the c and then the c another thing which we can do is we can another thing which we can do is we can take this c take this c this a and this b this a and this b c a b fine abc cab so he from these like lexographical like the smallest one which will come when we do ascending order so this is the lexographical smallest abc the smallest number and then it's increasing this here first letter is c here first letter is b but this is obviously smaller right first letter is so so the thing is that we will prefer c the thing is that we will prefer c the thing is we will be preferring we the thing is we will be preferring we will prefer will prefer taking the smaller letter taking the smaller letter taking the smaller letter smaller letter taking the smaller letter smaller letter when i say meaning when i say meaning a is the small a smaller than b a is the small a smaller than b fine fine prefer taking smaller letter prefer taking smaller letter so see over here we have taken so see over here we have taken a first and then we have taken b a first and then we have taken b let me just change this test case to let me just change this test case to something different something different so let me do one thing let me have so let me do one thing let me have something like this c something like this c uh uh a a b c b c something like this so uh or or let me do it like this b b will be coming here or uh before this so so like this it's c b a c now the thing is guys we have to see c we can take this one also so there is no problem for c but b we have to take this only because there is no b fine in the previous test case the fine in the previous test case the previous test case was bc abc previous test case was bc abc bc abc bc abc in that we we neglected this b this b we in that we we neglected this b this b we did not take y because b was here after did not take y because b was here after a a but here b is only this only there is but here b is only this only there is one occurrence of b one occurrence of b only there is one occurrence of b only there is one occurrence of b so b we will take this one only so b we will take this one only so b so b a a and then c will be the output for this and then c will be the output for this one could be c one could be c we take this c we do not take this c we we take this c we do not take this c we take this c take this c c b a c b a but obviously this one is smaller so but obviously this one is smaller so that's why we are com we are taking this that's why we are com we are taking this so the thing is we will be prefer taking so the thing is we will be prefer taking smaller letter smaller letter but if there is but if there is but if like this b but if like this b this b has only this b has only like there is no other b after this so like there is no other b after this so we'll be taking this b only we'll be taking this b only fine so we need to store fine so we need to store but we have to like we have to but we have to like we have to store the store the see we if we we have to store the last see we if we we have to store the last index index we have to store the last index we have to store the last index of a letter of a letter of a letter because c over here we neglected this b we neglected this b because we knew that b is here so there could be multiple b's right b could be here also so something like this could be there b c b a b c so we will neglect this b we will neglect this b because we know that b could be here also b b's like the maximum index where b is so 0 1 2 3 4 5 so maximum index here is b fine so we have to store the last index of a letter so that we can check can we neglect this b can we neglect this b because we can neglect because there is another b present here so if we are at two index we can neglect this b because this b is also present at 4 index fine so we will get it afterwards also but let's say over here in this case c b a c and let's take b here also something like this we have fine so here we can neglect this b we can neglect this b because we knew we know that b is present here also but when we come here here we cannot neglect this b because this is the last occurrence of b this is the last index where b is present so we cannot take like this b we have to take it anyway even though like a smaller than this b but still this is the last occurrence of b so we have to take it bac fine so i hope you understood this thing let's dry run let's let's see how we can use this thing in our approach so over here this test case let's take so over here this test case let's take the second test case now this one here we have c and this is d fine uh so first of all what i will be doing is i will be i will be taking an array i'll take a character array so when i say character array because these these will have characters only now and that too also the lowercase english letters so there will be 26 lowercase english letters so i'll take an array for storing the last indexes of all characters of all letters so this array will be 26 size 0 okay okay this is a character array which i have this is a character array which i have taken taken that is here zero will be representing a that is here zero will be representing a one index will be representing b one index will be representing b two index will be c and three index will two index will be c and three index will be d and similarly this will be e and so be d and similarly this will be e and so on on okay so this i have taken okay so this i have taken this array i will be storing the last this array i will be storing the last indexes of each letter indexes of each letter because that we need to know because that we need to know so so for a what is the last index let me do for a what is the last index let me do indexing 0 1 2 indexing 0 1 2 3 3 4 5 six seven 4 5 six seven what is the last index here what is the last index here the last index of a one two three so two the last index of a one two three so two is the last index of a is the last index of a then what is the last index of b b's then what is the last index of b b's last index is six last index is six c's last index is seven there are many c's last index is seven there are many c's zero at in at three index and then c's zero at in at three index and then five index and then seven index five index and then seven index and d is at last uh four and d is at last uh four so this is your and rest this will be so this is your and rest this will be zero zeros also zero zeros also like nothing would be there here so this like nothing would be there here so this is your character area right is your character area right now now uh uh what we will be doing is so see what we will be doing is so see we we let's say we have the cb let's say we have the cb uh a something like this we are going we uh a something like this we are going we are traversing on the string c are traversing on the string c b b so see so see here we need to check here we need to check over here c when we are at a over here c when we are at a we need to we need to see that okay this b and c letters are see that okay this b and c letters are bigger than a right they are bigger than bigger than a right they are bigger than a a so so i can avoid taking these i can avoid i can avoid taking these i can avoid taking these if there are taking these if there are afterwards occurrences of these letters afterwards occurrences of these letters so i can avoid this cb so i can avoid this cb because c is present after this a also because c is present after this a also and b is also present after this a and b is also present after this a so i can avoid taking these i can take a so i can avoid taking these i can take a which is the smaller one which is the smaller one so how to store what were the previous so how to store what were the previous characters characters what was the previous characters what was the previous characters how we can store that so we need to have how we can store that so we need to have a data structure for that a data structure for that previous character previous character so for that so for that we can use a stack we can use a stack why stack because stack we can use to why stack because stack we can use to store the previous characters store the previous characters okay okay and that too in the order so this will and that too in the order so this will be first then this will be be first then this will be so that like that so that like that uh let's take a stack uh let's take a stack so i'm taking a stack here so i'm taking a stack here to store the previous characters to store the previous characters i am taking a stack i am taking a stack also i have been taking another also i have been taking another character array character array uh let me remove this uh let me remove this i will be taking another character array i will be taking another character array which will be storing which letter we which will be storing which letter we have taken have taken as of now as of now so which character we have seen so which character we have seen so this so this array name i am writing a scene and this array name i am writing a scene and this is also character array 0 1 2 3 4 is also character array 0 1 2 3 4 here this is a b here this is a b c c and this is d and this is d okay okay seen uh so let's do one thing let's try seen uh so let's do one thing let's try it it step by step so see what we are doing is we will be starting i will start iterating on the string so first of all we'll go to c we will see so there is nothing in the stack as of now so we will just add the c c will be added and in this here this see this area will be pre-filled like we will fill this area before only before iterating on the string this last index array you will understand what is the use of this uh just keep watching so here first of all we added c in the stack and then here uh c since we initially this will be false everything will be false now we have taken the c in the stack meaning we have considered it we have taken we have considered it so we will change it to true so this i will change it to true okay then we will iterate further so now we will go to b now guys see very important point here b is b letter is there now don't you think that rather c being the first letter of the string b should be the first letter because b is less than c and it will be more like so graphical smaller string if it starts from b other rather than starting from c right so if this letter is less than the top of the stack whatever is on the top of the stack c is on the top of the stagna c is on the top of the stack so b is less than c on top of the stack so b should be in the stack c can we can take afterwards only if c now another condition see we can remove only if there is afterwards occurrence of c so this is what this is one index right here c is last uh occurrence where is c lastly present c is present and seven index so this last index is greater than the current index meaning c is also present afterwards so we can remove the c we can safely remove this c and we can add this b and since we have removed the c so it will change from true to false we change from true to false and yeah that that's it so what we have done what step we have done we have checked the top of the stack top of the stack is if the current letter the current c of i of i let's say s of i if current letter is less than the top of the stack here it was b and this was top of the check for c if this is less than and c has other occurrences also so then we can remove the c and we mark in the scene array false okay so this step we have done now let's move forward we go to a now again top of the stack is what b and f is what a a is less than b so obviously what's better a string starting from b or a string starting from a which one is better obviously this is better right we have to have the c we have to have the lexographical smallest here in the problem that they are saying smallest so we will take a so but before removing this b we need to check whether b is present afterwards or not so so that we we have to take v also right we have to have every letter appear once so we cannot neglect b if it's not present afterwards but over here current index is 2 and b's last index is what 6 so b is present so we can remove it safely so from here i will be removing b and i forgot to change it to true firstly so here uh true will be there but now since b is removed so it will change to false okay and a we are adding so a will be changing to true so it will be true here and a we will add in the stack okay now let's move forward so here now we'll go to c so here c is the current s of i and top of the stack is a which is not greater than this c so this is fine we can add now if this is the case so we can safely add this c in the stack so this could be the next letter c c could be the next letter okay now we go to d so here s of i is what d and top of the stack is what c so is c greater than d no fine so this is fine we can have d also here we'll just push so this is if otherwise else we just push in the stack okay now we go here now see now it will be change now it will now here s of i is what now here s of i is what c c and top of the stack is what and top of the stack is what d d so d is greater than c d is greater than so d is greater than c d is greater than c meaning this d should be removed c meaning this d should be removed but do you think this d should remove but do you think this d should remove this condition is satisfying this condition is satisfying but but these last occurrence is what 4 these last occurrence is what 4 and current index is what five and current index is what five these last occurrence was this only d these last occurrence was this only d this one there is no more d afterwards this one there is no more d afterwards so we cannot remove this d we'll have to so we cannot remove this d we'll have to have it have it okay so even though this condition is okay so even though this condition is getting satisfied but the last getting satisfied but the last occurrence of d occurrence of d was was uh less than this is the last occurrence uh less than this is the last occurrence of d of d it was less than the current index this it was less than the current index this is a current index and this is the last is a current index and this is the last occurrence of d occurrence of d so then we cannot remove the d we cannot so then we cannot remove the d we cannot remove d remove d okay okay and and also we have to change this c's because also we have to change this c's because we have added cena and d also so we have we have added cena and d also so we have to change it to true i am forgetting it to change it to true i am forgetting it so we have to change it to true so we have to change it to true then afterwards now let's move forward then afterwards now let's move forward and we will not add this c again see we and we will not add this c again see we will not add again will not push because will not add again will not push because c is already present c is already present uh see uh see uh is already uh is already not here c is already present right not here c is already present right in the stack in the stack so if we will not add c again then we'll so if we will not add c again then we'll go forward go forward we'll go to b we'll go to b so so here here what is the top uh current letter b what is the top uh current letter b and it's less than and it's less than top of the stack which is d top of the stack which is d so we can remove the d but see so we can remove the d but see these last occurrence was this only so these last occurrence was this only so we cannot remove it again so we will we cannot remove it again so we will just simply just simply push b why we will push b now push b why we will push b now because p b is not present it's false so because p b is not present it's false so b we need to push b we need to push we will push b we will push b okay and then c is here so c is already okay and then c is here so c is already present present c is already present here true will be c is already present here true will be there c is already present so we will there c is already present so we will not push it and string we have iterated not push it and string we have iterated c we have completed this traversal and c we have completed this traversal and here the stack is something like this here the stack is something like this so if we push the stack push items from so if we push the stack push items from the stack so b will be first then b will the stack so b will be first then b will be there be there then c will be there and then a will be then c will be there and then a will be there there so now we will reverse it so now we will reverse it a c a c d b and this is the output d b and this is the output a c d a c d b b okay okay i hope you understood this approach i hope you understood this approach let's see how uh let's see the code now let's see how uh let's see the code now so see what we have taken we have taken so see what we have taken we have taken three things one is the stack other one three things one is the stack other one was this last index array and then the was this last index array and then the scene array scene array okay okay so last index area we are storing the so last index area we are storing the last index of all letters last index of all letters then we are taking taken this scene then we are taking taken this scene array array and this stack and this stack okay now okay now what we are doing here over here we are what we are doing here over here we are iterating see this is we are iterating iterating see this is we are iterating this for loop this for loop we are iterating we are iterating um um if if we have if if we have we have seen that character we have seen that character we will just continue so here like for we will just continue so here like for example c here in this c c was already example c here in this c c was already seen so i will just continue we just seen so i will just continue we just move forward otherwise if the top of the stack see if the top of the stack is greater than so5 top of the stack is greater than so5 and i is less than the last index of the top of the stack so like top of the stack was d uh but it's that condition was not satisfying so we need to check if the last index is when the like if there is any other occurrence of that letter or afterwards so if there is then we can remove that letter and we can change to false and we can push the character and we can mark seen as true so after this for loop we will have a stack something like this like this then we can just simply pop from the stack but we popped from the stack it was in rever it was in the reverse order so we will reverse it and we will get the output so we will reverse it and we get the output and we'll return it i hope you understood the problem uh time complexity see we are doing single traversal time complexity is of n and space is of n also because we are taking this extra data structures i hope you understood the problem and the approach let me know in the comments of any doubt if you found the video helpful please like it subscribe to my | 2024-03-24 10:21:26 | 316 | Remove Duplicate Letters | Leetcode 316 | Stack | Day-18 |
|
8ql7cLPa1Ik | um hello so today we are going to do this problem which is part of lead code this problem which is part of lead code daily challenge so what we are asking to daily challenge so what we are asking to do is basically do is basically um just to design a hash set without um just to design a hash set without using any built-in hash tables so we using any built-in hash tables so we can't use um a python dictionary can't use um a python dictionary um and then here um and then here um we have multiple we have the of um we have multiple we have the of course the add function to add a key to course the add function to add a key to the our hash set we have contains to the our hash set we have contains to check if the key is in the hash set and check if the key is in the hash set and then we have removed to remove a key then we have removed to remove a key um from our hash set right so pretty um from our hash set right so pretty straightforward now the the problem says straightforward now the the problem says that the key is between 0 to 10 to the that the key is between 0 to 10 to the power of 6. okay and we'll have at most power of 6. okay and we'll have at most 10 to the power of 4 cores so how do we 10 to the power of 4 cores so how do we do this well the simplest solution do this well the simplest solution because we know the keys are integers because we know the keys are integers and they are between 0 and 10 to the and they are between 0 and 10 to the power of six this is not efficient and power of six this is not efficient and not the actual y hash set isn't not the actual y hash set isn't implemented it's not implemented this implemented it's not implemented this way but as a start for solving this is a way but as a start for solving this is a problem problem it's definitely valid since we only need it's definitely valid since we only need the keys 10 to the 0 to 10 to the power the keys 10 to the 0 to 10 to the power of 6 right what we can do is just create of 6 right what we can do is just create a Boolean array right that a Boolean array right that um will mark an a position as false or um will mark an a position as false or true depending on whether the value is true depending on whether the value is in the hash set or not okay that way if in the hash set or not okay that way if we want to add a key we can just mark it we want to add a key we can just mark it as true if when we remove it we Mark the as true if when we remove it we Mark the position as false and we want to check position as false and we want to check contain we check if the position is true contain we check if the position is true right right um so that would be something like um so that would be something like um let's just do it like this so it um let's just do it like this so it would be something like would be something like this here we want to initialize it to this here we want to initialize it to false first for all of them so this is false first for all of them so this is going to be for all going to be for all um the values in the range of um the values in the range of um 10 to the power of 6. okay and then um 10 to the power of 6. okay and then here we want to do self dot values of here we want to do self dot values of key key um and we want to assign say true um and we want to assign say true because we just added it and here we because we just added it and here we want to say false because we are want to say false because we are removing it okay and if we want to check removing it okay and if we want to check if it's present we can just return if it's present we can just return whether it's present or not okay now whether it's present or not okay now this is this is has a lot of space overhead but it has a lot of space overhead but it should pass except here the index is out should pass except here the index is out of range yep because we need 10 to the of range yep because we need 10 to the power of 6 plus 1 to reach if we get a power of 6 plus 1 to reach if we get a value of 10 to the power of 6 value of 10 to the power of 6 to have it um in index then we need to to have it um in index then we need to add plus one here in Python so let's run add plus one here in Python so let's run it again to submit it again to submit and this passes okay and this passes okay um okay so now let's see how we can um okay so now let's see how we can reduce this space reduce this space um so the key idea here is to use um so the key idea here is to use buckets right so basically before we buckets right so basically before we were using 10 to the power of 6 right were using 10 to the power of 6 right and so to reduce that space let's just and so to reduce that space let's just use maybe 10 000 right you could also do use maybe 10 000 right you could also do thousand but whenever we get a key right thousand but whenever we get a key right to be able to fit it in one of the to be able to fit it in one of the buckets here so let's have 10 000 buckets here so let's have 10 000 buckets buy buckets I mean just lists buckets buy buckets I mean just lists right and whenever we have a key we will right and whenever we have a key we will just do modulo just do modulo ten thousand and that will give us the ten thousand and that will give us the bucket index that we want to put it in bucket index that we want to put it in and then we'll just add it to that and then we'll just add it to that bucket so what does this mean let's take bucket so what does this mean let's take a smaller number just to understand here a smaller number just to understand here so let's say we have only 10 buckets so let's say we have only 10 buckets um and this maps to to a bigger number um and this maps to to a bigger number uh but 10 10 buckets we just so that uh but 10 10 buckets we just so that it's easier for us so if we have the key it's easier for us so if we have the key is equal to nine then we'll put it in is equal to nine then we'll put it in bucket nine so we'd have like ten bucket nine so we'd have like ten buckets so we'd have one buckets so we'd have one two three four five six seven eight nine two three four five six seven eight nine ten okay so this should be three five ten okay so this should be three five and then three five okay and so when we and then three five okay and so when we get nine let's just go to the ninth get nine let's just go to the ninth bucket here index nine bucket here index nine um um so our indexes would be one two three so our indexes would be one two three four five six okay so four four five six okay so four six six and then sorry about this and then sorry about this and then we'd have seven eight nine okay and then we'd have seven eight nine okay so something like this okay so something like this okay um so when we get the nine key Nine um so when we get the nine key Nine right right um here just to um here just to to make the buckets work a little bit to make the buckets work a little bit nicer right we can have nicer right we can have number from number from um um yeah we can number 10 like this okay yeah we can number 10 like this okay it's fine it's fine um so we can put it here um so we can put it here um okay so we'll put our value here so um okay so we'll put our value here so that would be just nine that would be just nine now what if we get let's say 11. now what if we get let's say 11. okay so we'll do 11 module 10 that will okay so we'll do 11 module 10 that will give us one so we'll put 11 here give us one so we'll put 11 here okay so that's sort of the idea okay so that's sort of the idea um if we get to key equal to maybe 19 um if we get to key equal to maybe 19 then if we do modulo 10 we'll get nine then if we do modulo 10 we'll get nine so I'll put 19 here so I'll put 19 here and then if we get so you can see when and then if we get so you can see when there is there is um when the value is in a key that has um when the value is in a key that has already another value we'll put it in already another value we'll put it in the list right and this is what sort of the list right and this is what sort of the main the main issue with hash set the main the main issue with hash set and hashmap is to handle collisions and and hashmap is to handle collisions and the fact that 9 and 19 here are both in the fact that 9 and 19 here are both in the same position this is what the the same position this is what the Collision was but how we handle it can Collision was but how we handle it can be done differently in different be done differently in different implementation in our implementation implementation in our implementation here we are just closing using a list here we are just closing using a list but in some other implementation you but in some other implementation you could use a linked list because could use a linked list because insertion because removal in linked list insertion because removal in linked list is a lot faster is a lot faster um so you could you so that's sort of um so you could you so that's sort of the the main idea here the the main idea here um and then now if we get let's say key um and then now if we get let's say key is equal to 13 then maybe 23 even we do is equal to 13 then maybe 23 even we do my 0 to 10 right we'll get three my 0 to 10 right we'll get three and so we'll put it in position and so we'll put it in position uh I think three here okay so I'll put it here 23 are and now so you can see the the insertion should should work fine now but what about the removal well same thing we go backwards so if we want to remove key equal to 11 again we do modulo 10 we find the bucket index so the buckets index would be one so we found it here and then we'll look for it in the list and remove it before I check if it's there similarly let's say for 11 we do modulo 10 we find the bucket index and then we search in the bucket right so here maybe there were multiple values like uh 14 uh maybe there was here like one sorry this is 21. 31 right then to search for this 11 we just search if it's in the list okay so that's the the main idea behind the solution now let's cut it up so we need buckets so let's first say the the size of our buckets is going to be um 10 000 in in this case here and so let's just ten thousand we'll do plus one to fit the the last one and this is now false we want a list for each bucket and then what we want to do next is basically just um here we want to get the bucket index to to know where to add this right and so to do that well we'll just need the bucket um and let's call it let's create a function to give us the index okay so let's create a function and so for that function what do we need and so for that function what do we need um to get the index well um to get the index well um we just need to get the key modulo um we just need to get the key modulo the number of buckets first okay so that the number of buckets first okay so that gives us the bucket index okay and then in the bucket once we get the bucket so it's going to be just like let's call these buckets actually so we are going to take and we get the bucket itself and now to and we get the bucket itself and now to search for the element search for the element key we just go through the list in that key we just go through the list in that bucket so let's just say I can now if now if the element is equal to the key we found the element is equal to the key we found it then we're going to return the index it then we're going to return the index I I but we also want to get the bucket index but we also want to get the bucket index so let's have this written both the so let's have this written both the bucket index and then the the index of bucket index and then the the index of the element itself now if we are not the element itself now if we are not able to find it in the bucket then it's able to find it in the bucket then it's not there so let's just return something not there so let's just return something that says that the element is not there that says that the element is not there so maybe you can just return minus one so maybe you can just return minus one so now with this index function so now with this index function um it's easy to change this here so what um it's easy to change this here so what do we need to add an element do we need to add an element so we'll get for to add an element since so we'll get for to add an element since it's not there we'll get a minus one but it's not there we'll get a minus one but let's we can still call index to get the let's we can still call index to get the bucket index so let's call index bucket index so let's call index to get the bucket index so here to get the bucket index so here we'll get the bucket index and then we'll get the bucket index and then Let's ignore the other value because we Let's ignore the other value because we don't need it and so we can just append to this bucket and so we can just append to this bucket right we can just append the key so this would be solve that buckets okay but I think here the problem says see the problem says for add to insert the value but this is a hash set so if the value is there maybe we want to just not add it right so to do that we can just check if the value is there so Q is okay okay okay so this is how we handle the ad now okay so this is how we handle the ad now how do we handle the remove how do we handle the remove we can do the similar thing here so we can do the similar thing here so we want to go we want to go and remove position at position I or remove the key so in in a list you can just remove the key itself like this the value itself okay so how do we Implement um checking if the value exists well again we need to check the index right so and then we just check remember if it's not there we'll return minus one so if it's not there so just if it's there then the index would be positive big or equal to zero if it's if it's there the index would be big or equal to zero if it's not there it would be minus one we could also just do different the minus one here okay okay so now let's run this and see if it okay so now let's run this and see if it works looks good so basically the main works looks good so basically the main idea here is using the modulo to get a idea here is using the modulo to get a bucket then the bucket we add the bucket then the bucket we add the elements in a list and so to search for elements in a list and so to search for them we just we do it this way by just them we just we do it this way by just going through the list going through the list um um if we wanted to we could use a sorted if we wanted to we could use a sorted list as well that's another option to list as well that's another option to keep the list sorted and to um sort of keep the list sorted and to um sort of binary search to search for the element binary search to search for the element that's also another option so let's that's also another option so let's submit this submit this um looks like there's a problem here um looks like there's a problem here let's see okay so in remove here we want to check if the element is there before removing it right because it's not there we don't want to remove it so how do we know if it's not there we can just check if the index is equal to -1 then we don't want to remove anything that's right there so let's just fix that submit and this passes okay yeah so that's sort of a better implementation as an exercise you could also try to solve it with a linked list yeah that's pretty much it thanks for watching and | 2024-03-21 10:23:04 | 705 | Design HashSet - Leetcode 705 - Python |
|
JnxAWShm4PU | and have given the number of days, okay what do you have to do, row on zigzag pattern, we have to arrange 22, we have to arrange as many days as we have given, we have to arrange it and the string. What we have to do is to read line by line and the sting that will be ours has to be given to us line by line. Okay, so what we do is let us understand through the example what is the problem, then we will So So So look here, what we have given you is a look here, what we have given you is a string S and a number of roses string S and a number of roses three, so what we have to do is to three, so what we have to do is to make a zigzag pattern like this make a zigzag pattern like this and in this the number of roses You have to take four, there is a You have to take four, there is a You have to take four, there is a van here, okay, so here van here, okay, so here we will arrange it first on the zigzag we will arrange it first on the zigzag pattern, so look what is here, then pattern, so look what is here, then we will drink first, after that, what will we will drink first, after that, what will happen to us, what will happen to us, what will happen to us after A? happen to us, what will happen to us, what will happen to us after A? happen to us, what will happen to us, what will happen to us after A? ok after that P then P what will we do after that we will put it here then where we will put it here we will what is after L what is I what is after i van After three lines, we have to After three lines, we have to After three lines, we have to return the sting, it will be like this, then look at the HP of these two cards, so what we have to do is to read it line wise and return the sting. How will we solve this problem, how can we do it on the pattern, so look let us see, if we store this pattern somewhere, what will we do after fixing it, we will read it line by line and How will How will How will we do this? What will we do? We will take a vector. We will take a we do this? What will we do? We will take a vector. We will take a vector of string. Okay, so the number of rolls in the vector of strings will be the same, number of rolls in the vector of strings will be the same, what will be our elements? We will have lines. what will be our elements? We will have lines. Three numbers of rules have been given, so there are Three numbers of rules have been given, so there are three lines here. three lines here. three lines here. then this is your one element, take one, what will you then this is your one element, take one, what will you do, do, then you will store this testing app, it then you will store this testing app, it is ok at zero index, you are at index, that is, the size will be three, your number of roses will be equal to your vector. OK, now your challenge is that the string you will create at the zero index should be P A H N, the string you will store at the Van index should be A P L S I G and the string you will create at the V index should be A I It should happen, now you will do this, how will you do this, this is It should happen, now you will do this, how will you do this, this is It should happen, now you will do this, how will you do this, this is your challenge, so look for it, we your challenge, so look for it, we will do, let me show you, will do, let me show you, what will we do, we will start from here, okay, we will what will we do, we will start from here, okay, we will start from here, okay, so what will we do, we will take a flag, When it goes down, it will go till the bottom. When it goes down, it will go till the bottom. When it goes down, it will go till the bottom. When it goes up, it means what we have to do is to keep When it goes up, it means what we have to do is to keep interchanging. Okay, so we will interchanging. Okay, so we will know that we are going up. If we are know that we are going up. If we are going down, then going down, then what will we do accordingly, we will increase our index. what will we do accordingly, we will increase our index. In this condition, we have to In this condition, we have to In this condition, we have to from here you will have to come from zero to the van, from the van you will have to go to you, from you then you will have to come to the van, then you will have to go to zero, then from zero you will have to come to the van, from the van then you will have to It It It means that you will do this in the van, this means that you will do this in the van, this you will do this at zero, you will shoot 1, you will you will do this at zero, you will shoot 1, you will do this and what will you do with this, will you store it on the van, if you do it like this, then what will you do, If you have If you have If you have stored P, then whenever your zero will be stored P, then whenever your zero will be zero and number of rolls, number of roses, zero and number of rolls, number of roses, how much is here, if there is three, then 3 - 1 i.e. 2, how much is here, if there is three, then 3 - 1 i.e. 2, when you reach the last index of the first index, when you reach the last index of the first index, then then what will you do with this flag? what will you do with this flag? what will you do with this flag? flip it, you can say flip, now this is our false, so what can we say, it is at zero now, so we make it true and as soon as we feel that this is our true, We will do plus van, We will do plus van, We will do plus van, okay so that means i is your i is your van. van. van. when the flip will happen. When your number is zero and your number of roses is minus one, then we will flip. If this is still true, then we will do I + 1. Whenever this is true, we will do plus one. Till here we have gone to A. True, ours is to tu pe, what will we True, ours is to tu pe, what will we True, ours is to tu pe, what will we do? We will store A and we come to know do? We will store A and we come to know that we are on tu, that is, where we are, if we are on the that we are on tu, that is, where we are, if we are on the last row, then what will we do, we will last row, then what will we do, we will flip it again, that is, what will we flip it again, that is, what will we do by making it false? do by making it false? do by making it false? will come to know that the fall has happened, then what you have made of yours, you mine it again, make it a van, then if you go to the van, then where will you store this p, here people will pay according to the ai. What is still yours, this is your falls, so whenever the falls is there, you will do mines, what will happen with the van, it will become zero because this is your falls, okay, flag is your falls, then what will we do, we will do this, we will do this here. where has A gone to A, A has gone to zero, then where has A gone to A, A has gone to zero, then flip it again, that is, if you want to make it true, then you have to make it true, flip it again, that is, if you want to make it true, then you have to make it true, then when it becomes true, then I will be your then when it becomes true, then I will be your I plus van, then it will be I plus van, then it will be van, so van pe we. van, so van pe we. van, so van pe we. then what is the next element is our L so we will store L here okay then this cat of yours is true so I is yours again you will become you now what will you do now you will put I here because the The element is yours, ok, it has been stored, The element is yours, ok, it has been stored, The element is yours, ok, it has been stored, now you know that it has now you know that it has reached the last row, reached the last row, so flip the flag of what it is, so flip the flag of what it is, what we will do here is to flip it what we will do here is to flip it i.e. false. i.e. false. i.e. false. mine I to Van, that is, it will go to Van, so I started here last, after I, there is S, so what will we do on Van, we will store S, If If If it is false, then what will happen to our i will become zero it is false, then what will happen to our i will become zero i.e. -1, this will make minus i.e. -1, this will make minus van from van zero, then at zero what will we do, again we will van from van zero, then at zero what will we do, again we will store h because after s store h because after s you have h, okay now you know. you have h, okay now you know. you have h, okay now you know. you have gone to zero, then you have to click again, then you will make it true, you have not done it, OK, what will happen after doing true, it will go from zero to van, now what is after this, if it has come, then it has Pay will be sold Pay will be sold Pay will be sold because according to WAN, you have got because according to WAN, you have got WAN index, so here you people, WAN index, so here you people, then you know that this is true for you, so then you know that this is true for you, so what will happen to you, what will happen to you, what will we what will happen to you, what will happen to you, what will we do, we have started income from I. do, we have started income from I. do, we have started income from I. is R then we will store R. Okay, now you know that now you are on the last row, what do you do, flip it, whenever you fall, what we have to do is to 1 will become 2 to 1. 1 will become 2 to 1. 1 will become 2 to 1. What do we have to do on this van? We have to What do we have to do on this van? We have to store the element after R i.e. if we want to store the element after R i.e. if we want to make income then this will become I. Now make income then this will become I. Now what is yours if it is false then I will have to be mined what is yours if it is false then I will have to be mined i.e. you will have to make zero on 0. i.e. you will have to make zero on 0. What will you do by going and storing N? What will you do by going and storing N? Then you come to know that you Then you come to know that you are at zero i.e. first row. Okay, then you have to are at zero i.e. first row. Okay, then you have to flip it to true and whenever it is true, flip it to true and whenever it is true, we increment it we increment it by van. by van. by van. do IBPS and do the last element. Yes, you got this, make this string on zero, make this on van, make this on you, now what will we do, we will take another flu, take a sting answer with zero, in which what you do is Index Burnai Zero B One Plus B Index Burnai Zero B One Plus B Index Burnai Zero B One Plus B Tu i.e. add all and return this final, so Tu i.e. add all and return this final, so this is how we will do, if we will this is how we will do, if we will solve this problem, then solve this problem, then what do I do, I will also show you the code, so see here what we did. We have taken a vector of string with the name answer A, whose size will be equal to your number of roses. Okay, so whenever our number of roses becomes one, what will you do? If it is one, then we cannot increase it. Right here, If you have to show then If you have to show then If you have to show then whatever string will be yours will be your answer whatever string will be yours will be your answer then retain the string S adrevise what to do then retain the string S adrevise what to do now in blue flag falls slowination now in blue flag falls slowination i zero no and one by one character we will i zero no and one by one character we will see what will we do ok first we will see what will we do ok first we will add i to it. add i to it. add i to it. then look at the vector. Is this eye our zero? Is this eye our last or first row? If it is any of the two then what will we do by flipping the If it is If it is If it is i + 1 then we will adervise i - 1, i + 1 then we will adervise i - 1, what will happen in this way, one character will be stored on all the indexes, what will happen in this way, one character will be stored on all the indexes, 22, now 22, now what we have to do is to take the string, okay now we will get what we have to do is to take the string, okay now we will get each string, whatever we get, each string, whatever we get, what we have to do. what we have to do. what we have to do. and we will turn it here so I hope you have understood. If you liked the video then please like, | 2024-03-18 11:36:39 | 6 | 6. Zigzag Conversion |
|
Ftey8arnbdo | this is binary tree in order traversal its lead code question 94 and is one of its lead code question 94 and is one of the Google interview questions so we the Google interview questions so we have the roots of e3 we are dealing with have the roots of e3 we are dealing with the binary tree here and we need to the binary tree here and we need to return the in order traversal of each return the in order traversal of each nodes values this looks very simple we nodes values this looks very simple we already know the formula to do this we already know the formula to do this we can use a depth first search algorithm can use a depth first search algorithm and we can use a recursive function to and we can use a recursive function to achieve that but there is one small achieve that but there is one small trick here we have to return the in trick here we have to return the in order traversal of the nodes values order traversal of the nodes values through a vector so the vector has to be through a vector so the vector has to be a vector of integers and we need to a vector of integers and we need to return the values for example one two return the values for example one two three in a vector of size 3 where the three in a vector of size 3 where the contents of the vector would be the contents of the vector would be the values of these nodes in order in the values of these nodes in order in the solution at first when you begin you solution at first when you begin you only have this line as part of your only have this line as part of your solution it's a public function and this solution it's a public function and this is the vector of integers that you have is the vector of integers that you have to return the name of the function to return the name of the function action and the parameter which is eight action and the parameter which is eight nodes so it's a node pointer and to nodes so it's a node pointer and to solve this challenge I'm creating a solve this challenge I'm creating a vector called values a vector of vector called values a vector of integers and I'm setting it as privates integers and I'm setting it as privates because I only need it in my solution because I only need it in my solution class class now I need to reserve some space for my now I need to reserve some space for my Vector here and to reserve space I need Vector here and to reserve space I need to specify the capacity that I need for to specify the capacity that I need for my Vector so if you scroll down to the my Vector so if you scroll down to the constraints here they say that the constraints here they say that the number of nodes in the tree ranges from number of nodes in the tree ranges from 0 to 100 so we need 100 slots inside of 0 to 100 so we need 100 slots inside of the vector to be able to store the the vector to be able to store the values for a maximum of 100 nodes so values for a maximum of 100 nodes so here once I reserve some space in memory here once I reserve some space in memory it means that I don't need to reallocate it means that I don't need to reallocate spaces anytime I'm pushing a new value spaces anytime I'm pushing a new value this helps a little bit with performance this helps a little bit with performance then what I check here is if I have a then what I check here is if I have a valid nodes if you look again at the valid nodes if you look again at the examples here sometimes they have null examples here sometimes they have null as the node meaning that there is no as the node meaning that there is no nodes there example one has a right nodes there example one has a right child but it doesn't have any left child but it doesn't have any left channels just keep in mind that some of channels just keep in mind that some of the values in the inputs are going to be the values in the inputs are going to be null so I need to check here if it's not null so I need to check here if it's not null then I'm going to follow the in null then I'm going to follow the in order traversal algorithm and this uses order traversal algorithm and this uses recursion so if there is a left child we recursion so if there is a left child we need to visit the left trials we then need to visit the left trials we then need to visit the current nodes in this need to visit the current nodes in this context when I say visits we need to context when I say visits we need to push the value of the current nodes push the value of the current nodes inside of the vector and then if there inside of the vector and then if there is a right chance then we need to visit is a right chance then we need to visit the right child and because this is the right child and because this is recursive this logic is going to repeat recursive this logic is going to repeat for all the notes and when we are done for all the notes and when we are done we can return the values so these values we can return the values so these values Vector will keep getting updated at Vector will keep getting updated at every function call and the last return every function call and the last return that we'll get is the vector fully that we'll get is the vector fully populated with the values from the populated with the values from the binary tree that's pretty much all the binary tree that's pretty much all the logic that you need remember that in logic that you need remember that in order goes left Roots right so this is order goes left Roots right so this is the order that we have here let me run the order that we have here let me run this code this code and we pass all the test cases but these and we pass all the test cases but these are just the sample ones so let me are just the sample ones so let me submit it submit it and we've passed everything with zero and we've passed everything with zero milliseconds so that's pretty good milliseconds so that's pretty good um I'll keep solving the other ones um I'll keep solving the other ones especially for Google interview especially for Google interview questions so if you like my Solutions in questions so if you like my Solutions in C plus plus and you want more C plus plus and you want more programming tutorials and coding videos programming tutorials and coding videos please subscribe to my channel and I'll please subscribe to my channel and I'll catch you next time | 2024-03-20 13:29:16 | 94 | Binary Tree Inorder Traversal - Google Interview Questions - LeetCode 94 Solution - C++ |
|
VcrGPbcjfag | what is up YouTube today I'm going to be going over move zeroes it's a easy going over move zeroes it's a easy problem on the code I know I said I problem on the code I know I said I wasn't gonna do easy anymore but I wasn't gonna do easy anymore but I really like this one I thought it was a really like this one I thought it was a little bit harder than most of the little bit harder than most of the easies so it's a good one to know easies so it's a good one to know check out my slack channel subscribe if check out my slack channel subscribe if you haven't already now see you guys you haven't already now see you guys soon alright so today we have move soon alright so today we have move zeroes giving it ready numbs write a zeroes giving it ready numbs write a function to move all zeroes to the end function to move all zeroes to the end of it while maintaining the relative of it while maintaining the relative order of the dawn zero elements so order of the dawn zero elements so basically we just want to move all the basically we just want to move all the non zeros to the front and do it in non zeros to the front and do it in place so we're gonna have oh one space place so we're gonna have oh one space complexity and minimize the total number complexity and minimize the total number of operations so that just means we're of operations so that just means we're going to loop through it have my going to loop through it have my whiteboard somewhere oops okay so how would you solve this there's actually like a few ways the way I like to solve it is you check to see so we're gonna have I which is our loop counter and then we're gonna have I called it last zero so it's basically saying where the last possible zero was so we're gonna have if nums of I does not equal zero then we're going to swap the if it's not zero we're gonna swap it to the front where the last zero was and we're going to increment zero last zero plus bus at the end it keeps track of the last zero so we know where to so we're only going to be swapping it at the last zero so let me give you a demonstration so I'm gonna do this one right here okay so if num shevai does not equal zero it does not equal zero but we can't obviously swap anything so we need to have because it's the front so we need to add if if I does not equal last zero because if they equal each other that means we're at the front basically the where the last zero is so we can't swap them you know and then numbers of I so we're gonna want to swap well actually we're gonna just move along because we're gonna hit this it's it's not gonna equal true for this one and it's not gonna equal true for this one because of this statement because I does equal last zero we only increment last zero if we execute this statement right here so let me just code it so it makes this one's a little bit harder to explain for me so int length equals Nome last zero so let's set up last zero last zero so let's set up last zero equal to zero by less than rings so if numbs the first statement I had does not equal zero we're gonna want to swap it because we want the zeros at the the back so if it doesn't equal zero let's move it to the last zero and if I is not equal last zero like I said they can't equal each other because that means we're at the front so we're gonna want to swap if we go back to the whiteboard the first case we were gonna want to swap is um so we're actually going to let me show you we're gonna increment last zero out of here because if we execute this basically singing I just exited it's basically saying that the last first zero I guess is right here so that's where we want to keep that pointer and we're gonna want to swap this with this so we just need to do numbers of I numbers of I equals nums or no numbers basically doing this as I go equals basically doing this as I go equals names of I and then numbers of I equals names of I and then numbers of I equals 0 because we just know we need to we 0 because we just know we need to we didn't have to use the temp variable didn't have to use the temp variable because we're just setting it equal to 0 because we're just setting it equal to 0 so that's why we could do that so that's why we could do that so let's code that out numbs of last 0 it numbs of I equals 0 and I think that's it because we don't have to return anything it's void yeah I hope that explanation made sense I'm gonna go through the debugger because I know it was like it takes it takes a little bit to pick up on so the bugger should make it a little bit more clear because I actually showed so we have last zero we're going to so we have last zero we're going to increment I let me give it a different increment I let me give it a different test case I wanted to swap these two test case I wanted to swap these two whatever we're gonna increment my last whatever we're gonna increment my last zero it's gonna stay the same because zero it's gonna stay the same because thumbs of I does equal 0 and okay so now thumbs of I does equal 0 and okay so now we're at a equals 1 last 0 is going to we're at a equals 1 last 0 is going to they're not equal so we're gonna swap they're not equal so we're gonna swap them and then we're gonna increment last them and then we're gonna increment last 0 and it just does that so now it's 0 0 and it just does that so now it's 0 and it's just gonna loop through the and it's just gonna loop through the entire thing until they're all swapped entire thing until they're all swapped and all the zeros are at the back so and all the zeros are at the back so that's all you have the hardest part is that's all you have the hardest part is just coming up with the logic on your just coming up with the logic on your own I think you just need to really like own I think you just need to really like analyze it analyze it whiteboard really helps interesting whiteboard really helps interesting continuing to see problems just like continuing to see problems just like this not just like it but just this not just like it but just continuing to practice and you can continuing to practice and you can develop an algorithm to actually come up develop an algorithm to actually come up with this reading other people's with this reading other people's discussion posts and creative solutions discussion posts and creative solutions also helps me so if you guys like this also helps me so if you guys like this video like it I'll see you guys in the video like it I'll see you guys in the next video | 2024-03-22 14:07:31 | 283 | LeetCode 283 | Move Zeroes | Solution Explained (Java + Whiteboard) |
|
bnfvUU3pEvo | um hello so today we are going to do this problem which is part of leod daily this problem which is part of leod daily challenge night dialer so basically we challenge night dialer so basically we have sort of a chess Knight so just have sort of a chess Knight so just similar to chess where basically Knight similar to chess where basically Knight can move in L shape it can be either can move in L shape it can be either first two step horizontally and then one first two step horizontally and then one step uh sorry two steps vertically One step uh sorry two steps vertically One Step horizontally or the other way Step horizontally or the other way around two step horizontally and then around two step horizontally and then one step vertically right but the start one step vertically right but the start is two steps and then one steps and sort is two steps and then one steps and sort of gives you an L of gives you an L shape um now the variations they add on shape um now the variations they add on here is that you have um um sort of a here is that you have um um sort of a phone pad um where you can stand on phone pad um where you can stand on numeric cells right and so with this numeric cells right and so with this phone pad you need to apply these L phone pad you need to apply these L shapes movements so that's the key idea shapes movements so that's the key idea here and you get n and basically what we here and you get n and basically what we are trying to get is how many distinct are trying to get is how many distinct phone numbers of length n we can dial so phone numbers of length n we can dial so if n is equal to one how many distinct if n is equal to one how many distinct numbers of length one we can dial if n numbers of length one we can dial if n equal to two how many distincts of equal to two how many distincts of length two we can dial so basically it's length two we can dial so basically it's n is the number of n is the number of digits and initially you can start in digits and initially you can start in any uh numeric cell okay um and you you any uh numeric cell okay um and you you so you start from a numeric cell and so you start from a numeric cell and then you can do n minus one jumps makes then you can do n minus one jumps makes sense because you need n digits when you sense because you need n digits when you start in a numeric cell you have the start in a numeric cell you have the first digit and so the remaining ones first digit and so the remaining ones are n minus one okay and the jumps you are n minus one okay and the jumps you you are allowed to do are only valid you are allowed to do are only valid night jumps so only something like night jumps so only something like this or something like let's say if you this or something like let's say if you are at four like this okay um and we are at four like this okay um and we need to give the answer modul 10 the^ of need to give the answer modul 10 the^ of 9 so let's take a look at the first 9 so let's take a look at the first example here n equal to 1 what are the example here n equal to 1 what are the possibilities now the key thing here to possibilities now the key thing here to remember is that you need all the remember is that you need all the variant so what does that mean that variant so what does that mean that means you can you need to one means you can you need to one possibility is to start at cell one the possibility is to start at cell one the other possibility is start at cell two other possibility is start at cell two start at cell three so each digit you start at cell three so each digit you can start at it and then calculate the can start at it and then calculate the number the the number of distinct phone number the the number of distinct phone numbers you can get from that cell so numbers you can get from that cell so with n equal to one which means with n equal to one which means basically just one numeric value well basically just one numeric value well the distinct one you can get are all the the distinct one you can get are all the numbers here so can start at zero at one numbers here so can start at zero at one all the way to nine so overall that's 10 all the way to nine so overall that's 10 numbers or 10 phone numbers so 10 okay numbers or 10 phone numbers so 10 okay um for n equal to 2 it's a little bit um for n equal to 2 it's a little bit different well for n equal to 2 you can different well for n equal to 2 you can first start from zero and then figure first start from zero and then figure out all the variations so that means you out all the variations so that means you start from zero let's say um and then start from zero let's say um and then you go two to you go two to six or you can six or you can um or you can start from zero go to four um or you can start from zero go to four okay so two V two possibilities with okay so two V two possibilities with zero that's the only possibilities zero that's the only possibilities because you can't go left or right um because you can't go left or right um for one you can go from you can go for for one you can go from you can go for example like this to get to eight example like this to get to eight or it could go like this to get to six or it could go like this to get to six those are the only two possibilities and those are the only two possibilities and if you do all of those you get 20 at the if you do all of those you get 20 at the end okay so that's sort of the idea and end okay so that's sort of the idea and the bounds are 5,000 so not too big so the bounds are 5,000 so not too big so should be should be doable now how do we should be should be doable now how do we how do we tackle this well the main how do we tackle this well the main thing to think about here is that this is actually sort of can be done recursively because let's say say um when you when you are at for example if n equal to 3 and you start here you get to six you get to four now you use two out of that three so you have one more jump so now you do six which you can only do like this okay or maybe you could do like this okay six you could go to one you could go to seven or you could go to to zero like this back to zero okay okay and so for six so basically that means when you get to six now you are at six with the jumps one so you can see there are sub problems basically that's what I'm trying to say now what is the state of a sub problems of a sub problem here well first the current Square you are at but also how many jumps you have so the remaining jumps okay and for let's say n equal to 3 um let's say we start first at zero we have two remaining jumps okay and so we go to six so when we go to Six now we have we are at cell six we have one remaining jump we go to from six we can go to one and we have zero remaining jumps and so what's the overall number here for this 0 61 okay and you do the same thing for other for other numbers so you then you start from one and you try all the possibilities of course zero zero um starting from zero you have another possibility which is to go to four right so you can go to four and then you have one remaining jump okay so this is clearly is a dynamic programming recursive solution um basically we just our state here is going to be this okay and for each um we know for each number we know the the valid numbers it can go to that's the key inside here is for each number you can only go to specific places so for example for zero you can only go to six and four for one you can only go to six or eight sorry to six like this or to eight and so let's just have a map with this so let's have a map uh let me just copy it over that says for each number what are the valids places you can go to and now when we are let's say let's call this DP then for each number we just need to get the next n squares we can go to B basically let's call this jumps jumps okay then we can just check the jumps okay then we can just check the valid jumps for that current square and valid jumps for that current square and go to go to those and of course from that next one those and of course from that next one we need to decrement the remaining jumps we need to decrement the remaining jumps by one right because we just utilize by one right because we just utilize one and that's pretty much it we can of one and that's pretty much it we can of course cash because there will be course cash because there will be repetitive States because for example repetitive States because for example six you can get to it from zero you can six you can get to it from zero you can also get to it from one so we don't need also get to it from one so we don't need to calculate it multiple times so we can to calculate it multiple times so we can just cach um our DP here okay um the just cach um our DP here okay um the other thing um is what is our base case other thing um is what is our base case well base case should be if there are no well base case should be if there are no more remaining jumps right we are done more remaining jumps right we are done and when we don't have any remaining and when we don't have any remaining jumps that's one way we found a way to a jumps that's one way we found a way to a valid way to get to valid way to get to uh to get to um a number of length n so uh to get to um a number of length n so we can just return one and the result we can just return one and the result here needs to add up all the different here needs to add up all the different ways right and that's what we return at ways right and that's what we return at the end of course we will need to do the end of course we will need to do modulo but um that's that's the idea modulo but um that's that's the idea here now the next thing to think about here now the next thing to think about is we we can start on any numeric cells is we we can start on any numeric cells so this one needs to be called the start so this one needs to be called the start Point need to be zero with two remaining Point need to be zero with two remaining jumps one with two remaining jumps two jumps one with two remaining jumps two with two remaining jumps three with two with two remaining jumps three with two so basically from 0 to 9 we need to try so basically from 0 to 9 we need to try all of them as a starting all of them as a starting point so that's something we need to point so that's something we need to take care of in the code but that's the take care of in the code but that's the core idea so let's just implement it core idea so let's just implement it here here um so what do we need to do we need to um so what do we need to do we need to Define our function so we need current Define our function so we need current square and then remaining jumps let's just copy over what we just did um like this and we need to Cache so this needs to be a cache here and we need to Define our valid Chumps map so this is going to be like this you could also use an array because the index is um because the values here are consecutive you could use um um an array if you want to um so we have our valid jumps array and then here we said we need to try every number as a starting point so start let's call it in the range of we need 0 to 9 so we can just do range of 10 so that's going to be DP of that start Point remaining jumps are just n minus one because we already utilized one by placing the number in the start position now what do we need to get we need to get all the different ways so we need to add up each one of these and then we need to return that okay let's call this ways just so that it's clear same thing here and then we need to Define our mod so our mod that we need to do we need to mod by on for each addition so it's going to be 10 the^ of 9 plus 7even um and then we can just here this is going to be WS plus and we need to apply modulo same thing here we need to modulo like this modulo like this okay um and that pretty much is it um so okay um and that pretty much is it um so let's run it passes um looks good let's passes um looks good let's submit and that gets accepted okay um submit and that gets accepted okay um yeah so that's pretty much it um the key yeah so that's pretty much it um the key idea is to figure out that you can idea is to figure out that you can actually just hard code the this actually just hard code the this possible state for each number and then possible state for each number and then from there you could do a recursive from there you could do a recursive dynamic programming dynamic programming solution um yeah so that's pretty much solution um yeah so that's pretty much it if you uh need one-onone coaching it if you uh need one-onone coaching feel free to reach sh out uh to me on um feel free to reach sh out uh to me on um super Pier super Pier um yeah feel free to reach out to me on um yeah feel free to reach out to me on super Pier if you need any help thanks super Pier if you need any help thanks for watching and see you on the next one for watching and see you on the next one bye | 2024-03-25 11:43:11 | 935 | Leetcode 935: Knight Dialer |
|
sHgCwS0N3AI | so this problem is leak code id 1512 number of good pairs 1512 number of good pairs so given an array of integers nums so given an array of integers nums a pair i and j is called good if nums at a pair i and j is called good if nums at i i is equal to nums at j and i is less than is equal to nums at j and i is less than j j return the number of good pairs so this return the number of good pairs so this problem problem is one of the best problems to explain is one of the best problems to explain time complexity because intuitively a time complexity because intuitively a new programmer might think okay i'm just new programmer might think okay i'm just going to get going to get all the pairs check if the numbers are all the pairs check if the numbers are equal equal and check if i is less than j and if so and check if i is less than j and if so i'm just going to increment i'm just going to increment you know some count and that's you know some count and that's fine it works but it's not good because fine it works but it's not good because it's it's n squared it's for every i we have to go n squared it's for every i we have to go through every other number through every other number so that would be n squared and there is so that would be n squared and there is a a linear solution for this and we're going linear solution for this and we're going to go over that linear solution instead to go over that linear solution instead the the best interview solution that i the the best interview solution that i can think of basically can think of basically so what we first want to do is we want so what we first want to do is we want to create a hash map to create a hash map and this is going to be of type integer and this is going to be of type integer so it's going to map an so it's going to map an integer to an integer we're going to integer to an integer we're going to call this map and we're going to say call this map and we're going to say new hash map and then we also want to new hash map and then we also want to have a count have a count which is going to be and then i'll which is going to be and then i'll actually call this res to make it more actually call this res to make it more clear clear that's going to be the number of good that's going to be the number of good pairs the result basically pairs the result basically so i'll explain why we need a map but it so i'll explain why we need a map but it just just works for this um it's like it's like works for this um it's like it's like twosome twosome which is another problem i'll go over which is another problem i'll go over where you can optimize it with a map where you can optimize it with a map it's very similar so basically the idea it's very similar so basically the idea here here is we want to go through each numb is we want to go through each numb because we're going to have to do that because we're going to have to do that regardless so if we regardless so if we go through each num so what are we go through each num so what are we looking for here looking for here so we're looking for pairs that have the so we're looking for pairs that have the same number same number and we're looking for the i less than j and we're looking for the i less than j so basically the number so basically the number must come after its pair so because must come after its pair so because we're looping through nums in this way we're looping through nums in this way every number we access is every number we access is greater than the index is greater than greater than the index is greater than the last number we've seen the last number we've seen so this condition is taken care of by so this condition is taken care of by default just the way that we are doing default just the way that we are doing this this and basically we want to see and basically we want to see um how many numbers do we have um how many numbers do we have that equal this num so this is taking that equal this num so this is taking care of this nums i care of this nums i equals nums j case so we're going to equals nums j case so we're going to search our map search our map and how many numbers do we have of this and how many numbers do we have of this num num and basically how we do that is we're and basically how we do that is we're just going to check just going to check um if map dot contains key um if map dot contains key num so have we seen this number before num so have we seen this number before good how many times have we seen it so good how many times have we seen it so we're going to do map we're going to do map dot get knob and this probably makes no dot get knob and this probably makes no sense because it's just like an empty sense because it's just like an empty hash map hash map so at the end here we're going to so at the end here we're going to actually go um actually go um put num map dot get put num map dot get or default or default um num zero plus one um num zero plus one so basically what's going on here um so basically what's going on here um we're incrementing the count of this num we're incrementing the count of this num and and why we do it this way is this getter why we do it this way is this getter default is because this num might not default is because this num might not exist exist yet so if it doesn't uh we're going to yet so if it doesn't uh we're going to do 0. if it does exist we're going to do 0. if it does exist we're going to get get the current count and then whatever the current count and then whatever whatever goes on here we're just gonna whatever goes on here we're just gonna add another one to it add another one to it so basically we're going through the so basically we're going through the nums nums we're checking if this number already we're checking if this number already exists have we seen it can this make exists have we seen it can this make pairs pairs is what we're asking and if so how many is what we're asking and if so how many pairs can it make pairs can it make and then we just increment this we we do and then we just increment this we we do this after this after we increment it because we don't want to we increment it because we don't want to count the current number as a pair count the current number as a pair because um because um moving on to this test case to explain moving on to this test case to explain this further this further so if we have this so if we have this and we have one and we put it in the map and we have one and we put it in the map to put two in the map put through the to put two in the map put through the map then we hit this one map then we hit this one um there'll be one one in the map um there'll be one one in the map so that makes one pair so this one and so that makes one pair so this one and one is a pair one is a pair it wouldn't be two pairs it's just one it wouldn't be two pairs it's just one pair so that that's kind of why we do pair so that that's kind of why we do all that all that and let's go ahead and run this and and let's go ahead and run this and we'll see that we get we'll see that we get accepted and let's go ahead and submit accepted and let's go ahead and submit it we'll see we get 100 run time so it we'll see we get 100 run time so pretty straightforward uh this is an o n pretty straightforward uh this is an o n solution it uses o n space solution it uses o n space o n time uh because we have to go o n time uh because we have to go through every num and we have to keep a through every num and we have to keep a map that stores the num so map that stores the num so yeah i hope this helped tried to make it yeah i hope this helped tried to make it as clear as possible as clear as possible pretty straightforward thank you for pretty straightforward thank you for watching i appreciate it as always | 2024-03-21 11:21:18 | 1,512 | Leetcode Solution - 1512 Number of Good Pairs |
|
j31ZOupyrAs | in this problem we have to reconstruct itinerary from from a given list of itinerary from from a given list of flights between different cities so you flights between different cities so you will be given a list will be given a list [Music] [Music] so let's say this city is a this city is so let's say this city is a this city is b b and this city is c so you may be given a and this city is c so you may be given a list like list like uh ba then you will be given a list of all the edges so ba means flying from b to a and these all are the flights taken by a common person single person but you don't know which order so you have to construct a valid itinerary that means it's not possible that person first flew to c because there is no outgoing edge from c c is just the end point or destination you cannot go anywhere from c so this cannot be the first flight so first maybe either b to a or a to b but if the first flight is b to a then it comes to a then either it takes c or b in both cases or one of the other flights will be missing you have to cover all the edges all are valid flights taken by a person so the valid path would be here go from a to b so the person was initially at a then went to b then came back to a using this line so this is the one two and three then back to a a to b b to a and then finally c so this would be the valid for this one in this case we had just one valid path but in some problems there can be multiple valid paths in that case we will return that value which is lexicographically occurring earlier and you are also given that the source is always a city called jfk so these are the airport codes in three digits so you have to start from jfk only this is the starting point so let's see how we will solve it clearly it's a graph problem and we are given a list of edges so this is just one example so these are the different flights taken by a person and this is a valid output so first step is to build the graph so we will represent it in adjacency list form so there is a flight from jfk to sfo so jfk to sfo there is one flight taken by this person this we have done then sfo to atl so this we have done then sfo to atl so there is another flight like this there is another flight like this then atl to jfk so there is another then atl to jfk so there is another flight like this flight like this and then atl to sfo and then atl to sfo so we have constructed all the edges so we have constructed all the edges now let's see the adjacency list of each now let's see the adjacency list of each node so these are the nodes in jfk sfo node so these are the nodes in jfk sfo and atl then we have atl and then we have then we have atl and then we have sfo so from jfk there are two outgoing sfo so from jfk there are two outgoing edges edges sfo and atl but we have to first try to sfo and atl but we have to first try to traverse lexicographically earlier traverse lexicographically earlier so we will keep them sorted so we will keep them sorted atl first and sfo next atl first and sfo next in atl there is two outgoing edges in atl there is two outgoing edges jfk and sfo so jfk jfk and sfo so jfk and sfo and in sfo there is just one and sfo and in sfo there is just one outgoing edge which is outgoing edge which is atl and we we have to always atl and we we have to always start from jfk in all the problems start from jfk in all the problems so this will always be one of the so this will always be one of the airports in the input airports in the input so we are starting dfs from here only so we are starting dfs from here only thing is that thing is that instead of normal dfs in normal dfs instead of normal dfs in normal dfs we if we we if we reach a vertex we consider it wasted and reach a vertex we consider it wasted and we don't visit it twice we don't visit it twice so if we came from some vertex to some so if we came from some vertex to some other vertex other vertex then some other vertex and there is an then some other vertex and there is an edge like this edge like this so once we reach here we don't take this so once we reach here we don't take this edge since edge since this is going to a vertex which is this is going to a vertex which is already wasted but in this case the only already wasted but in this case the only difference is that we will not mark it difference is that we will not mark it as visited as visited instead we will come back here since instead we will come back here since there may be more outgoing flights there may be more outgoing flights so here the notion of wasted has changed so here the notion of wasted has changed we will not mark it as wasted we will not mark it as wasted but instead to ensure that so if we but instead to ensure that so if we don't don't mark it as wasted what's the guarantee mark it as wasted what's the guarantee that we will not come back again that we will not come back again since we take this edge again and reach since we take this edge again and reach here here and now we will look at its neighbors so and now we will look at its neighbors so this will also be a neighbor so we may this will also be a neighbor so we may again come here again come here so in order to get rid of that once we so in order to get rid of that once we move from this to this we remove this move from this to this we remove this edge edge so person has taken the flight so there so person has taken the flight so there is no point in is no point in taking it again although the person may taking it again although the person may have taken have taken this flight from a to b multiple times this flight from a to b multiple times then we will have multiple edges like then we will have multiple edges like this so first so this b will be this so first so this b will be occurring multiple times in the occurring multiple times in the adjacency list of a adjacency list of a so every time we reach b we delete one so every time we reach b we delete one edge edge so that we don't repeat it like in this so that we don't repeat it like in this case case so this way we are keeping track of uh so this way we are keeping track of uh avoiding avoiding taking one edge multiple times so we taking one edge multiple times so we will will trav take each edge once trav take each edge once so here the notion of which state is not so here the notion of which state is not there we have to take each edge once there we have to take each edge once and once we take an edge traversion is and once we take an edge traversion is that is we come from this to this that is we come from this to this there is no need for this we have listed there is no need for this we have listed this edge this edge so here the notion of which state is not so here the notion of which state is not for nodes but for nodes but for edges so we can mark that wasted by for edges so we can mark that wasted by just just deleting it so you come here delete it deleting it so you come here delete it so let's begin how we will do that so we so let's begin how we will do that so we will modify our dfs will modify our dfs approach here so let's start from jfk so we will start from here and then we go to atl since it's first in the adjacency list since these are sorted and here instead of labels from 0 to n we have string values so we cannot use some fixed size vector which we know beforehand but instead we will use a map where the key will be this airport code so a map of a string and the second is a list or a set and we will keep this sorted so we can use set in c plus set uses red black trees internally so these will be sorted we are not using unordered set and in java we can use a priority queue or we can use a tree set or tree map where we keep track of this string and also the count how many times it has occurred or we can use simply priority q that will sort it based on uh alphabetical order of strings so uh we come to jfk we are here then so we called then we look at its neighbors so first then we look at its neighbors so first it will be atl it will be atl so we will come to atl so we will come to atl or we will call dfs atl or we will call dfs atl and then this edge we have taken so let and then this edge we have taken so let us delete this us delete this or mark this in blue or mark this in blue so assume that this edge does not exist so assume that this edge does not exist now we have come now we have come through this edge so in actual code we through this edge so in actual code we will also remove this will also remove this so this atl will go away from this so this atl will go away from this adjacency list adjacency list so we pick the first neighbor and so we pick the first neighbor and they'll also delete it from the they'll also delete it from the list so now this jfk will have just one list so now this jfk will have just one value value and here again we will call dfs and at and here again we will call dfs and at atl we have atl we have jfk and sfo so which one we will take jfk and sfo so which one we will take alphabetic order so it will call alphabetic order so it will call dfs of jfk dfs of jfk and get rid of this and we come here and get rid of this and we come here and jfk again look at its other and jfk again look at its other neighbors neighbors that is it will pick the first one in that is it will pick the first one in the list and now there is only one the list and now there is only one so it will call dfs on so it will call dfs on sfo sfo and it takes this edge and we remove it now we are at sfo so we go to sfo and see what is the first neighbor which is atl so it will come it will call dfs on it will call dfs on atl and we get rid of this then we come to atl we see what is the neighbor so only sfo is remaining so we will take this edge go to sfo and delete it so you can see dfs getting called for same node multiple times and here we are considering edges as vested now we come back to sfo and we look at neighbors there are no neighbors so that neighbors there are no neighbors so that means we are done with this so when we means we are done with this so when we are done with this are done with this we insert it into a stack so let's write the code first then we will run through complete that example itinerary and we are given as list here so first [Music] adjacency list this will be a map where key will be the airport code or a string and this will be a set or rather multi-set since there can be multiple edges like this in the same direction as well so build in the same direction as well so build the adjacency list based on the the adjacency list based on the edge list that is given to us just like edge list that is given to us just like we built it here manually we built it here manually so jfk sfo means in jfk so jfk sfo means in jfk insert sfo in jfk insert insert sfo in jfk insert atl in sfo insert atl atl in sfo insert atl and so on this way we will build this and so on this way we will build this adjacency list adjacency list this is the first step and once we have this is the first step and once we have built this built this we will start doing dfs and we have to we will start doing dfs and we have to do dfs from do dfs from a particular airport which is jfk a particular airport which is jfk this is always the starting node and in this is always the starting node and in dfs function dfs function if ah if ah so till we have some node so till we have some node in this adjacency list of s in this adjacency list of s a d j of s is not empty adjs dot front that is the first neighbor and finally this when this becomes empty and finally this when this becomes empty that means there is no way to go from that means there is no way to go from this node this node and when this will become empty so and when this will become empty so whenever we take an edge we delete it whenever we take an edge we delete it and we delete this once from this its and we delete this once from this its neighbors list neighbors list so finally it will become empty when we so finally it will become empty when we have taken all the outgoing edges have taken all the outgoing edges so when this becomes empty we will so when this becomes empty we will insert this s to the stack and finally we will take one element at and finally we will take one element at a time from the top a time from the top and print it or return in the result and print it or return in the result so let's complete this example so we had so let's complete this example so we had completed at completed at sfo so we had inserted sfo there sfo so we had inserted sfo there then this call of atl load terminate so this call terminates here so atl is printed inserted into the stack then this terminates back to sfo and this call terminates here so jfk and this call again terminates here so and this call again terminates here so atl will be inserted atl will be inserted and this call terminates here so jfk and this call terminates here so jfk will be inserted will be inserted so from where we have started that will so from where we have started that will be the be the final node in the stack that is at the final node in the stack that is at the top of the stack top of the stack so let's write the path it simply so let's write the path it simply keep popping one element at a time so keep popping one element at a time so jfk is popped jfk is popped then we go to a till then we go to jfk then we go to a till then we go to jfk then we go to sfo then atl and finally sfo and let's match if it matches our answer so jfk atl jfk atl jfk sfo then atl sfo so this is the this is a valid path there can be other solution as well from jfk we can go to sfo and from sfo to atl and then again jfk and then atl and then sfo that will also work but we will take this which ever is lexico graphically first so this one will be the correct answer here let us take one more example let us say we have j f k and then we and back here and then y x z and back here and then y x z like this so again we will start from like this so again we will start from jfk so dfs of jfk it calls it will take this path since this is so it takes this path so it takes this path so it calls dfs x yg so it calls dfs x yg and then this takes this path and calls and then this takes this path and calls dfs of jfk dfs of jfk and this calls yxe and now this one has no other neighbor so this vertex is done so this dfs call terminates and we put it into the stack that is y x y x z then this terminates here jfk then xyg and jfk so what is the order jfk xyz so jfk we are first here then we go to then again jfk so this is the second then again jfk so this is the second flight and then finally y flight and then finally y x g or third flight x g or third flight so this way we have to uh so this way we have to uh code this thing so let's code it in c code this thing so let's code it in c plus java and python plus java and python so this is the same example i had taken so this is the same example i had taken this second example this second example since this was slightly generic so this is our adjacency list here it's and we will take multi-set instead of and we will take multi-set instead of set set because we can have edges from a to b because we can have edges from a to b multiple times so we have to build this so simply adj uh so in t0 insert so in t0 insert t1 and that's it this will build the adjacency list and then we will call dfs on jfk and it needs this adjacency list we can and it needs this adjacency list we can also make it also make it member of this class or we can pass it member of this class or we can pass it by reference and it also needs this result where it so while this is not empty then so while this is not empty then we will pick the front and once we have our traverse or outgoing edges we will insert it into the result so instead of a stack we are we will directly push it into our result [Music] but we will be we can push in the beginning or end if we push in the beginning we don't need to do anything we can simply return that result but pushing in the beginning is very costly in this vector everything needs to be shifted so overall if we insert n items it will take n square times first time no shift second time one shift third time two sips so one plus two plus three all the way up to n n square so it's better to append in the end and finally we will reverse that or you can push into a temporary stack or you can push into a temporary stack and then finally pop one by one and keep and then finally pop one by one and keep inserting into the result inserting into the result both are same things so let's submit so let's submit [Music] and the solution is accepted and it's right here around 78 percent of the submissions so in java uh you can use there is no so in java uh you can use there is no multiset so either we can have a multiset so either we can have a tree set and also tree map and where we tree set and also tree map and where we will have will have string and also a count so if we have string and also a count so if we have multiple times we will increment the multiple times we will increment the count count and while we want to remove we will and while we want to remove we will decrement the count and when count decrement the count and when count becomes zero becomes zero uh either we remove it or we devise our uh either we remove it or we devise our code code in such a way that its count is more in such a way that its count is more than zero so it's better to use priority than zero so it's better to use priority queue here that would be much simpler queue here that would be much simpler so let's first copy dfs so key of the map remains same string and here instead of multi-q we will have priority q u e u e here we need to check if it's absent then we need to create a new priority queue for corresponding to that node when we are inserting a neighbor to the so adj dot uh this is the first one is the uh this is the first one is the source that will be the key for source that will be the key for this adjacency list since we are adding this adjacency list since we are adding it for the first time so t zero means uh so adjacency list is built and our result is so here we cannot directly check like so here we cannot directly check like this if this is absent then this will this if this is absent then this will throw an error throw an error so let's save it not empty here it's a linked list so we can directly add in the beginning in the c process we had not added in the beginning since that was costly for so here we will not need this reverse and the java solution is also accepted and we are right here around 100 mark and here we will sort the tickets so and here we will sort the tickets so that's why whenever we are creating our that's why whenever we are creating our adjacency list already we will adjacency list already we will add uh the one which comes early in add uh the one which comes early in lexicographically lexicographically first so let's sort it beforehand first so let's sort it beforehand and we will sort based on second thing and we will sort based on second thing uh if uh if there is an edge from u to v we will there is an edge from u to v we will sort based on v sort based on v because that is what we are adding as a because that is what we are adding as a neighbor of the first if you has already been inserted a key has already been created corresponding to you then we will simply append it if not then we will you and here also we are appending in the end line 16. line 16. first neighbor first neighbor and the python code is also accepted | 2024-03-24 10:42:16 | 332 | Reconstruct Itinerary | LeetCode 332 | C++, Java, Python |
|
THvEXoEcR_0 | Ki Rupa Is This Video Baikunthpur Discuss About This Question In The East Coast Question In The East Coast Celebrity Speaker Advocate In Great Celebrity Speaker Advocate In Great Souls Scooter Question Was So He Jehovah's Souls Scooter Question Was So He Jehovah's Rules Against Matrix Where Women Are Both Very Rules Against Matrix Where Women Are Both Very Fierce And Forgive And Jerk Fierce And Forgive And Jerk A Consistent Amazon Nutritious Several Years Were A Consistent Amazon Nutritious Several Years Were Now Show Now Show this particular bhi color is amla de dega phone liya m.a. this particular bhi color is amla de dega phone liya m.a. Second year Ishwar Singh so that rotation to Second year Ishwar Singh so that rotation to get metro system so that chakli rotating middle get metro system so that chakli rotating middle player of the matrix will sleep situation player of the matrix will sleep situation security particular dear of the matrix security particular dear of the matrix so isi aggravating this luli a that show is so isi aggravating this luli a that show is love rotating recipe advocated love rotating recipe advocated counterclockwise direction is therefore today's counterclockwise direction is therefore today's inquiry and over and tips inquiry and over and tips inquiry and over and tips spelling of changes so soon 10851 so rotating 10 toughest welcome to 10 questions page control this question will come to this position for them to follow were some simple remedies prescription disposition list Muslim Sudhir WhatsApp questions friend this grade appointment um Can upgrade and see how to return Can upgrade and see how to return Can upgrade and see how to return final spread which is rotation final spread which is rotation five units in the water cooperation so let's see how they can be five units in the water cooperation so let's see how they can be updated on updated on which situation metric app should which situation metric app should perform according to were ritual direction metrics perform according to were ritual direction metrics and offer hussain's hai to is 232 and offer hussain's hai to is 232 compromise retention compromise retention compromise retention Process One Will Move One End To This Post To Facebook Discussion Will Issue This NRHM Dishum Dishum Bittu 12321 56001 Yesterday Morning Previous How They Can Oppose Solution Is That You Can Think And This Particular Layer If If If edit suggestion directly safe from this vansha was continued edit suggestion directly safe from this vansha was continued in this session and written all in this session and written all office numbers in a very active 150 office numbers in a very active 150 over 140 now converted second husband over 140 now converted second husband took these dark gold it 1008 all things took these dark gold it 1008 all things this suicide note to corporation chicken leg piece Cut This One Films Police Facebook Did Acidity Test Will Appear For Next Editing Regional One Products Listen This Particular 15 Day To-Do List Straight Define Presidential Africa And Convert Your In Bill Gates Secondary In This Number At Or C21 Phase Senior Officer Rotation Of This Saath Final Hari Mirchi Is Form 580 Saath Final Hari Mirchi Is Form 580 Saath Final Hari Mirchi Is Form 580 Activists Have Every Right To Activists Have Every Right To You Made The Fighter 134 On You Is This Concept 100 ODI You Made The Fighter 134 On You Is This Concept 100 ODI Cricketers This Particular Morning Will Put Back Cricketers This Particular Morning Will Put Back Side District Side District Member Is Feeder 34 Rotation Is Cheesy So Ultimately What Means That Member Is Feeder 34 Rotation Is Cheesy So Ultimately What Means That Divided Into Divided Into Three Sub Problems Quitting Shayari Sacrifice Rotating Quitting Shayari Sacrifice Rotating Diary-2 That A Promise Cutting Is Hair Pack To Retail Pack To 10 Particular Friend Sulta Services Wicket This So That This Time Play List Till Office Of History And See How It Works Those Those Those on time day suffer from it first time on time day suffer from it first time Champcash also 376 length of address kids Champcash also 376 length of address kids saugandh skin who is the saugandh skin who is the lunch this number Russian lunch this number Russian phone number call extends support number of phone number call extends support number of wealth plus am so am naqsh wealth plus am so am naqsh loot loot you whenever MS Word - two plus and minus two you whenever MS Word - two plus and minus two * * * That This Seven For This Position And Were Going That This Seven For This Position And Were Going In This Direction Shooting's Validity Date In This Direction Shooting's Validity Date Decide Swift 20 This 1575 Similarly Decide Swift 20 This 1575 Similarly Practical Dance Acting Forex Sweater Doing Practical Dance Acting Forex Sweater Doing Well In Preventing Extend's Well In Preventing Extend's Setting The Value Setting The Value Setting The Value in greater noida address and click on service benefit welcome of this particular look service benefit welcome of this particular look so wick but this hadith number 468 feel that in the so wick but this hadith number 468 feel that in the ear but not so x minus minus two ear but not so x minus minus two x back to difficult thing and white x back to difficult thing and white picture That Access Vivo's Election 70 Go That Access Vivo's Election 70 Go That Access Vivo's Election 70 Go Back To Here Single Face Lifting To Times Back To Here Single Face Lifting To Times One Majority Ko Subscribe Now To Us One Majority Ko Subscribe Now To Us Among Us Asli Ruke The Bike Is Us Us War Among Us Asli Ruke The Bike Is Us Us War Festival School Na Yes Beg Sudhir Oppressed Festival School Na Yes Beg Sudhir Oppressed Sample Sharifa Rotation Is Sample Sharifa Rotation Is Given Key So What We Do Diya Is Given Key So What We Do Diya Is Given Key So What We Do Diya Is yes ki vestige vestige to date use what are the values of this day the and skimming person mode song in this that this is the front what I am going to your help shyam limit for little champs is what is what is good that everything The Half The Half The Half 3310 I Position Will Behind 3310 I Position Will Behind A Plus Point A Plus Point Is Suicide Plus Result Plus K With I Is Suicide Plus Result Plus K With I Plus Number 124 Everything Is The Name Of Plus Number 124 Everything Is The Name Of The Committee Member Final Year To All The The Committee Member Final Year To All The Politics Of Bachte And Specific Politics Of Bachte And Specific Advocate Sunil Sihag Medical Shop You Mita Since Advocate Sunil Sihag Medical Shop You Mita Since Creating Creating Creating Off These Elements of This Beneficial Survey Team of Things Will Do Justin Bieber Doing This You My Tab Value Do This Book This Everything Else Will Be Amazed by Shaving The Team That Stuff Scientists Develop This Later Based ft s places wich was initially ft s places wich was initially ft s places wich was initially fruit 24 hotspot of intent 2003 one hair fruit 24 hotspot of intent 2003 one hair fairer leave one and order and share subscribe tappa fairer leave one and order and share subscribe tappa liye vacancy jitna roti the liye vacancy jitna roti the pie cheese isko chhut senior division far hai pie cheese isko chhut senior division far hai aur is particular liya main course aur is particular liya main course certificate par cigarette and previous a bike certificate par cigarette and previous a bike Shamshuddin 10 Pickup Set Clear Converted Shamshuddin 10 Pickup Set Clear Converted Into A Single Every Settings Single Leg Piece Into A Single Every Settings Single Leg Piece Needle Rotator Sakta Are And Pushed Back Needle Rotator Sakta Are And Pushed Back Side Tak Tweet Side Tak Tweet 180 Rishta Khoon And Submitted Active 800 i10 Tulsi Give number of columns of Give number of columns of Give number of columns of which the volume to retail position which the volume to retail position 3000 Android 2.2 Yes and Changing Weather 3000 Android 2.2 Yes and Changing Weather MP3 1000 Half points will continue Hath MP3 1000 Half points will continue Hath Surya First what happens if voted To Surya First what happens if voted To is with a unique position Slip 600 Kamal is with a unique position Slip 600 Kamal ji thanks Mamu Twist and turn layer ji thanks Mamu Twist and turn layer Pickup deep famous battery saver mode temple strong Pickup deep famous battery saver mode temple strong supporter of is located please do you do that supporter of is located please do you do that this green of clans wrestling wave where you want to this green of clans wrestling wave where you want to rotate pie that from this group rotate pie that from this group this 281 home tips and architecture of the pulp this 281 home tips and architecture of the pulp this 281 home tips and architecture of the pulp Protein Vitamin C 12123 subscribe to The Protein Vitamin C 12123 subscribe to The Channel Channel that if taken fight you office that if taken fight you office length of the sense of the Voice of Nation - New length of the sense of the Voice of Nation - New Model subscribe to the Page if you liked Model subscribe to the Page if you liked The Video then subscribe to the Video The Video then subscribe to the Video then subscribe to the Page if you liked then subscribe to the Page if you liked The Video then subscribe to the switch off The Video then subscribe to the switch off यहान पर अंब्रादरी कन्सीव सौहार्द इस वीर यहान पर अंब्रादरी कन्सीव सौहार्द इस वीर वे क्लिए छीज पे बासिक माथ्स 10th है क्या आप जासी आर तार्फ टीम इस हैप्टी विशेष टी बी टक्स उप इंडियाटली कैसी तारन टीम समोकिंग Secession Pass Jhal Not Such Inside Serving Rice Distic In Increase Search Multiple Of Restoration Dena Can Ofton Included In This Technique President General Secretary Sorbets Obscene Come Close To Bread | 2024-03-25 13:03:33 | 1,914 | Leetcode-Cyclically Rotating a Grid |
|
n8xjVezFUfQ | Show More MP3 Video Song Hi Guys Anurag Side So MP3 Video Song Hi Guys Anurag Side So We're Back General Questions 10 Minutes Call We're Back General Questions 10 Minutes Call to Keyboard So what to say in it He to Keyboard So what to say in it He is saying Initials Otherwise Keyboard Only One is saying Initials Otherwise Keyboard Only One Character S President A Keyboard A Character S President A Keyboard A Notepad Surya Went On That One Character Notepad Surya Went On That One Character Presented Okay Presented Okay two operations from another notepad. You can perform two operations on the notepad. The first is copy all. You can two operations from another notepad. You can perform two operations on the notepad. The first is copy all. You can copy all the characters present in a notepad. You can copy all the characters present on the notepad. Okay, the second is paste. can copy all the characters present on the notepad. Okay, the second is paste. can copy all the characters present on the notepad. Okay, the second is paste. copied it, then it is okay, then by asking the second question, you can paste till the characters, thoughts, copied last time, okay, he is saying that the beginning is present, so I have to tell you that the governor number and one number and given. You need so many, you have to get exact panasonic1, okay, so if we look at the situation, it is something like this, this is a notepad, okay, this is a notepad, so I have given it here, The operation has been done by The operation has been done by The operation has been done by copying it, look at one, the other copying it, look at one, the other operation has been done, copy the copy of paste and copy and operation has been done, copy the copy of paste and copy and this will mean that this will mean that as many as as many as this is from late here in which area there this is from late here in which area there are four, so if you copy then it are four, so if you copy then it means do not do this. means do not do this. means do not do this. you have taken 21 off, you will read all four of them to copy this, velvet is four of four, these are the copies, this is oil, but it is copy and this is the meaning, so now what is he asking you to So I So I So I told you how to take NS, how many told you how to take NS, how many minimum operations have I done, how many minimum operations have I done, how many minimum operations can I do for copy and paste, how many minutes minimum operations can I do for copy and paste, how many minutes can you make, it's ok from late, now if you want to see, let's can you make, it's ok from late, now if you want to see, let's remove all this. A note has been made to explain remove all this. A note has been made to explain what's in it. what's in it. what's in it. given you an egg in typing. Okay, so I told you that in equal to zero, tell me that even a single adv1 exam is becoming possible. Okay, so how is the test going to If we If we If we look at it then it look at it then it is there or Anil Bindal & 1210 An Inquest is there or Anil Bindal & 1210 An Inquest zero is possible because one is already available zero is possible because one is already available then if we see that if then if we see that if their value becomes my one then it their value becomes my one then it is that if I make only one then one at least. is that if I make only one then one at least. is that if I make only one then one at least. already pregnant, then I make a small table here, how is the table in between these and the main steps or in the middle of the environment step, if I make a table then it will look something like this, If you have become a, If you have become a, If you have become a, then stable, if you have filled it, then if it then stable, if you have filled it, then if it is my NGO, then it is possible in these these steps, is my NGO, then it is possible in these these steps, take it, believe it is infinite, give is possible in it, take it, believe it is infinite, give is possible in it, you remember, you you remember, you can delete it already, now his mobile number can delete it already, now his mobile number is one, so I is one, so I is one, so I available, so I am looking for one step further, it is zero, okay, then I say there is two quests, two have to be made, I have a way to make two of you, I Then I will make Then I will make Then I will make space here, so how many steps are space here, so how many steps are taken to make one copy? Now taken to make one copy? Now keep in mind that copy is a corporation and keep in mind that copy is a corporation and paste is also another operation, so it is one plus one two. paste is also another operation, so it is one plus one two. Copy paste is not one operation, it is two Copy paste is not one operation, it is two operations. operations. operations. then I have returned it to How to. Okay, then what am I saying that if you see, there will be no other way to make three each, to make me the top 3. The operation is done, then The operation is done, then The operation is done, then you paste it, okay, wash, the operations are done, you paste it, okay, wash, the operations are done, plus one, then you will have to plus one, then you will have to present it one more time to make it free, three operations have been done, present it one more time to make it free, three operations have been done, how many free steps do I need to make it free, there is a little interest in voting. little interest in voting. For interesting, see For interesting, see that now you have to make four of these from the left, that now you have to make four of these from the left, you have only one given for typing, so you have only one given for typing, so what will happen, we will make it in two ways, see from the shop, one is that you have Is it Is it Is it ours or we have presented it three times, after ours or we have presented it three times, after selling it three times, two or three operations, that is, selling it three times, two or three operations, that is, like OnePlus 3, it is like OnePlus 3, it is costing me four for four, basically four, costing me four for four, basically four, what is the other way to make it, what is the other way to make it, I have got it since late. I have got it since late. I have got it since late. do it, I will open the settings, make a copy of this one and then I have done it, so this is done, how many have I used so far, OnePlus One Two seems to be in one copy and on One, it I can copy it from, I can copy it from, I can copy it from, it is completely fine, these are the two, it is completely fine, these are the two, I have copied them, I have applied operation on one of them, I have copied them, I have applied operation on one of them, bar operation offer has been presented to both of them, so it is visible and one step, so it so it is visible and one step, so it takes time, the chart is applied only then. takes time, the chart is applied only then. takes time, the chart is applied only then. similar but the method of operation is different. In this we brush it 1193 times and what we do is make it 12 times and then do the face. Okay, so right now it looks like it is four. Then let If If If I have to make five, then I have to make five, then five will have to be taken from something similar, five will have to be taken from something similar, so how do I take an example so that so how do I take an example so that you can understand things in a better way, you can understand things in a better way, then I take nine from late, I do n't know why I am typing but n't know why I am typing but five is right now five is right now five is right now take it now or is there a line that if I make 9:00 then how can I make that, then if I make it at nine then you will understand what approach should be taken, till now it is Everything is going on, now look carefully, Everything is going on, now look carefully, Everything is going on, now look carefully, okay, here it is written that what okay, here it is written that what I tell you to do is to I tell you to do is to make it in nine, so one of the most travel make it in nine, so one of the most travel way is to copy it, okay, the copy will cost way is to copy it, okay, the copy will cost one per hour, then present it eight times, one per hour, then present it eight times, okay. okay. okay. and then the tilak of the total will be applied. In this way, there is at least one way to make it. Kevin 9 put the cost and keep in mind that if you want to make any N number The maximum cost will be the maximum cost, it The maximum cost will be the maximum cost, it The maximum cost will be the maximum cost, it is okay, we is okay, we cannot exceed this, so if we make a hunter number, it will cannot exceed this, so if we make a hunter number, it will never cost them more, if we extend this then extend this then what can be the other way? He said that what can be the other way? He said that he wrote, okay, one copy of this. he wrote, okay, one copy of this. he wrote, okay, one copy of this. much pressure, you have got one friend to pet you, so the sum is 12. Okay, now how many operations are OnePlus One. Now see, if I paste these two any number of times, I can never make a Northern, why because new models, you are What it means is to What it means is to What it means is to say that this number of S should say that this number of S should always be divided into our goal, only then always be divided into our goal, only then we can present it that many times. How to clear this thing? Okay, so we can present it that many times. How to clear this thing? Okay, so you are clear, two you are clear, two chords have been placed, I have added one more. chords have been placed, I have added one more. chords have been placed, I have added one more. how many times will you get the sequence of the team, now these are the three, if I paste these three one more time, then how to go on foot, how much will it cost to make it eggless, then I got stuck one more time. Okay, here n how much cost was incurred, the total status should be 1234 552, our work is done, earlier our work was being done in non, see, so basically what do I have to do in this question, what will I do in this question, like I I I will start filling my form that I will make it, will start filling my form that I will make it, how much will it cost, I will make it, that will work, if I how much will it cost, I will make it, that will work, if I put three, how much will it cost, if I call, put three, how much will it cost, if I call, how much is it, then how much will it how much is it, then how much will it cost, then find out the answer for six 600 flour, so what will I do now that cost, then find out the answer for six 600 flour, so what will I do now that this is my nine How many numbers can this mark be divided into completely, How many numbers can this mark be divided into completely, How many numbers can this mark be divided into completely, before that before that I will check it. Okay, so how will it be the ninth hottest? I will check it. Okay, so how will it be the ninth hottest? Click on the like button. Here you are Click on the like button. Here you are nine two, the second one is three two three and then nine two, the second one is three two three and then 129. Okay so note my 129. Okay so note my 129. Okay so note my n't matter, I will see for you what is the cost of making it for free, if there is compulsion, tell me to make this situation, these are the three, what is the cost of making them, then I will include in that cost, the method of making it, the So what will I do with this cost, So what will I do with this cost, So what will I do with this cost, how many times can I paste it to how many times can I paste it to make it nine, I will see that these are three A's, then I will make it nine, I will see that these are three A's, then I will press them twice, once again if it press them twice, once again if it is my own, it will not be made, then how will it is my own, it will not be made, then how will it come out, what should I do, there will be a knot in it. come out, what should I do, there will be a knot in it. Divided by three, it's okay, so once I have Divided by three, it's okay, so once I have already kept the paste, how much should it cost? already kept the paste, how much should it cost? 333, so let me 333, so let me sell it two-three times, I have to press it two times sell it two-three times, I have to press it two times because it because it is already there once, so I will say okay. is already there once, so I will say okay. is already there once, so I will say okay. and copy it once. When you copy it, it will cost you, so it will be effective. Look at it once again, it is not okay, If I keep making it If I keep making it If I keep making it from three then it is okay then how many times will I have to present it through from three then it is okay then how many times will I have to present it through and to make nine I will have to pass that free and to make nine I will have to pass that free time but once it is time but once it is already available I am copying at this time already available I am copying at this time ok so basically I will have to present it from two time ok so basically I will have to present it from two time ok so basically I will have to present it from two time but copy it AB Corporation Atul two plus one is okay so this is my work which was already done Pistol Advisor If copied then basically 913 means it will not take three operations for me, okay what do I do it will take three operations Let's look once again at the Let's look once again at the Let's look once again at the intention of making one, how much money did it cost to make Than A, okay, then if it cost like this, then I okay, then if it cost like this, then I copied it, so four operations were done, okay, copied it, so four operations were done, okay, and I presented it twice like this, how much did it cost? Meanwhile Galis, six operations have been done and Meanwhile Galis, six operations have been done and Shiksha will come here, okay, six operations have been done, Shiksha will come here, okay, six operations have been done, I had written it wrong, at I had written it wrong, at one time you told me this one time you told me this number, if that flat gets broken in time, then number, if that flat gets broken in time, then I will see that at which- I will see that at which- So what will I do, I will So what will I do, I will start looking at the multiples of one text, this is the 821 one, start looking at the multiples of one text, this is the 821 one, so I have to make it, okay, after that, so I have to make it, okay, after that, maybe two, maybe two, maybe maybe two, maybe two, maybe f4, maybe f-18, two one. f4, maybe f-18, two one. f4, maybe f-18, two one. fine with multiples, so I will check which late I am making from 4K group. I don't know the cost of the add because I am making my answer once, I I I know the answer to this first, if know the answer to this first, if I make a group of this, then how much is this, I make a group of this, then how much is this, then I can see then I can see that if this one is the Madonna of the whisker, that if this one is the Madonna of the whisker, then how much will it be, okay this one is two. then how much will it be, okay this one is two. then how much will it be, okay this one is two. I want to make it using this, then what will be the answer? So for that, I have just found out from the human being that I have given one number and how many steps and it seems okay to me, so if we want to write in the court then see how we will write. So first of all see this end request request one is fine if only one is made then nothing should be done return zero zero why do we have to do anything one is life imprisonment to make and one is already made ok If there are If there are If there are two, then brother, I will copy one each and present it to you two, then brother, I will copy one each and present it to you friends. Now you will have to return to two, friends. Now you will have to return to two, then what can I say, if I make a camera, I will then what can I say, if I make a camera, I will name it as 'Previous' because of name it as 'Previous' because of how many times it takes to make 'Previous'. You can tell me and and and make and make. Okay, now fill it, one thing told me that the previous zero has no meaning, it is infinite, one, start, So there is zero So there is zero So there is zero cost, if I start with two or if I want to cost, if I start with two or if I want to make this then its cost will be two. make this then its cost will be two. Now I will make a loop for the rest. Let's see Now I will make a loop for the rest. Let's see how it will work. So how it will work. So I started the loop with three because I have to start I started the loop with three because I have to start filling it with 36 hours in advance. filling it with 36 hours in advance. filling it with 36 hours in advance. I know it, okay, I will do it. First of all, I will put it together that the TV is clear, I am the only one. What I mean to say is that if I make a number and then only the maximum can be done to make it then So my answer So my answer So my answer is, if it is better than this, then take it. Okay, so is, if it is better than this, then take it. Okay, so my answer is, if it is better than this, then take it. my answer is, if it is better than this, then take it. Like the net, if we cannot sleep, then to make nine, there is a Like the net, if we cannot sleep, then to make nine, there is a line operation to make nine. There line operation to make nine. There cannot be a number, there is no better answer than this. cannot be a number, there is no better answer than this. cannot be a number, there is no better answer than this. saying, I understand that this thing is fixed, then what will be the previous five, I have agreed, then what should I do, I will take it, Jai Guru, I start with I want to, then it means to say, look, it is like If I want to make my number a multiple, If I want to make my number a multiple, If I want to make my number a multiple, then its smallest number will be 1622. then its smallest number will be 1622. What has happened, it will become * 21, What has happened, it will become * 21, then it will become into six. Sorry, I am then it will become into six. Sorry, I am writing here that writing here that a train will go to education, it will be okay, by doing this it will become a train will go to education, it will be okay, by doing this it will become very useful. very useful. If you If you multiply any number by train, it will be 1220, then the multiply any number by train, it will be 1220, then the first one who is its multiple must be first one who is its multiple must be practicing this, the even number is 9 practicing this, the even number is 9 and you have taken some other number. and you have taken some other number. So it was said seventh class 6, then it became 70 So it was said seventh class 6, then it became 70 less than that, ok it means to say that we need a less than that, ok it means to say that we need a number to divide, so I am wondering number to divide, so I am wondering from which will it start, now you will accept that we started from 8, from which will it start, now you will accept that we started from 8, then make the ad a matter with you and then make the ad a matter with you and send it. send it. send it. If you consume it, then F-18 will come. If it is not there, then we will look further down and see if this 1622 is coming, will you find such words, then 512 So I want to So I want to So I want to sons of unlawful How long will I do of sons of unlawful How long will I do of wild a great many 1212 Okay wild a great many 1212 Okay okay as long as my country is greater than one okay as long as my country is greater than one 121 121 Now what is there to see here Now what is there to see here I want to see my here that means that I want to see my here that means that if I am if I am if I am What does it mean, what should I do after making notes18's ATM that the soil has taken the ticket till active on this occasion, so what I started doing, see, you are please check that while dividing not, write to the team If he does ninth then C is in a hot mood right, If he does ninth then C is in a hot mood right, If he does ninth then C is in a hot mood right, that is, nine is basically one of its that is, nine is basically one of its factors, after bursting, I will check add, factors, after bursting, I will check add, do the same again, then check six, do the same again, then check six, for which I will answer, for which I will answer, okay, so what am I doing? okay, so what am I doing? okay, so what am I doing? FIR Model Jaggu Secretary, DP Sharif Previous of I What will happen to me that I am Dormant Yadav, the answer given right now is there, if he is better and he is younger then let him be, otherwise what else do I have to do, Now Now Now listen carefully, we had to make this difference nine, one is one, listen carefully, we had to make this difference nine, one is one, so I saw that if I so I saw that if I press it twice in Delhi then it will be right, then if we press it twice in Delhi then it will be right, then if we need the cost of making three, then three will be need the cost of making three, then three will be our model, so I our model, so I our model, so I will I do aa previous of j ok this cream all this place means how close to make the free co look plus i visor meanwhile sexual - oneplus one should be well why because so many times don't present me your body come times ne do Advisor - If you want to close it but you will have to copy it again, then it will be effective - 9 paise here, you will get cancer. Okay, so this is done, you have saved it in the environment and this - - I will do it, but I don't have to do anything, Give the returned DP of those Give the returned DP of those Give the returned DP of those who were kept in it, I will make it my warden who were kept in it, I will make it my warden at my end, I will try and see, there is no good OTP, its name is sorry, by the way, there is a question on DP, If If If yes, then you have to submit it and see, yes, then you have to submit it and see, I am reading everything, if the answer is yes, then you are done with it, okay, now this one has got it, okay, this question has a catch in this question, well, now that may be an opportunity for you It is possible that if you do this much It is possible that if you do this much It is possible that if you do this much in the interview then your work will be done in the interview then your work will be done but it is late, okay, there are but it is late, okay, there are many ways to make the team, make 120, many ways to make the team, make 120, okay make two into nine, okay okay make two into nine, okay make 326 or else 1957 16231 Hello Saifina. make 326 or else 1957 16231 Hello Saifina. make 326 or else 1957 16231 Hello Saifina. Make it or whatever text-21 we have to make, all these will be its what will be its murders, its factors will be there, there are ways to make the team, then you will observe all the numbers you get, you will see that always with the largesse factor. What will you do with the largest factor, if you multiply, blaster means editing, okay, then 13 back to Noida will start from Noida, basically multiple and if it is any other number, let's say it So let's So let's So let's start tension that we will see if we divide by start tension that we will see if we divide by 10:00 then it will not work, no, when we 10:00 then it will not work, no, when we consume quietly, then seven into thin will be the consume quietly, then seven into thin will be the main and answer to it, now main and answer to it, now how is it, that was basically observation, friend, how is it, that was basically observation, friend, nine for you too. nine for you too. nine for you too. is 1297, 3237 or 921, then you will see that the one with 323 is the one who is always giving the answer, so we can directly save the complexity of the people, we will To protect it, if To protect it, if you immortals come into conflict, then you immortals come into conflict, then basically unite them, then what is the basically unite them, then what is the benefit of this, unnecessary benefit of this, unnecessary checking will be going on, we will not have to do that checking, so what I have done here is that what I have done here is that if if if so I will do CBI team will do 290 if I am dividing then Noida will be my answer only one cool ok so if we submit then it is taking 21 If you submit then it will be done in milliseconds, it is ok and 15159 percent Paas like from Java solution, this is a 3D question of this question, if it is an easy question then I would have understood it and if there is any don't then you Ho and you Ho and you Ho and you can ask on Instagram Tak Ram's handle is N U R A G can ask on Instagram Tak Ram's handle is N U R A G Anurag COD Just okay so this is the Anurag COD Just okay so this is the handle of Takraar, now you can go and ask and if you have handle of Takraar, now you can go and ask and if you have any question request then you any question request then you can also put it in the comment on your Instagram. can also put it in the comment on your Instagram. can also put it in the comment on your Instagram. please make this question so I will make it for that 10:00 bye bye | 2024-03-20 14:41:59 | 650 | Leetcode 650 | 2 Keys Keyboard | Hindi | Explanation + Code |
|
kPMwkZ84Lh8 | hey what's going on guys it's ilya bali here i recorded stuff on ilya bali here i recorded stuff on youtube chat description for all my youtube chat description for all my information i do all information i do all liquid problems uh make sure you liquid 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 is thumbs up to support it and this is called flower planted with no adjacent called flower planted with no adjacent you have and gardens labeled one to n in you have and gardens labeled one to n in each garden you want to plant one of each garden you want to plant one of four types of flowers four types of flowers bad at the position of i is equal to x y bad at the position of i is equal to x y describes the existence of a describes the existence of a bi-directional path from carbon x to bi-directional path from carbon x to carbon y carbon y also there is no garden that has more also there is no garden that has more than three pad than three pad coming into or leaving it your task is coming into or leaving it your task is to choose a flower type for each garden to choose a flower type for each garden such that for any two gardens connected such that for any two gardens connected by by path have different types of flowers path have different types of flowers return any such choice as an array return any such choice as an array answer or answer the position i is the answer or answer the position i is the type of flower type of flower planted in the i plus one garden the planted in the i plus one garden the flower types are denoted one flower types are denoted one two three or four is guaranteed an two three or four is guaranteed an answer exists uh well let's look at answer exists uh well let's look at those those examples we got n examples we got n uh is three but one two uh is three but one two two three three one return output one two three three one return output one two three two three and is equal to four but one two three and is equal to four but one two three four four output one two one two and is four but output one two one two and is four but one one two two three three four four one one two two three three four four one one three two three two four output one two three four well four output one two three four well um n is greater than or equal to one and um n is greater than or equal to one and is less than or equal to 10 is less than or equal to 10 000. the size of those 000. the size of those path is greater than or equal to 0 and path is greater than or equal to 0 and is less than or equal to 20 is less than or equal to 20 000. no garden has four or more bats 000. no garden has four or more bats coming coming into orlando it's guaranteed an answer into orlando it's guaranteed an answer exists exists uh right to the bad we uh right to the bad we can create an array to type integer can create an array to type integer and return that array and return that array the end new integer length of the race equal to the number of gardens we could use map we got we could use map we got integer the type for keys integer the type for keys and set of the type integer for values and set of the type integer for values we got a key value volume we got a key value volume is associated with the specified is associated with the specified key type integer this case key type integer this case it's called map nothing special it's called map nothing special new hash map the type set of type integer is the value um create a for loop and i is zero is less than at each iteration we put i as key at each iteration we put i as key and new hash set and new hash set the type integer as the value create another for loop uh we're gonna loop through those b at the positional one minus at the positional one minus one then for a neighbor one then for a neighbor get e one minus one get e one minus one that at b at the position of zero that at b at the position of zero minus one we have minus one we have um undirected um undirected edges yeah edges yeah and we create the for loop and we create the for loop and i is equal to zero and i is equal to zero uh i is less than the number of gardens i plus plus uh the time complexity for this solution 1.5 and uh 1.5 and uh where big o of you know n and where big o of you know n and big of past the time big of past the time the space complexity is big off um okay here um okay here at each iteration at each iteration we will be creating an array we will be creating an array it's called um it's called um types you could notice from the description of that problem that um this problem that we have for types we say the length of that array is equal to 5 because that's one based indexing yeah use five instead of four here uh j on map door get in the case when our enabler in the case when our enabler has not used uh has not used uh the type yet the type yet we do nothing in the case when we do nothing in the case when the neighbor has used the type the neighbor has used the type uh we mark that type uh we mark that type as used set up the value 2 as used set up the value 2 1 um 1 um use you know use you know types at the position of the answer the prediction of j one create another for loop into a is four j is greater than zero k minus minus in the case when uh the type is not been used yet we can use that type we use that type so types the position of j is zero we got a bunch of zeros by default uh answer uh answer at the position of i is at the position of i is j code code accepted good let's submit success well you can imagine um a graph and let's look at this example this one we got pass one two three four and four uh zero one two and three and sets right there here we are looking through those uh through those rows uh b at the position of zero one minus one e zero zero we add uh b at the position of one two minus one one um so right here you can imagine an edge uh like you know or let's say one two right one two or let's say one two right one two it's like zero and one it's like zero and one zero and one yeah um so from the position of one we can get to two and then mob that get be at the position of one which is two two minus one which is one one we add let's set uh b at the position of zero one minus one zero zero so from this point from two we can get two one as well undirected edge and the same for this one three four you know three four the position of uh two to two to uh four minus one three to four uh to four uh 2 and 3 and then from you know 4 minus 1 2 and 3 and then from you know 4 minus 1 3 3 2 3 3 2 uh 3 minus 1 2 uh 3 minus 1 2 to two from four we can get to three and from um that's it like and then we do um that's it like and then we do those things already explained right those things already explained right yeah thank you guys for watching leave yeah thank you guys for watching leave your comments below your comments below uh i wanna know what you think follow me uh i wanna know what you think follow me on social medias follow me on instagram on social medias follow me on instagram admin snapchat and i'll see you next admin snapchat and i'll see you next time time bye | 2024-03-25 15:41:37 | 1,042 | LeetCode 1042. Flower Planting With No Adjacent Solution Explained - Java |
|
4R1XnP-6UZw | hello so this question is picking iterator so you have to design the iterator so you have to design the iterator let's support the picking iterator let's support the picking operation on the existing iterator in operation on the existing iterator in addition to the test next and then next addition to the test next and then next operation so this is uh pretty operation so this is uh pretty straightforward for iterator uh straightforward for iterator uh implementation so uh what do I need to implementation so uh what do I need to do is I need to uh incremental class and do is I need to uh incremental class and then there are three different methods then there are three different methods and basically you just need to uh using and basically you just need to uh using the iterator the iterator uh something like this and then you put uh something like this and then you put in the inch right you put an inch into in the inch right you put an inch into the the uh uh iterator class and let me say this is ID iterator class and let me say this is ID and you need to also have the next next and you need to also have the next next is what is the next value of the is what is the next value of the iterator next so which is uh I Theta iterator next so which is uh I Theta next next right the next should be what equal to right the next should be what equal to this this and then you just traversal and then and then you just traversal and then this will be here right so uh let's just this will be here right so uh let's just start coding so what I will do is what start coding so what I will do is what iterator and I also have an integer next so I will have to uh to find my ID which is iterator to iterator right so I'll basically just reassign and next I will say it go to default and then so uh once I set next to uh next to no I need to make sure that's my iterator iterator integer ID has next so I'm going to just call hazmax if you do and then I'm going to assign my next so I'm actually Traverse uh Traverse my it and for this one has next I'm going to just say that's my next is uh that's not equal to no or what I T uh that's not equal to no or what I T that has next right so I basically can Traverse my uh area but I don't actually call it.net over here this is because if you do then you probably will miss out the next function we want to override it and then for the pig right since you have next value but you are not actually moving your index so imagine you are at least index so I'm I'm just uh join a box over here so you are you are here this is your current ID Index right and this is your next value right but you are not actually moving right so you need to uh just uh return the value of names for the kit right and then follow next you need to actually store the value so I'm going to say current equal to next then I will move my pointer to the next one right and then reassign my next to here if there's a value right so straightforward you know so this is going to be next and now I'm going to just stored in my current value to next right return the current for sure and then if it dot has net right you you cannot you cannot just call if ID dot next because you need to make sure if I did the test next then you need to return something which is next equal to 80. if not languages I then just Define next to no so this is going to be pretty much a solution so yeah Summit alright so let's talk about the timing space this one for the time uh this is what although all of one right because you don't actually Traverse all of the value in the iterator you uh you assign a memory allocation and then for the space this is definitely all of them and representing the lineup later right now take it they pick it should be about all all of one for timing space this one all of One Like You are not actually Traverse the whole entire area you just Traverse the next one right and this is all of one so follow quick notes this is this is pretty much a solution so uh subscribe if you like it and comment if you have any questions so I | 2024-03-22 14:10:30 | 284 | LeetCode 284 | Peeking Iterator | Iterator | Java |
|
EKm6oLVwsQc | starting to so now I have three five six eight nine is the total sum here and then starting at 3 and a 3 that is 1 1 and this adds 2 3 4 6 and 7 and similarly God just let see if we construct this table 5 6 and this is 1 3 4 I still this table 2 & 1 this is not 1 so this one so here's 3 so by doing this we have calculated the sums of all the sums of all sub-arrays with an A so now now I let's see if we can use this information to get the final result we want the final result we want is for sub arrays that have the same sum so I think we can do this in okay so again this is gonna be another N squared skin so the skin square decathlete table and then let's try n squared skin so let's start at 1 1 let's look at 2 to know send me 3 3 4 4 & 5 5 & 7 7 so in this case we have 4 indexes but we could have looked actually not sure if this actually give actually not sure if this actually give us because we need to take directly one us because we need to take directly one 1 two 2 three 3 four 4 if they're not 1 two 2 three 3 four 4 if they're not equal to any backtrack and take 5 5 or 6 equal to any backtrack and take 5 5 or 6 6 or 7 7 so this is still in into the 4 let me mmm how much time do I have left let me mmm how much time do I have left I have 18 minutes okay let me just I have 18 minutes okay let me just strike two so again I solution like strike two so again I solution like let's just try one one compared to find let's just try one one compared to find these separate so let's okay so this is these separate so let's okay so this is me and squirts cancel it take the very me and squirts cancel it take the very first element and then starting index to first element and then starting index to scan until you find something that's scan until you find something that's over the current sum and then you start over the current sum and then you start at three three and then this is over for at three three and then this is over for four or five five six four or five five six okay so I think this is actually still okay so I think this is actually still eight and and squared scan so it's on eight and and squared scan so it's on the N squared total in this case okay the N squared total in this case okay let me just count this and then we'll let me just count this and then we'll see if this passes okay so here so DP of see if this passes okay so here so DP of zero zero is if written so at least let zero zero is if written so at least let me think it's gonna be the start and the me think it's gonna be the start and the end index so okay I think we can just do end index so okay I think we can just do D P of n okay so let's create the table D P of n okay so let's create the table first first so we start at the let's say I'm for so we start at the let's say I'm for some difference is zero all right there should be we start at all right there should be we start at the left left equals zero and now the the left left equals zero and now the right is let's just eat DP left left right is let's just eat DP left left equals right okay so that's four into equals right okay so that's four into equals one plus three plus the name equals one plus three plus the name right plus plus okay so now we want to right plus plus okay so now we want to add a right plus DP left right minus 1 add a right plus DP left right minus 1 which we should have already done on the which we should have already done on the previous iteration so it's 2 DP left previous iteration so it's 2 DP left right cause this you just make sure this right cause this you just make sure this tables I'm just just make sure this tables I'm just just make sure this function is correct before move on function is correct before move on that's two so just 18 okay so one DP so this is one three two three four five this does not look correct what's going on so one three four six seven one three four six seven nine tenth the first rows correct the second row two three five six eight nine so it's the very seems like the very last element let me just do a smaller test case here let me just do a smaller test case here just so it's easier to think about my g1 just so it's easier to think about my g1 so it went three four so okay so seems so it went three four so okay so seems in the second row second row left is I didn't I didn't name these scribbles very well quick equals a row row sorry she not sigh yo+ right he goes anybody okay so let me try the base case like okay so let me try the base case like going to okay so that works going to okay so that works I just the second row is not okay I just the second row is not okay so 1 1 plus 1 is less than 2 so this is row okay I see should be blue plus right so we're not increasing this TP row-column plus one - okay I see TP row-column plus one - okay I see little plus right here this is Rho plus little plus right here this is Rho plus right minus 1 1 3 4 2 3 2 1 ok now this right minus 1 1 3 4 2 3 2 1 ok now this looks correct looks correct let me try - one - one let me try - one - one this one's we had two three eight nine this one's we had two three eight nine six seven five one three four - three six seven five one three four - three and one okay and one okay now this table is correct now let's try now this table is correct now let's try to derive the answer these nice table to derive the answer these nice table it's initialized to false now so we want it's initialized to false now so we want to iterate no 8 that considers every to iterate no 8 that considers every possible prefix so again we start with possible prefix so again we start with left equals 0 0 less than that's plus left equals 0 0 less than that's plus plus and then let's do the end so for a weight equals goes left right less than weight equals goes left right less than in great plus plus in great plus plus okay now the candidate this will okay now the candidate this will generate every possible starting generate every possible starting candidate for us so let's just say candidate for us so let's just say candidate equals DP left right okay so candidate equals DP left right okay so now for each of these we want to Ford now for each of these we want to Ford scan our table and see how many and see scan our table and see how many and see how many total equal sub arrays of a how many total equal sub arrays of a cell and we can do this free to e as cell and we can do this free to e as soon as we see one possible sub array we soon as we see one possible sub array we will take that answer it's always gonna will take that answer it's always gonna be the best choice so let's do this in be the best choice so let's do this in one scan private say this is find take a one scan private say this is find take a dpi ring so the starting index is gonna dpi ring so the starting index is gonna be the right plus one to start in and be the right plus one to start in and equal zero we want this to be at least equal zero we want this to be at least three so yeah so we start at J and C seven so yeah so we start at J and C seven minutes so we start at J you scan one pulls up J less than n + + + o so there's DP j + end holes so we need our target sum here and target this equals target down + + and then we want J equals end and I want to break out of if he did it the start will be the rate if he did it the start will be the rate plus 1 and then the candidate is the plus 1 and then the candidate is the target true okay let's see if this runs it won't but well CPU right plus one signed 51 I found has to be at least three holy I kind of worked okay let's try another example here so let's say our target sum is 3 1 2 0 0 3 1 1 1 and then let's say or take the 1 so let's see if that's a 3 2 sides 2 3 4 negative 1 a 3 that's a 3 2 sides 2 3 4 negative 1 a 3 maybe they don't consider like no they maybe they don't consider like no they do zero okay I misread okay I do zero okay I misread okay I misread the question so we are trying to misread the question so we are trying to find I J and K such that if we take away find I J and K such that if we take away these three numbers the four remaining these three numbers the four remaining sub arrays are equal so I did this sub arrays are equal so I did this question wrong okay how do I so I have three minutes left let's try so I have three minutes left let's try to think about this real quick so like I to think about this real quick so like I think for that question let's just see think for that question let's just see if this solution works for like what I if this solution works for like what I thought the question was should be false this is false so I mean at least I coded up this shitty function oh good job all right let me delete this this is a lesson learned I can hope your father watches this and choice me fail so if I have three so instead I want to find three values three values where if we take them out for submarines or equals again we can do this naively we just again we can do this naively we just take out try every combination of three take out try every combination of three indexes trying to think of how to do it indexes trying to think of how to do it better so again I think if we take the better so again I think if we take the sum so for any if we know we have to take out three values only then let's then we know that the sum of these three values has to be up this array has to be a divisible by four right so after taking out three values the total sum of that means FGP Xian 3 Daly's the total sum has to be divisible by 4 so we could this could speed up the naive approach were like for any three indexes like if we take them out if we subtract them out from the Sun if we know it's not divisible by 4 then it is we did not we did not I'll see we did not pass this question I'll see we did not pass this question but I will now go ahead and actually try but I will now go ahead and actually try to solve this and without the mock to solve this and without the mock contest okay so like now it's in the new format so unfortunately like this recording is not gonna work anymore but anyways thank you for watching I'll just end the recording here and I'll try to sell the | 2024-03-20 10:53:35 | 548 | 548 Split Array with Equal Sum |
|
nFiAUwTH0zY | he-hello there so got to quickly talk about today's recruiting challenge about today's recruiting challenge question it's called first a unique a question it's called first a unique a character in the string and the question character in the string and the question is as follows given a string we want to is as follows given a string we want to find the first non repeating character find the first non repeating character in it and return its index if there if in it and return its index if there if there are no such character meaning there are no such character meaning every character has at least the more every character has at least the more than one x then we should return active than one x then we should return active one so this question yes I think it's a one so this question yes I think it's a sort of like a watered down version of sort of like a watered down version of 1429 first tunic number which is also 1429 first tunic number which is also our coding challenge question for last our coding challenge question for last month's so I do have my own video about month's so I do have my own video about it if you interested you can check out a it if you interested you can check out a link there I also put our spin on it to link there I also put our spin on it to support pop so the video is quite long support pop so the video is quite long yeah it's kind of interesting if you yeah it's kind of interesting if you want to consider pop so definitely check want to consider pop so definitely check out the video if you want are you out the video if you want are you interested in looking at that so just interested in looking at that so just for that let's go back to this question for that let's go back to this question so if we look at the string lead code we so if we look at the string lead code we see that Karthik LT Co D the the all see that Karthik LT Co D the the all appeared only once e is the only appeared only once e is the only character that appear more than once so character that appear more than once so the question asks us to grab the rare the question asks us to grab the rare first one that was no repetition so it's first one that was no repetition so it's L so the index is zero so to solve this L so the index is zero so to solve this problem we can just do one scan through problem we can just do one scan through the string to cut up at the number of the string to cut up at the number of times each character appeared in the times each character appeared in the string and do a second round of check string and do a second round of check from left to right for each of the from left to right for each of the letters we encounter we check whether letters we encounter we check whether the letter has a frequency column one or the letter has a frequency column one or not if it's one then the first one we not if it's one then the first one we find you know from left to right it's find you know from left to right it's going to be the one that we want to going to be the one that we want to return its location so that's a two return its location so that's a two linear path in the worst case and the linear path in the worst case and the space is going to be the hashmap which space is going to be the hashmap which stores the in a number of times each stores the in a number of times each character appeared so the size is equal character appeared so the size is equal to the vocabulary size that's the total to the vocabulary size that's the total number of number of you need the characters in a string so you need the characters in a string so it's a it's actually quite optimal it's a it's actually quite optimal already if we want to do even slightly already if we want to do even slightly better we can we can utilize something better we can we can utilize something like order to map order dictionary like order to map order dictionary potentially coupled with a set or or not potentially coupled with a set or or not we can we can do that either there are we can we can do that either there are there are multiple solutions we can use there are multiple solutions we can use a set to do deduplication or we can use a set to do deduplication or we can use the order dictionary which the values be the order dictionary which the values be a couple of number of times it appeared a couple of number of times it appeared and the last locations we find it and and the last locations we find it and just keep moving that whenever we update just keep moving that whenever we update that key value pair we'll move it back that key value pair we'll move it back to the linked list and of the linked to the linked list and of the linked list and we're fine so there are list and we're fine so there are multiple ways to improve the first brute multiple ways to improve the first brute force solution to be strictly one pass force solution to be strictly one pass the missus it the necessity is not as the missus it the necessity is not as not very high so I'm just going to code not very high so I'm just going to code up the hashmap frequency count and do a up the hashmap frequency count and do a second scan to find it first second scan to find it first and then code a set plus order and then code a set plus order dictionary solution that's the solution dictionary solution that's the solution is pretty much essential to the 2d to is pretty much essential to the 2d to the solution here we have a set and a the solution here we have a set and a dictionary but to support pop it won't dictionary but to support pop it won't be a little bit more difficult so again be a little bit more difficult so again if you're interested you can check out if you're interested you can check out my video yeah so so just going to talk my video yeah so so just going to talk about this question the simple about this question the simple straightforward solution we're going to straightforward solution we're going to create a hash map a store the character create a hash map a store the character to its frequency count to its frequency count let's call char frequency which is the just gonna contour on the string and then do a second scan from left to right we want to grab the location as well so if this character has a frequency count of exactly 1 we'll just return its location if we don't return anything while this for loop meaning whether for left or right we tested every character we we still couldn't find one with the frequency comping 1 we return negative 1 so that's the code yeah so in terms of the solution this is definitely our easy level question so a little bit improvement can be can be that we repurpose this hash map use it to store and it has to be ordered so the the keys and it has to be ordered so the the keys of sorted based on the time it's being of sorted based on the time it's being inserted so onto the hood it's a hash inserted so onto the hood it's a hash map plus a linked list kind of data map plus a linked list kind of data structure hybrid in there and we're structure hybrid in there and we're gonna just assess to do deduplication so gonna just assess to do deduplication so every time we see a character more than every time we see a character more than once we make sure that we remove it from once we make sure that we remove it from this hash map so in the end we can just this hash map so in the end we can just check on the key value seen here in the check on the key value seen here in the hash map those will be the characters hash map those will be the characters with only one appearance in the string with only one appearance in the string and this is ordered we can just grab the and this is ordered we can just grab the rare first one it's guaranteed to be the rare first one it's guaranteed to be the first non-repeating character industry so it's just they're just going to be a house branch based on whether we see this character or not just pizza the second time at least as a second time we see this character we will make sure that it's never in the hashmap anymore so we pop it off and else we will remember yeah this is the first time we see it and we want to remember its location so we can after this just a one pass we can you know a return statement here so if the hashmap is empty there is no character with exactly one time appearance we can return negative one yeah so this is pretty much the code yeah so this is pretty much the code it's a linear in time just the one pass it's a linear in time just the one pass strictly one pass through the string and strictly one pass through the string and the space it's proportional to the the the space it's proportional to the the in the worst case is going to be to in the worst case is going to be to multiply by the character size the size multiply by the character size the size of the vocabulary because both seeing of the vocabulary because both seeing and character character location can and character character location can take up until if everything is unique take up until if everything is unique it's going to be you know to multiply it's going to be you know to multiply two data structure each with number of two data structure each with number of unique character as as the size so let's unique character as as the size so let's submit this one as well I do have an submit this one as well I do have an arrow so next I forgot a if statement it runs example yeah so it works here you are to solution one is to pass with strictly one data structure that's linear in size with the book I'll resize the second one the space can potentially double but the time can potentially be half so you got a trade-off there so | 2024-03-24 12:01:35 | 387 | Leetcode 387 First Unique Character in a String |
|
I83XgeSiqsQ | Hello friends to Jhal Ajay, once again welcome Hello friends to Jhal Ajay, once again welcome all of you to your YouTube channel Teacher Thi, all of you to your YouTube channel Teacher Thi, so in today's video we will list some so in today's video we will list some very interesting questions of Purti Vriksha, very interesting questions of Purti Vriksha, so basically the questions so basically the questions are of mathematics category type and a little bit of Ko Minute Vriksha is also are of mathematics category type and a little bit of Ko Minute Vriksha is also included. included. included. and then let's see how it can be this year then dacoits executive work at a point to figure out which you have to means to test to determine which this means to test to determine which this means to test to determine which this is E and then after that he has is E and then after that he has given some ways how we can fit the picks to given some ways how we can fit the picks to get some tips get some tips and then give each one some time to sign The and then give each one some time to sign The Pick Will Consume All Rituals But Sentence Pick Will Consume All Rituals But Sentence Real Admit Real Admit Real Admit and no one will take time but after consuming any but who, neither a single minute is this a factor or a parameter, so it has to be seen We will have to hold a long We will have to hold a long We will have to hold a long meeting of that last month meeting of that last month i.e. i.e. how much we will have to wait for it to dry then that how much we will have to wait for it to dry then that is the minister you may not find any other pics during this time to this time you can't do any more to this time you can't do any more stupidity stupidity stupidity terminus to divide is text debit the point but different appointment diner dash roy printer professional attitude and not the time to point let's see it that where look like suppose I have From From From and exactly one butt, what is one of these exactly, and exactly one butt, what is one of these exactly, a big problem, should one drink the a big problem, should one drink the confirmed chakli, one, even I do confirmed chakli, one, even I do n't know that is the point, that's n't know that is the point, that's why I gave him some to drink, I bought some from the market, okay, did I why I gave him some to drink, I bought some from the market, okay, did I grind it or did people make him grind it or did people make him drink it? drink it? drink it? value is two, take two pieces, I am here, this is two, don't go to the diagram, just go to the conductor, so these are some people, this is I have to test this, which butt means I There There There will be a back side and after that there will be a test. It is will be a back side and after that there will be a test. It is very important here that you note very important here that you note that if there is Malviya page number one on any one, that if there is Malviya page number one on any one, this is pin number two, then I this is pin number two, then I will admit this paste and send one text at a time. will admit this paste and send one text at a time. Okay, one thing. Okay, one thing. Okay, one thing. if I say that I am doing this and this from the pocket, I am doing this and this, okay, now it will weaken both of them, Even if it Even if it Even if it is there, is there, who will tell me which of these but I who will tell me which of these but I was poisoned because I have got him was poisoned because I have got him tested for both, now I too could be in this too, tested for both, now I too could be in this too, could be in this too, could be in this too, what will I have to do for him then I will have to do it what will I have to do for him then I will have to do it again. again. again. but kilometer topic long on adapter day match gas is any one butt poisoned or not then pick at that time you are not like that with a goat also Two, if you Two, if you Two, if you make it consume two, then what will make it consume two, then what will happen to us, advocate, when will we get this confirmation, which happen to us, advocate, when will we get this confirmation, which butter was we, so this is a little bit of a butter was we, so this is a little bit of a very important point here that we will make a page that very important point here that we will make a page that even a bird will consume at a time, this is even a bird will consume at a time, this is this. this. this. either this one, this one, this one, he has the options, he will do all three, only one at a time, then this or this or this, then the confirmation will come, why is this done? Now it comes to the point of operation and after applying 21 minutes to the sector, enter the minutes and 1 minute to test, ok, what is this thing, both of them are telling that it will pass the test in half an hour, I will give the pause to my customer in an hour. in an hour. in an hour. I don't care about it, within half an hour and that's it, I have controlled this pest, now I came here and stood up, now I went into the room and for how many minutes can we do this, maximum, No, any No, any No, any melt will take 10 minutes, it will happen melt will take 10 minutes, it will happen within 10 minutes only, if it happens in within 10 minutes only, if it happens in more, then more, then spend 10 minutes in this observation period, if it spend 10 minutes in this observation period, if it all comes in the observation plate, then it means that if all comes in the observation plate, then it means that if not only in this, then not only in this, then this, then In this type, I have a In this type, I have a In this type, I have a little more of this, little more of this, which takes 5 more which takes 5 more minutes and what he was minutes and what he was saying, I told that it will take any saying, I told that it will take any time and time and test it and if any customer of mine can weigh it test it and if any customer of mine can weigh it in so many minutes, then I said that Mirwaiz and I then I said that Mirwaiz and I believe in the thing which believe in the thing which That in every trial, in every experiment, That in every trial, in every experiment, in every method, he never reads any topic, in every method, he never reads any topic, when a wanderer in any of the when a wanderer in any of the trials, if he does not die then what trials, if he does not die then what will matter, at what maximum will matter, at what maximum will I perform the experiment, such as will I perform the experiment, such as Suppose I did an experiment once, Ignored did Suppose I did an experiment once, Ignored did not come, did not accept, second, not come, did not accept, second, what happened next, 15 minutes before my death were what happened next, 15 minutes before my death were wasted, I invested in females wasted, I invested in females and he did not even refuse, in the next time period and he did not even refuse, in the next time period also he will be wasted not only in Marathi but also in females. also he will be wasted not only in Marathi but also in females. So how much will this 1615 go to, So how much will this 1615 go to, if I add a number time plus to 1615, then it should be equal to this, so I should if I add a number time plus to 1615, then it should be equal to this, so I should really have it really have it because above sixty minutes or because above sixty minutes or above aerial minutes, I will above aerial minutes, I will never be able to perform the experiment anyway, so this thing is never be able to perform the experiment anyway, so this thing is loosening it. loosening it. loosening it. take it one more plane that next two will go to maximum maximum equal to two, then this shows that the numbers and trials, the number experiments which will be mine, will be the waypoints that if brother it sticks with me, there So the minimum is four, so I will be So the minimum is four, so I will be So the minimum is four, so I will be able to do this, the maximum is four, I will be able to able to do this, the maximum is four, I will be able to make zero trail, I have not made this crazy journey at this place, so this was an make zero trail, I have not made this crazy journey at this place, so this was an observation here, now a observation here, now a little question, now it is a bad frame, little question, now it is a bad frame, now this should be understood after this type. now this should be understood after this type. Now this much is known that friend look Now this much is known that friend look maximum friends, 215 dowry phone means maximum friends, 215 dowry phone means virus will go to this compound maximum now if virus will go to this compound maximum now if I talk about travels then I talk about travels then how many trains were there, we have come to know that how many trains were there, we have come to know that travels will be Raipur Nak, ok this much travels will be Raipur Nak, ok this much is clear now one is clear now one is clear now one that will also be there, there will be one in it, in which there will be one from one side, so therefore we will save all the picks, in the total total also be one oil in the plus, in which if there We will have that butt We will have that butt We will have that butt noise, whether it is printed without any pack or noise, whether it is printed without any pack or not, it will tell us in the same way that we have a not, it will tell us in the same way that we have a tab in which the points will be butt, it will definitely tab in which the points will be butt, it will definitely be hundred percent, so this be hundred percent, so this point question will be the total number of trends, point question will be the total number of trends, now let's talk. now let's talk. now let's talk. of the landscape, if I get the numbers and the pick near me, then I know how many holidays and how many travels can be a part of the gas, on which I said, Not Marathi, if this is the first Not Marathi, if this is the first Not Marathi, if this is the first trail, if you have made it in the back race, then the next trail, if you have made it in the back race, then the next person will also have to pass from behind, after this, person will also have to pass from behind, after this, all the people will have to go behind, how many all the people will have to go behind, how many things will Yogi speech give, he can take part in the trial, things will Yogi speech give, he can take part in the trial, because of this he is total. because of this he is total. because of this he is total. made, how much is it made of power, that it has become stars, that now if it has become stars, then I have also increased the speed, the power points, how much of the attacks have gone, you tell me, how much will it go, I said that it is more. Whatever travel award travels and goes to whatever number, all this should remain as much as the alarm set max loosening question number of but should remain as much as Birds Beerwa because if but SIM will not be left but In the end, if it becomes zero and goes negative, In the end, if it becomes zero and goes negative, In the end, if it becomes zero and goes negative, then nothing will happen, there is no benefit, then nothing will happen, there is no benefit, so whatever is done atomic, the work will continue till October, so whatever is done atomic, the work will continue till October, then put a lot of cider cloves to then put a lot of cider cloves to open the lock P Shirdi strong also, open the lock P Shirdi strong also, leaving the last one, leaving the last one, days should be added. days should be added. days should be added. lock, now whatever we seal here, we will do it, here we have sealed it, we will take the job, hence total 10 to 12 times, I must do it, if you want a little complicated, then now we accept it. First of all, what have we told you that the number of tiles, I said, take out I have already I have already said that he will send a value unnecessarily, so he will do it, so let's cover this also in the bracket, it was a mistake, but if I sleep, was a mistake, but if I sleep, then it is not in favor, then it is not in favor, now one thing, there is some black admission in it, now one thing, there is some black admission in it, due to which he is doing it like this. due to which he is doing it like this. Okay Okay that Abhilash Lilly return kya hoga hoga that Abhilash Lilly return kya hoga hoga return karna hoga ka ya return karna hoga ka ya ko vijay type meaning in return karna ko vijay type meaning in return karna before that log me don't clock off kya log off but it's a that divided by match date the divided by match date the lord of the lord of the pain on PAP pain on PAP That what will be done with all the results that will come, That what will be done with all the results that will come, its McDermott serial that its McDermott serial that Chief Lota is fine and in the end convert it Chief Lota is fine and in the end convert it into interior because you will get double the into interior because you will get double the value photo shooting rally, because of this it is time to symbol that I am a doctor who is going to get sex. Hai Fix If you liked the video then please comment in the comment section and do not forget to subscribe the channel and for this question I am going to release this pure video on Saturday on Saturday One More Time So Let's You Are Left after one month Left after one month Left after one month hydration ok sakhri hai karke hydration ok sakhri hai karke in next video thank you to | 2024-03-22 14:48:39 | 458 | Leetcode 458. Poor Pigs |
|
K9zRM-ttaDs | hey what's up guys in this video i'm going to go through this uh going to go through this uh liquor 289 game of life liquor 289 game of life so um yeah there's a lot of wording in so um yeah there's a lot of wording in here here but let's dive into the example directly but let's dive into the example directly so so uh for each sub this is uh the cells uh for each sub this is uh the cells uh so zero means that that cell and uh so zero means that that cell and one means uh a living cell one means uh a living cell and we need to look at the surrounding and we need to look at the surrounding cell cell for example by surrounding is really for example by surrounding is really means that means that for example this cell the surrounding for example this cell the surrounding cell would be this one this one this one cell would be this one this one this one this one this one this one this one and this one this one this one this one and this one so this one so it has eight surrounding cells it has eight surrounding cells and then look at the stylus of and then look at the stylus of surrounding cell to determine the surrounding cell to determine the whether it's gonna be living whether it's gonna be living or that in the next next stage or that in the next next stage and for example for this cell there's and for example for this cell there's there are only three there are only three neighbors for this guy he has one neighbors for this guy he has one two three four five five neighbors two three four five five neighbors so for that one as we talked about it so for that one as we talked about it has eight has eight neighbors um and there's a lot of neighbors um and there's a lot of wording here but essentially what it's wording here but essentially what it's saying saying is uh if we sell is uh if we sell that was a one so that was leaving that was a one so that was leaving before before if the neighbor all the neighbors if the neighbor all the neighbors um he has two or three um he has two or three neighbors that are leaving neighbors that are leaving it will he will leave in the next stage it will he will leave in the next stage otherwise he will die so otherwise he will die so let's look at the example uh for example let's look at the example uh for example for this guy over here it has um for this guy over here it has um one two three yes one two three yes three leaving neighbors in on in this three leaving neighbors in on in this stage stage and the next stage you're gonna you're and the next stage you're gonna you're gonna be leaving you're gonna be alive gonna be leaving you're gonna be alive however uh let me look at a counter however uh let me look at a counter example oh example oh for example this guy he has only one for example this guy he has only one living neighbor living neighbor in the next stage he's gonna be dead in the next stage he's gonna be dead because he's on his only one living because he's on his only one living neighbor neighbor it does not have two it does not have it does not have two it does not have three living neighbor that's why in the three living neighbor that's why in the next stage next stage it died and for the cell it died and for the cell currently is that because you will be currently is that because you will be alive we have if we has alive we have if we has three um living three um living neighbors so for example otherwise you neighbors so for example otherwise you die die so for example um so for example um let me put this wording over here so for let me put this wording over here so for example for example for uh for this guy over here it has three uh for this guy over here it has three this it has to be exactly three living this it has to be exactly three living neighbors neighbors so he has exactly three main layers so he has exactly three main layers in the next stage it is a life in the next stage it is a life and for this guy over here and for this guy over here he has only two living neighbors in the he has only two living neighbors in the next stage next stage instead is continue to be that instead is continue to be that so we need to avoid a function to so we need to avoid a function to determine the cell in the next stage is determine the cell in the next stage is going to be leaving going to be leaving for that and we need to do this one for that and we need to do this one in place meaning that we have we will be constantly overriding the board and uh and the status of the um those labels could be it has to be based on the uh the status and time zero is not the status in time one in the next it's not in the sudden in the next stage has to be the status in the current stage so that will be the challenge because we'll be overriding the board so the step so the information that's showing the board will be changing right so and that's a challenge and uh and this is showing the same thing whether we just discussed um and yeah so that's one of the one follow-up question one of the yeah the second one is um let me read it for you uh we represent the board using a 2d array in principle the board is infinite and well which could cause problem when the active area encroaches upon the board if the broader of the way for example our living cell you have reached the border and how would you address this problem and we will talk about that after we solve this recording challenge and this question was popular as you can see it was asked by amazon drawbars open door and all the other big names also google and apple and first we need to actually have a and first we need to actually have a direction list direction list because it has you can go to affordable because it has you can go to affordable direct direct sorry not for eight different directions sorry not for eight different directions um you can go to here here um you can go to here here here and here and go to the corner here here and here and go to the corner here here here here so yeah totally entirely here here here so yeah totally entirely eight directions so we have a direction list that's all the possible direction that we can look around when we find the neighbors and with number one rows number columns and this is the um status tracking that we can do it in place on the board um this will come into handy because we have to do everything in place for example if the cell and at this current start and the current stage is leaving and they continue to be leaving so it's zero means is dead and one one means our life right so in the current stage is leaving and the next stage is still b to be alive and then we have a one one and if currently is leaving in the next stage is going to be that so you have a one and zero so currently is that and the next stage is going to be leaving with zero and one and zeros and zero will probably guess that already it means that is that at the current stage and next stage is continue to be dead so um as you can see we have the top four two for loops um nested follow-ups in here uh let me walk you through uh the first one first and then we are going to the next one which is a lot easier to understand so uh we have a double for loops to look through each of the cells on the board and then for each of the sales we have the count lives so we count how many neighbors surrounding neighbors they are leaving and for uh the row move and column move in all the directions list and the neighbor that we're looking at would be the current row plus the row move and the current column plus the current move and then that will be a specific neighbor that we're looking at the coordinate of the neighbor that we're looking at and if the neighbor is within the boundary right minus one because we are talking about index if the the row the net the row of the neighbor and the column of the neighbor as they are within the boundary and then we can look into their value if their value are either one means that we have not yet override a board or a one one or one zero basically we only interested in the first one because we only need the current status of the cell right so either one of these three then we can increase the current lives by one so basically we this chunk code is basically uh this chunk of code sorry we basically look around for the neighbors if the neighbors are within the boundary if the current status they are leaving we increase the count life by one and uh and then now we have some two cases in here and for the first case for the first case if the cell is leaving is um is alive currently is alive and you will continue to be living it continue to be alive if there are two or three living neighbors so this is exactly doing that right so if uh the cell is currently alive if the surrounding neighbors has against two or three uh surrounding neighbors they are live currently and we can override it to be one and one because it's currently living and continue to be alive otherwise if if the surrounding neighbors they don't have two or three of them are leaving they will die in the next stage and then they will move from and that's one case currently um and that's one case currently um the cell that we're looking at is alive the cell that we're looking at is alive or if the cell we're looking at is or if the cell we're looking at is that in that case if there are three that in that case if there are three names surrounding neighbors they are names surrounding neighbors they are currently alive currently alive in the next stage the cell will be alive in the next stage the cell will be alive and how can we do that because currently and how can we do that because currently we can have the common life we can have the common life is equal to three and it will move from is equal to three and it will move from zero zero to one it moves from the dead to one it moves from the dead status to one the living status status to one the living status the alive status otherwise you continue the alive status otherwise you continue to be that to be that and after the after that we often we and after the after that we often we overwritten the entire board overwritten the entire board by having like one one string on one by having like one one string on one serial as a string serial as a string zero one or zero zero everywhere on the zero one or zero zero everywhere on the board and then we can translate board and then we can translate basically we only need that started in basically we only need that started in the next stage the next stage so that's why we only need the second so that's why we only need the second number over here and that's exactly how number over here and that's exactly how we can do that we can do that so we look at the second component and so we look at the second component and then convert it back to the integer then convert it back to the integer so this is that so this is that and as you can see uh it's pretty and as you can see uh it's pretty efficient efficient both on the speed and also on the memory both on the speed and also on the memory and memory is a key point in this and memory is a key point in this exercise exercise uh speed as you can see is big o of m uh speed as you can see is big o of m times times n um even though we have 12 n um even though we have 12 2 for loops but we just um 2 for loops but we just um each of the forum takes big over n times each of the forum takes big over n times n and another one takes the same n and another one takes the same time so and it's basically m times n time so and it's basically m times n plus m times n so essentially still m plus m times n so essentially still m times n times n and then we're doing some if statements and then we're doing some if statements in between and they are only taking big in between and they are only taking big o o one so that one so that addresses the first question and the addresses the first question and the second question we second question we have was uh what about the board is have was uh what about the board is infinite i couldn't come up with a infinite i couldn't come up with a better solution than the official one better solution than the official one so i'm gonna read it for you and so and so i'm gonna read it for you and so and uh so far we have only adjusted one of uh so far we have only adjusted one of the four the four yes the following questions for this yes the following questions for this problem statement problem statement we saw how to perform the simulation we saw how to perform the simulation according to the four rules in place according to the four rules in place for example in other words without using for example in other words without using any additional memory any additional memory the problem statement also mentions the problem statement also mentions another follow-up statement another follow-up statement where it says which is a little bit where it says which is a little bit open-minded open-minded open-ended sorry we will look at open-ended sorry we will look at two possible solutions to the adjustment two possible solutions to the adjustment essentially the second follow-up essentially the second follow-up answer has to adjust the scalability answer has to adjust the scalability aspect of the problem what would aspect of the problem what would happen if the board is infinitely large happen if the board is infinitely large can we still use the same solution that can we still use the same solution that we saw earlier we saw earlier or is there something else we can have or is there something else we can have we will have to do uh differently if the we will have to do uh differently if the board becomes infinitely large board becomes infinitely large there are multiple problems our current there are multiple problems our current solution could run into solution could run into and that's the other problems first one and that's the other problems first one is it could be computationally is it could be computationally impossible impossible to iterate a matrix that's really large to iterate a matrix that's really large it would not be possible to store that it would not be possible to store that big of a matrix entirely in big of a matrix entirely in the memory we have a huge memory the memory we have a huge memory capacity these days for example capacity these days for example let's say it's 100 gigabytes however it let's say it's 100 gigabytes however it still still wouldn't be large enough to store such a wouldn't be large enough to store such a large matrix in the memory large matrix in the memory and thirdly we will be wasting a lot of and thirdly we will be wasting a lot of space if such a space if such a if such a huge board only contains a if such a huge board only contains a a few living cells and the rest them are a few living cells and the rest them are all all that so the rest so only a few ones that so the rest so only a few ones and the rest are all zeros in that case and the rest are all zeros in that case we have a extremely sparse matrix it we have a extremely sparse matrix it won't won't make sense to save a board such as a make sense to save a board such as a matrix matrix coenco matrix this is very sparse coenco matrix this is very sparse because it's only only a few area because it's only only a few area contains contains um useful information this is what it's um useful information this is what it's saying saying such an open-ended problem uh better such an open-ended problem uh better should to design should to design discussion during programming interviews discussion during programming interviews and it is a good and it is a good habit to take into consideration the habit to take into consideration the scalability aspect of the problem since scalability aspect of the problem since your interviewer might be interested your interviewer might be interested in talking about such problems the in talking about such problems the discussion section already does a great discussion section already does a great job job at addressing this uh specific portion at addressing this uh specific portion problem we will briefly go to go over problem we will briefly go to go over two different two different solutions that have been provided in the solutions that have been provided in the discussion section as discussion section as they broadly cover two main scenarios of they broadly cover two main scenarios of the problem the problem so one aspect of the problem is that so one aspect of the problem is that just by just by this gentleman over here so as mentioned this gentleman over here so as mentioned before before it is quite possible that we have a it is quite possible that we have a gigantic gigantic matrix with a very few living cells in matrix with a very few living cells in that case that case it will be not smart to save the entire it will be not smart to save the entire or at as it is so if we have extremely or at as it is so if we have extremely sparse matrix it would make much more sparse matrix it would make much more sense to actually just save the location sense to actually just save the location of which only living cells are located of which only living cells are located and then apply the four rules according and then apply the four rules according to accordingly using only the living to accordingly using only the living cells cells and there's some code in here uh that's and there's some code in here uh that's showing how to do that however showing how to do that however essentially what it's saying is we can essentially what it's saying is we can uh obtain only the living cells from the uh obtain only the living cells from the entire board and then apply entire board and then apply the different rules only the own using the different rules only the own using only the leaving cells and finally only the leaving cells and finally update the board in place update the board in place the only problem with this solution the only problem with this solution would be the entire board cannot be would be the entire board cannot be fitted fitted in the memory if that's indeed the case in the memory if that's indeed the case then we would have to approach problem then we would have to approach problem in a different way in a different way for that scenario we assume that the for that scenario we assume that the contents of the matrix contents of the matrix are stored in the file one row at a time in order for us to update a particular cell we only have to look at each eight adjacent neighbors which essentially lie in a row above or below it so for updating the cell of a row we just need to either row above and the row below and thus we read one row at a time from the file and and at max we have to use three rows in the memory we'll keep discarding rows that are proceed are processed and then we'll keep reading new rows from the file one at a and then another person's solution and then another person's solution resolved um resolved um around this idea and then there's some around this idea and then there's some discussion about this coding discussion about this coding in in the discussion board it it is in in the discussion board it it is important to know that there is no important to know that there is no single solution for someone's problem single solution for someone's problem everybody might have a different everybody might have a different viewpoint viewpoint for addressing the scalability aspect of for addressing the scalability aspect of a solution a solution and these two solutions just just adjust and these two solutions just just adjust some basic problem some basic problem with handling matrix based problem scale with handling matrix based problem scale so yeah this is so much how i would so yeah this is so much how i would approach approach this problem and also some other people this problem and also some other people approach the scalability of this problem approach the scalability of this problem i hope you like it if you do please hit i hope you like it if you do please hit the like button the like button and consider subscribing to the channel and consider subscribing to the channel hopefully hopefully i will see you in the next video thank i will see you in the next video thank you for watching | 2024-03-22 14:20:19 | 289 | Leetcode 289. Game of Life | Python | FAANG Coding | Matrix In Place | Simulation | Scalability |
|
_vVu8JLQt2E | hey hey everybody this is Larry this is day day four of the Leo daily challenge just four of the Leo daily challenge just want to make sure because I got it wrong want to make sure because I got it wrong yesterday uh hit the like button hit the yesterday uh hit the like button hit the Subscribe button join me on Discord let Subscribe button join me on Discord let me know what you think about today's F me know what you think about today's F and let me know what you think about and let me know what you think about yeah these intros in general I'm here yeah these intros in general I'm here again still again still in in kagoshima I always have trouble kagoshima I always have trouble remembering where I am but I've been in remembering where I am but I've been in different cities every other day yeah uh different cities every other day yeah uh here's the here's the problem hey hey uh yeah thanks the other problem hey hey uh yeah thanks the other older Larry or younger I guess younger older Larry or younger I guess younger Larry from the past it's always a Larry from the past it's always a younger Larry when you're looking at me younger Larry when you're looking at me now I am older in real now I am older in real time and I got to stop like I don't know time and I got to stop like I don't know did I not submit yesterday why is that uh sorry huh I guess I have to redeem a Time huh I guess I have to redeem a Time ticket sorry friends give me a ticket sorry friends give me a second uh second uh huh whoops did I not submit I I have to huh whoops did I not submit I I have to look at it again but oh well what a silly I mean we had a video okay I just click on submit how does okay I just click on submit how does this this work yes did I huh man that is wild H I have to remember this is the second time I done the prom and forget to submit I mean I don't know maybe on my profile there'll be a streak thing but I don't care about a streak per se but but at least I don't care if I didn't do it but if I did do it then you know I wouldn't be able to do it anyway sorry friends uh part of the fun part of live is that you could see Larry being silly in other ways uh but yeah let's take a look at today's P 153 last moment before or ends for our prank okay so R prank of length end um I I don't know if this is well known by now but but I I've seen this a few times and and I know it so I don't know uh but the idea here is that you know the okay the first thing you might consider to do is simulation but n is 10 to the 4th which is like 10,000 and 10,000 if you do like n square e things because they always or at the worst case they're going to collide like half of them on the left half on the right or something like this and then Collide right um the way to visualize this is uh and I'm going to bring up the drawing pad for a second uh okay there we go is that uh and I probably have done this visualization before but you can think about this as a number line or whatever uh or the line that they give you and then actually let me redraw this maybe you could think about this as a the line that they give you but then now you can add an extra AIS of uh time right so now you know going up is time right let me do it this way so then now you say let's say we have a red one that goes from left to right what does that mean right so that means that the first um can you see that dot it's a little bit small but uh let let draw a s instead so let's say we we start here I'm drawing with the touchpad so it's a little bit weird but you know or you know it's just ugly right and then the next one if it moves to the right it be here right and so forth so then here you could draw this line as right something like that and it it moves One Step per second and right uh of course the only difference is or the only thing that's tricky is that they also oh whoops uh is that they're also ones moving to the left and they Collide right so let's say you have something like this and the blue ones are going to the left side and you know same idea right and you do something like okay I messed up on the drawing and connecting the dots okay there we go right and then of course here what you actually want to do in theory is that because now they Collide um at the same spot uh then now you can think of it as this this boo going to the right and then you know what this is what they want you to think right but if you think about it you know uh if you kind of and I kind of maybe hint at it a little bit already right which is that okay so this is what happens if you kind of think about it in a timeline kind of thing but because all the ants don't matter or or ants matter but no uh because each end is um not differentiable from the other one uh meaning that they are uh in a way funable man I'm talking about these ANS like economic things but um but they just like you know there's no an a with a different characteristic and they're all just the same right so that means that in a way you can think about them as oops you can think about it like this as in you know you you could just like let's say uh n the red n is one and the BL n is two um you can just swap the IDS afterwards right so when they Collide you may say that the N1 goes to the right and N2 goes to the left but or or the other way around maybe I don't I don't know this mirror thing is always hard um you can think about them as just passing through each other and with that logic that means that you get to um skip all this simulation and just see kind of things right um so that's basically the idea by this form and once you realize that idea a lot of things become a lot easier and also if you look at Solutions prior is just like way short as a result but okay let's actually look at the right uh yeah so left oh this is just an right uh yeah so left oh this is just an array of things okay do we even have to array of things okay do we even have to sort no maybe oh I I didn't even realize what the problem was asking is the last end right as a result of our thingy uh and swapping them that means that you have to just get to see which one is closer to the left or closer to the right the edge and then going off right so that means that for X in left okay so let's just say four this is equal to zero for you know whatever uh what is so this four what does that mean right it's going oh sorry it's going to the left okay so that means that everything on the left it takes X seconds to cost right so that means that actually this is just max of left then to the right it is the smallest so then to the right it is the smallest so Min of right and then that takes n minus Min of right and then that takes n minus Min of right right so that means that Min of right right so that means that Forest is equal to Max of this and you Forest is equal to Max of this and you can actually can actually even even right oh right oh well whatever that's why this way and well whatever that's why this way and then obviously you can actually do this then obviously you can actually do this is a oneliner uh and I'll try to oh is is a oneliner uh and I'll try to oh is there an Mt sequence oh okay uh you there an Mt sequence oh okay uh you could default this as zero I think I could default this as zero I think I don't know it's uh it's a this is a list a this is a list oh oh oh oh oh oh oh no this is uh I think that's what I I oh no this is uh I think that's what I I was trying to do someone like was trying to do someone like this oh yeah okay cuz I wasn't sure it this oh yeah okay cuz I wasn't sure it was a positional argument I always was a positional argument I always forget and yeah and this time we forget and yeah and this time we actually quick submit and will you get actually quick submit and will you get it wrong why tell me why wait what am I it wrong why tell me why wait what am I am I misunderstanding am I misunderstanding this why is this not a this why is this not a thousand left oh oh oh this default as left oh oh oh this default as well okay fine uh that's why I guess we well okay fine uh that's why I guess we trying to be too smart on this one uh trying to be too smart on this one uh first time I didn't even get it well cuz first time I didn't even get it well cuz I would have just done yeah the actual I would have just done yeah the actual Loops but this time I um I tried to be Loops but this time I um I tried to be too cever and I set the default well too cever and I set the default well um but yeah um but yeah uh that's I gu we trying to be slick but uh that's I gu we trying to be slick but uh no uh but that's pretty much it uh no uh but that's pretty much it obviously this is going to be linear oh obviously this is going to be linear oh is this blocking the screen a little bit is this blocking the screen a little bit uh I mean you see the definition I think uh I mean you see the definition I think that's fine let me my big head okay that's fine let me my big head okay there you there you go all right uh but there you there you go all right uh but yeah linear time constant space that's yeah linear time constant space that's all I have for this one let me know what all I have for this one let me know what you think and you could see my outro you think and you could see my outro now that's all I have for today let me now that's all I have for today let me know what you think stay good stay know what you think stay good stay healthy to your mental health I'll see healthy to your mental health I'll see you later take care bye-bye and today you later take care bye-bye and today I'm going to end the day with these I'm going to end the day with these grape a bag of grape ice cream it tastes grape a bag of grape ice cream it tastes pretty good tastes like what you expect pretty good tastes like what you expect grape looks like a grape and yeah tast tastes great I got nothing all | 2024-03-21 11:07:15 | 1,503 | 1503. Last Moment Before All Ants Fall Out of a Plank - Day 4/30 Leetcode November Challenge |
|
KFzCRbpUcqM | number of ways to form a Target string given a dictionary dictionary means just given a dictionary dictionary means just some words so let's quickly jump on to some words so let's quickly jump on to the problem statement and the problem statement and it's pretty big so yeah I have just it's pretty big so yeah I have just broken down into actual components so broken down into actual components so yeah let's see it's firstly it's given yeah let's see it's firstly it's given that okay you are given a string that okay you are given a string a list of strings of same length and a list of strings of same length and that list of strings will be inside that list of strings will be inside worlds which means words will have a worlds which means words will have a list of strings of same lengths same list of strings of same lengths same length and a string called as a Target length and a string called as a Target string which I need to make your task is string which I need to make your task is to form the target to form the target which I have to make using the words in which I have to make using the words in this this all these strings under the following all these strings under the following rules what are the rules right rules what are the rules right the target it because it needs to be the target it because it needs to be formed right so it should be formed from formed right so it should be formed from left to right left to right which means I can't form see I which means I can't form see I ultimately want to form a Target but it ultimately want to form a Target but it should be formed by picking the elements should be formed by picking the elements from left to right cool to form the ith from left to right cool to form the ith character zeroth index of the target character zeroth index of the target let's see to form the ith character Zero let's see to form the ith character Zero index of the target you choose the kth index of the target you choose the kth character of the jth string inwards so character of the jth string inwards so many variables but still if the target many variables but still if the target what I'll show you if I want to make what I'll show you if I want to make this this then it should be same of some jth then it should be same of some jth string in this word kth character it string in this word kth character it means that okay the character should be means that okay the character should be same that's all once you use the kth same that's all once you use the kth character which means this character character which means this character then what happens is of the chair strain then what happens is of the chair strain of the any string here we choose of this of the any string here we choose of this particular string although you can particular string although you can choose any string but if you choose this choose any string but if you choose this character character then what happens is you no longer can then what happens is you no longer can use the X character of any string in the use the X character of any string in the words where X is less than equal to K words where X is less than equal to K which means any character less than this which means any character less than this thing whole thing because it is already thing whole thing because it is already you have chosen so remaining is this you have chosen so remaining is this whole thing right so for the next whole thing right so for the next upcoming element you cannot choose upcoming element you cannot choose anything from this white part you can anything from this white part you can only choose from the next part it is only choose from the next part it is what you have to do from left to a right what you have to do from left to a right cool cool that it is saying that okay all these that it is saying that okay all these all these characters becomes unusable all these characters becomes unusable last thing was that one thing was before last thing was that one thing was before this also that repeat the process until this also that repeat the process until you form the string Target that okay I you form the string Target that okay I choose some that I choose next I choose choose some that I choose next I choose next so I have to just form the target I next so I have to just form the target I have to do such steps notice that have to do such steps notice that notice that you can use multiple notice that you can use multiple characters from the same string which characters from the same string which means if I want to make ABA I choose a means if I want to make ABA I choose a from the string let's say 1 then I from the string let's say 1 then I choose the B from strain 2 then again I choose the B from strain 2 then again I can choose the string the character a can choose the string the character a from the string one itself which means I from the string one itself which means I can choose the same character again and can choose the same character again and again provided it should come after again provided it should come after which means if the a would have been which means if the a would have been here I could not have chosen it it needs here I could not have chosen it it needs to come after this whole thing to come after this whole thing cool last year aim is to actually return cool last year aim is to actually return the number of ways to form the target the number of ways to form the target from the words firstly if you just read from the words firstly if you just read this thing then only you should actually this thing then only you should actually be able to think of what things should be able to think of what things should be applied here but still I'll not name be applied here but still I'll not name that thing I'll just show you how you that thing I'll just show you how you actually reach to that thing since the actually reach to that thing since the answer may be very large so for sure answer may be very large so for sure very standard thing if the answer is very standard thing if the answer is large you return the modulo money nine large you return the modulo money nine plus seven plus seven cool now let's see the example to cool now let's see the example to actually figure out okay actually figure out okay um what's happening in the background if um what's happening in the background if I have these three words it's the same I have these three words it's the same word which I took in the above example word which I took in the above example itself same exactly same I will take the itself same exactly same I will take the same example in the whole problem Target same example in the whole problem Target is Aba which means that okay is Aba which means that okay what all can be possible firstly I just what all can be possible firstly I just show okay how what all can be possible show okay how what all can be possible then I'll show how it is being made then I'll show how it is being made firstly to make this ABA I can just grab firstly to make this ABA I can just grab an a from here B from string two a again an a from here B from string two a again from string one a from here B now c b from string one a from here B now c b earlier I took this one now I can take earlier I took this one now I can take this one also so it's same okay I think this one also so it's same okay I think here then again I get grab the a then here then again I get grab the a then one option is a b a again is a b a a b a one option is a b a again is a b a a b a a b a so these string are these six a b a so these string are these six ways can be possible to make this target ways can be possible to make this target out of these three strings out of these three strings provided you always saw whenever I had provided you always saw whenever I had to choose next element I just make sure to choose next element I just make sure that I'm choosing after this I can't that I'm choosing after this I can't choose anything before if I'm doing a B choose anything before if I'm doing a B I choose B for the next character I have I choose B for the next character I have to choose after this whole line to choose after this whole line now see what option we have now see what option we have you saw what option we have we had to you saw what option we have we had to choose a Target ABA so one thing for choose a Target ABA so one thing for sure that okay I start let's take this sure that okay I start let's take this example only I start with a example only I start with a I start with a because I want to make a I start with a because I want to make a Aba I start with a then my next option Aba I start with a then my next option to choose is B so I just go choose B to choose is B so I just go choose B another option to choose B is next just another option to choose B is next just here because I just have one condition here because I just have one condition that okay after this I need to choose so that okay after this I need to choose so whatever I can choose I can choose after whatever I can choose I can choose after that I choose B B has two options from that I choose B B has two options from this a I have b as two options then from this a I have b as two options then from this B from this B right here this be this B from this B right here this be right here for a I have two options this right here for a I have two options this here and here from this B right here I here and here from this B right here I have two options have two options right so what's happening wait let me right so what's happening wait let me erase this whole part and here and here erase this whole part and here and here from this B2 let's say it is B3 B2 B3 from this B2 let's say it is B3 B2 B3 from B2 we have two a's the a right here from B2 we have two a's the a right here and the a right here from B3 also we and the a right here from B3 also we have two ways a right here and a right have two ways a right here and a right here here which is A2 and A3 which is A2 and A3 and also in the starting you started and also in the starting you started from here right what if you had started from here right what if you had started from from um let's say let's say let's say let's um let's say let's say let's say let's say this a right here the bottom a the say this a right here the bottom a the bottom if you are started then you have bottom if you are started then you have next option is 1B next option is 1B for this 1B which is actually a B3 you for this 1B which is actually a B3 you have same options again two A's this a have same options again two A's this a and this a right here which is A2 and this a right here which is A2 which is a and again a which is a and again a right it is for the top it is for the right it is for the top it is for the last which means top last top last you last which means top last top last you saw what happened for this B3 top last saw what happened for this B3 top last for this B3 you are again finding you for this B3 you are again finding you will start with just one a then again will start with just one a then again for this B2 for this B2 you go B3 you go then for B3 for this you go B3 you go then for B3 for this next a also your B3 part which means next a also your B3 part which means this next sub problem part is repeating you know it's a recursion you start because you wanted to make the Target string which is a b a but you just start choosing those characters you just started with that character next you choose B you have two options next to choose a you have again like for this B two options for this B two options which is actually Four options and here we have two options so in total here you have four options here you have two options in total the options become six that's the sixth answer but you saw what happened while choosing this B you again have to think of okay let's think of choosing next is same problem occurs here if you take this a right here one thing for sure you know okay um when I'm trying to choose problem is being repeated for sure it's a DP problem I need to optimize it by ADP before that let's see how you can optimize this which means what part of problem is repeating that okay you know okay v a sub problem which means that this particular part let's say ba will come it will repeat so I can just grab okay number of ways to grab ba or I can do vice versa also maybe a b and then I can just look for again next a but let's see actually how in this problem we are thinking what is happening you saw what happened that I just showed you that okay problems are repeating here you can easily see that when I have grabbed these a B's then again I have to think I have this next a incoming next a incoming next a incoming next a incoming which means if I have the number of ways okay I can just grab this a b when is the next incoming because ultimately my condition is that anything after this a anything after this anything after this so if I just know the number of ways to grab a B from here up till this point up till this point up till this point and then again I can number of A's which occur after it I'll just multiply the number of ways to grab this A B's into a you didn't get it or you get it it was exactly the same how I was making from a I had two options let's consider I had made EB now I need to find the number of options to get just a here I was just saying okay from a I had two options for B then for these B I have again two options so let's consider okay to get a B I have three options now what are the number of ways to actually get the final a let's see with this example so what I can do is I can actually make my DP store number of ways to form the target J First characters which means number of ways I can grab a B ultimately I want to make a a b a right a b a let's take a number of ways to just grab a B Because see ultimately my main aim is to find the condition which I have to put that okay I can find the answer for my main strain so let's grab the answer for the small string small string is this main string is this if I have the answer for the small string so I should be able to find out the answer for the whole string it is my a ultimately so I just had a bigger problem I just thought okay if anyhow I just got the answer for that small problem how I will get the answer for my bigger problem which means if I had the number of ways I can get this a b so Arun please give me the number of ways I can get abs here you can easily see number of ways you can grab a B is actually three as I showed you a b because it is one a b here one a b here and one a b here so number of ways to grab a B's are actually three now after that I just okay after this after this after this I assumed to think okay next incoming thing is a number of ways to grab a B is three next incoming thing is a how many A's can be there there are two A's which can be there so for these three a B's I can have two a's you saw what's happening which means three is three a B's and two A's so in total I have six ways to have a Aba a b a in total six ways to grab a Aba a a b a a b a a b a a b a a b a a b a that is the reason if I just get to know the answer for the small sub problem which is number of ways to grab a B I can just count the number of A's here right now and I can just grab a kick count of these number of A's I have it is my DP of let's say J then it is the count so I'll just grab okay what is the actual number of ways to form the count of first J characters that is pretty much it in this DP firstly we just got to know okay the problem is being repeating so it's a DP problem for DP problem we just need to know uh the DP State and the DP condition the DP State let's think but for that let's see how we'll get the DP condition we just assume okay let's assume that for smaller sub problem we have the answer so how for the whole problem we'll get the answer if first smaller is a problem I have the answer for number of ways for a b number of ways to get a B let's say we have the answer and we get the next incoming a so how we will just grab the total number of ways to grab this ABA we just get to know by this condition that I will just multiply number of ways to get a B into the frequency which means the count of number of ways I just get the answer which means ultimately what happened was the DP state will actually become something like this number of ways of getting the first J characters of the target first J characters I am actually analyzing the first G characters of the target at a particular State and again finding out the result for that particular J characters at point of time I hope that you guys accounted which means that the DP of first J plus 1 characters is nothing but the DP of first J characters into the count of this incoming character which is after this index existing first J characters and then new JPS uh new deck the count of that particular character which is incoming in this condition let's see the code I'll explain actually how the code beautiful is written see you just you just got to know this DP condition that how actually we are finding the number of new new number of ways which means earlier for a B I knew I know I'm repeating that but if you have not understood it you can just skip it uh number of ways we get a b and then after that we have this a and then we can write the answer let's see the code pretty quickly it's easy not that but yeah medium firstly I just grab okay n m mod and all that stuff DP is actually what I need to make my target right so I'm just I have a b a so I just said for this at every state of those ja characters first G characters of what of Target so for sure my DB will have size M plus 1 because I'm just saying for the first character let's say it's a so it is DP of 1 which means one character if it is a b it is T P of 2 uh DP of 2 but if it is a b a it is DP of 3 it is just saying okay I am analyzing first G characters it is only analyzing one character only analyzing two characters first two characters because for sure we are starting from left to right analyzing first three characters of this particular string Target cool uh then we will just grab for sure I marked my DP of 0 as 1 why 1 it's because you know I am analyzing my DP of one so for sure my result will start from DP of 1 itself and not from 0 because my DP State actually stores for first J characters so for this DP of one as I showed you in the condition itself in the condition itself if it is 1 so for short J is 0 if J is 0 so I need to multiply by some count so initially if this DP of 0 if this DP it will be a DP of 0 if it is actually a zero then the count whatsoever it is there it will just actually go to 0 because 0 into something is 0 that's the reason I just want okay whatsoever count is there it should come that's the reason I should I just put one in case of DPF DP of 0. cool no worries then I have the count as I said at a particular point of time I just need okay what is the count of all the A's here what is the count of all the B's here because when I have analyzed this particular index I then when I am at this index I I need to know okay I just know okay what is the DP of J here but I also need to know okay if the incoming character I need to analyze is the a then what is the count of it you can also iterate on this particular whole string but it's useless you can just have the count of a that you can know okay A B number of ways are let's say three count of a is actually two right now right now right here so number of ways to grab a B A is nothing but 3 into 2 which is 6 if at this point of time number of ways to grab number of ways to have a b is 3 number of ways to have B after that is 1 because it's just one because the count of B is one so number of ways to grab a B is nothing but three into one it's the reason I just grab the count at every index at every index whatsoever alphabet character is there I just had and kept its frequency so that I can use the same thing while analyzing my DP because in the DPS itself I showed you I need to get the count of this incoming character of what of Target cool no worries then for sure uh my actual DP uh condition starts that okay I'll just go on from left to right it was second version from left to right which means increasing the size of this sub problem I have this a uh C what was the condition is c yeah a c c a b b b b b c a c a so I'm just going from left right okay I just analyzed first only this then I analyze only this then I analyze only this then I'll analyze only this it is how I'm and I'm just increasing my portion part which I need to analyze cool uh after that you will see I now okay my I'm just iterating on my words but what I have to think of is of my DP condition DP of what DP off as I said I need to check for the first check check characters offer of Target that's the reason I have to iterate on my Target also for that particular reason because I need to get my dpfj but you will see that I iterated backwards rather than forwards he will ask why I did it from M minus 1 because I need to trade on my target itself for every small sub problem you will see I just iterated from backwards rather than forwards is the reason because as I told you if I am standing here for this particular eye then I will just check Okay add this I I just check for this particular let's say a so I am actually analyzing my ap of 3 because it does the first three character which I'm analyzing right now for which I would need my DP of to which means the previous result of a b but that previous result of a b should be as of before not this I as of before which means when I would have been here it should have been in the last Loop in the last iteration of I whatsoever DP of 2 would have been there it should be coming which means as of I minus 1 if I'm standing at I so as of I minus 1 I want the DP of 2. thus if I just iterate on from 0 to 3 which means from 0 to M minus 1 then my DP of 2 will actually update as of I but I want my DP of 2 for my DP of 3 as of I minus 1 I want this as of I minus 1 not as of I because I want that when I am actually seeing this particular element right here I should only consider the element which means a b part if I'm c a right here I have to consider the a b part as of before as I showed you this condition it was marked as of before we need to analyze that's the reason I just iterated it backwards rather than forwards I hope that you guys got it and it is the exact same deep condition which we actually saw above that our DP of J plus 1 is nothing but DB of J into the count of that incoming character so it is the same way it is gone yeah DP of J DP of J plus 1 is nothing but DB of J into the count of that incoming character and it is just mod and I as I just added so I have to do a mod again because so that it doesn't overflow ultimately I have to return the DP of M why dpfm because it is the final a b A's C we need to analyze the first J characters so first three characters which means the string size is itself three which is M string size itself M Target is M so I need to analyze the first n characters and it is done so I have to return a DP of M that's pretty much it I know it had been a pretty complex problem but I hope that I was able to make it understand now time capacity is pretty simple as you look at the code we'll just get to know that we are just iterating on those words and for every word I'm just going on to every word length so it is if number of words are W word length are n so it is uh W into n in this particular DP condition loop I am just going on to that word length and for that I'm going on to every Target from reverse so it is M which is n into m that's the condition it is whole n into W plus n into m space is nothing but we are using a DP of size Star Gate which is M and a vector of count which is actually n into 26 which is constant so it is nothing but n into n plus M all the codes for C plus Java python is down below I hope that you guys got it that how I thought okay anyway I just get the small part I just get the number of ways to get a B now I know okay number of A's whatever are there I just multiply the number of ways to get the ABA now I have to think okay how I will actually find the number of ways of that a b so basically I have just I just assumed I have the answer for the smallest problem that I just know okay what condition I should apply okay when I know the condition then I actually get to know okay what DT State I should put on that actually because see although while explaining just people just explain okay you just take a DP State write this but actually how you think of is what is required to actually make your DP State as DP of J and not a UDP or something else by just iterating if you just think okay get the biggest sub problem get the biggest sub problem but if you like you will know what is but if you like you will know what is required to have that small problem required to have that small problem anyways I just need to have what is the anyways I just need to have what is the number of ways to get the number of ways to get the SE first two characters SE first two characters number of ways then if I have a I just number of ways then if I have a I just get okay first number of ways to get a b get okay first number of ways to get a b a a I hope that you guys got it and then I hope that you guys got it and then goodbye take care | 2024-03-19 15:47:38 | 1,639 | Number of Ways to Form a Target String Given a Dictionary || Dynamic Programming || C++/Java/Python |
|
xusDw5IVo84 | represent in the Daily Challenge constructor and if false if false if lift if false then the value? We must if lift if false then the value? We must not be understanding this. Let's go ahead. There not be understanding this. Let's go ahead. There was no point in giving it here. four, What is said in the factory, does it What is said in the factory, does it What is said in the factory, does it represent or not? If the value explain it in simple language, if whatever explain it in simple language, if whatever happens to the value, if the value of the grade, if there is a happens to the value, if the value of the grade, if there is a mother, means all the value, if there is a van, mother, means all the value, if there is a van, then the value of the grade will be its van. then the value of the grade will be its van. then the value of the grade will be its van. is zero, then it becomes a matter of zero. False Constructive This is our great question. What is our saying? Se value is all van and zero if the se value of the current grade will be means it is the photo of the note. is the element, inside this I tell that if this is our great, okay this is the note, the meaning of the note is that it is representing the grade, then the note of the note on one note, means it has any children In this, all the values are zero, our in this case, what will be our lift, it see all the deletes inside it, by the way, I will see all the deletes inside it, by the way, I will explain in the question, then you will understand, so let's explain in the question, then you will understand, so let's move ahead, [Music] like what is there in the example, [Music] [ Tell me, what elements are equal in this mode, Tell me, what elements are equal in this mode, after that now one thing has happened left is representing our top right, now we are top right. leaf note is Van and what will be the value. Zero D divided into current. Now we will see in the top left if ours is true then Van is done. What will be the value ours is true then Van is done. What will be the value which is above the element. We which is above the element. We will see all the ones in the top right. will see all the ones in the top right. will see all the ones in the top right. means that this is not our leaf note, so the value of this lip is zero value, we can take zero and van anything. Okay, become zero, the saree one was equal and it will not have any child. What is equal? If not equal comes here then take it as I have written above that zero van zero. If any one of these goes to grade A zero van zero then we do it again inside it How is the note formed, I How is the note formed, I How is the note formed, I come out one more, come out one more, then this is our problem, then this is our problem, now the complete recursive is written, how do we solve it, first of all look at the base condition in the distraction, first of all look at the base condition in the distraction, what can be the base condition, that is, as many what can be the base condition, that is, as many small valid cases are required as possible. small valid cases are required as possible. small valid cases are required as possible. smallest validation and which will be the smallest valid? This will come when we have only one element come when we have only one element left, no time, what will be the true value equal to date element and the rest of the children etc., whatever means its child when I will be a single element, mother lo if when I will be a single element, mother lo if when I will be a single element, mother lo if one element is given then it is not possible, it is not possible that there is a note converted, then first in the unit and then we will convert it into 2/2, meaning by putting a note of 2/2 each, four After that After that After that our 1 * 1 will come again, in this we will have a single element in action [Music] What has happened to us is true and the rest has come, now tell me when is it possible that there will Let me Let me Let me tell you once that it will be tell you once that it will be a bit complicated, so let us show it in the court itself, so first of all we will so first of all we will take a function I grade, after that the initial cell of a I grade, after that the initial cell of a column means position, whatever it is, we will simply and create a new note Okay, what else is the Okay, what else is the leaf note? Yes, leaf note? Yes, if it is bullion, then the phone will also work. To present it, we create a parent note. Now we have kept N value in it. Now top left. What? top laptop we taken we taken out the top, is the top model, is the What will be the value here? is also from the value above, it means what is it is also from the value above, it means what is it representing, it means it will representing, it means it will represent from all the values of this great, it represent from all the values of this great, it is recursively broken out and seen later, the top left leaf is required, it means There is no child, there is There is no child, there is There is no child, there is no child, it means all its no child, it means all its elements are equal, all its elements are equal, all its elements are equal, all its elements are equal, all its elements are equal, elements are equal, now all the elements of its elements are equal, so now all the elements of its elements are equal, so how can it be that it is equal but here how can it be that it is equal but here zero is zero, okay zero is zero, okay zero is zero, okay a separate child. Do you understand that a new set will be created because its A value will become zero? No, but if it is so that all the A's are equal, then it means that this is a leaf note and it has It is not a child because all the It is not a child because all the It is not a child because all the elements are equal, the value is also from, so elements are equal, the value is also from, so we checked that if the leaf is note, then why is it also and if the value is from also, the value is compared, the value is also from, meaning If If If all the elements are equal, then all the elements are equal, then only one note will be written in it at a time, which only one note will be written in it at a time, which means it will be left as a leaf, which means it will be presented as a whole and not means it will be left as a leaf, which means it will be presented as a whole and not sent to me separately. What will the value do? What will the value do? Update the value of any one separate item. Update the value of any one separate item. Update the value of any one separate item. when it is equal, it is ours, but if it is not like this, this is our single, he will have some children, so this is our single, he will have some children, so this is our time, top left, this is our time, top left, parent note, bottom right, question mark. I didn't make a typing mistake I didn't make a typing mistake [Music] [ submit | 2024-03-22 11:16:41 | 427 | 427. Construct Quad Tree||LEETCODE||EASY EXPLANATION|| C++||DAILY CHALLENGE |
|
NEsVXFgihzE | foreign [Music] problem and the problem's name is Max consecutive ones so in this question we're given array nums and we have to return the maximum number of consecutive ones inside the array so in this example there are two consecutive ones but there is also another set of ones which is longer than the previous set having three consecutive ones so we return that as output now let's take a look at this example and see how this can be solved so I've taken the same example they have given us so this is the nums array so we are going to iterate through the nums array from left to right and we'll access each element at a time so inside this for Loop we are accessing one element at a time using a pointer I so if that element at I is 1 we increment the count and we compare it with the variable and store the max of Max and count inside this variable and we finally return Max as the output so we start from I is equal to 0 so the element at 0 is 1 so increment count and we also check Max of Max and count so max of 1 comma 0 is once so set max also to 1 and we go for the next element next element is also one so increment count count will become to Max of count and Max is 2 so max will also become 2. now go for the next element it is 0 so make count 0 and check Max of count and Max Max of count and Max is 2 so max will remain 2. go for the next element it is 1 so increment count Max of count and Max is 2 comma one so max will remain two move for the next element next element is also one so increment count count is now to Max of Max and count is 2 comma 2 so max will remain 2 over the next element it is also 1 so increment count Max of Max and count is 2 comma three so maximum 2 comma three is three so change Max to 3 and go for the next element and now we reach the end of the array so we end the iteration and finally return whatever is present inside Max Max contains three so three is our output so this will be the range where Max is equal to three so if you return 3 as the out now let's code it up in Java so this is the function given to us and this is the input array norms and we need to return our integer variable denoting the maximum number of consecutive ones so let's start off by creating the result variable so max is going to be the output we are going to return which will denote the maximum number of consecutive ones and again I am going to create a variable count which will be used to count the number of ones in each set now let's iterate through the input array nums using a for now we have to check if the element at now we have to check if the element at the eight pointer is a one or not if that element is 1 we increment the count variable denoting there is a one and we check if it is the maximum streak and in the else block and in the else block it means that that number is not a one it means that that number is not a one if it is not a 1 we set back the streak if it is not a 1 we set back the streak to zero to zero so this for Loop will happen for all the so this for Loop will happen for all the elements inside the nums array and elements inside the nums array and finally we have the result inside the finally we have the result inside the variable Max variable Max let's return that now let's try to run the code the test cases are running let's submit the code there you have it a solution has been accepted so the time complexity of this approach is of n where n is the number of elements inside the nums array and the space complexity is above 1 because we are not using any extra data structure to solve this equation that's it guys thank you for watching and I'll [Music] [Music] foreign | 2024-03-22 15:33:32 | 485 | Leetcode | 485. Max Consecutive Ones | Easy | Java Solution |
|
KToLjmgVJzg | That's it, welcome back to my YouTube channel, I am Jyotish and in this video series, channel, I am Jyotish and in this video series, we are solving the problems of lift. The we are solving the problems of lift. The format of this video is format of this video is because today we are going to solve a classical problem because today we are going to solve a classical problem which is Calendar. which is Calendar. Number So let's see what this problem Number So let's see what this problem statement says which is melanin teacher statement says which is melanin teacher we have to return through if we have to return through if before one romantic but we people say follow the interior before one romantic but we people say follow the interior only when they reverse then it would be the only when they reverse then it would be the same number example given 1622 121 which same number example given 1622 121 which That number is 19 but - not the top number, That number is 19 but - not the top number, similarly tan and - 101 can also be subscribed to the channel similarly tan and - 101 can also be subscribed to the channel then you can simply reverse the number, in then you can simply reverse the number, in this way you can contact the this way you can contact the new number with the number and new number with the number and do the according result if the value do the according result if the value ok | 2024-03-19 12:12:36 | 9 | #9 Palindrome Number | Ultimate Leetcode Challenge |
|
7Qh7zyd6QDQ | hi my name is david today we're going to do number 551 do number 551 student attendance record one only code student attendance record one only code this is an easy level problem and we're this is an easy level problem and we're going to solve it going to solve it in javascript so this one was kind of in javascript so this one was kind of like a fun one like a fun one a simple if else statement while we're a simple if else statement while we're looping through looping through so we have a function that takes an s s so we have a function that takes an s s is a string right yeah it's a string is a string right yeah it's a string that only takes in that only takes in a l p a signifying the student was a l p a signifying the student was absent absent l signifying student was late and p l signifying student was late and p representing the student was present representing the student was present and they have an attendance word if they and they have an attendance word if they meet these criteria meet these criteria and so basically we have to return true and so basically we have to return true or false true or false true if they they meet these require if they they meet these require both of these criteria is false if they both of these criteria is false if they didn't so didn't so if they were absent if they were absent if the student was absent for fewer than if the student was absent for fewer than two days two days and then the student was never late more and then the student was never late more than three consecutive than three consecutive days so that is how we're gonna days so that is how we're gonna solve this problem so for this example solve this problem so for this example we return true because the student has we return true because the student has fewer than two absences fewer than two absences we look at the a's they only been absent we look at the a's they only been absent ones and they're ones and they're never late more than three times so they never late more than three times so they only relate twice consecutively only relate twice consecutively so how we're going to solve this problem so how we're going to solve this problem is that first is that first we have to look at we're going to loop we have to look at we're going to loop through this and we're going to return through this and we're going to return false false if if they doesn't meet one of these if if they doesn't meet one of these criterias and if they criterias and if they if we can loop through this without if we can loop through this without returning false returning false we return true so the first criteria we return true so the first criteria they look at is the absent they look at is the absent so we have to create a absent variable and that's just going to be a number that we're going to keep count of how many times they were absent in total and next we want to create a rate variable but consecutive so i'm late consec rate late consec rate variable okay so these are two layer variables we're going to use to keep track of everything and inside this loop we have to create a and inside this loop we have to create a condition condition if the student was if there was an a if the student was if there was an a condition if condition if value is a value is a and what we want to do if this happens and what we want to do if this happens is increment is increment a increment the absent and then we want to create a condition if absent is 2 or greater and then we just return false if this happens and now we look at the other variable was never laid three more consecutive days so we have to create a condition if it's and then we want to increment and then once we got that we have to and then once we got that we have to create create an else statement because we need a an else statement because we need a consecutive to reset consecutive to reset the variable else set contact date to zero and then lastly we return false if it's three or more so condition if contact rate is three or more and then we just return false and if we make it through this without returning fast will be returned true great so first we create the variables that absent equals zero that consec rate equals zero now we loop through s4 that i equals zero i is less than s dot length i plus plus and instead of this little loop we have to do each case if current index value as index i is we increment absent and then we create the condition to return false if it's two or greater if absent is greater than or equal to two return loss so that deals with this one and now we have to do the other condition if it's a late current index value equals l we do consec else and now we return false if and now we return false if consec rate equals consec rate equals is greater than or equal to is greater than or equal to three return three return false and we if you make it through this false and we if you make it through this without returning false we without returning false we return true great we got it so the complexity great we got it so the complexity the time complexity we know that we're the time complexity we know that we're doing a doing a loop do s so it's going to be of n and then the space complexity we are taking the constant variables here so it's going to be o one and that's it that's how you solve | 2024-03-20 11:00:56 | 551 | How to Solve "551 Student Attendance Record I" on LeetCode? - Javascript |
|
gtWtTLiqVa8 | hey guys welcome or welcome back to my channel so today we are going to discuss channel so today we are going to discuss another problem problem is binary tree another problem problem is binary tree maximum path sum maximum path sum very easy problem very easy problem in this problem we have to find a path in this problem we have to find a path in the binary tree in the binary tree and uh and uh so each node can only appear at most so each node can only appear at most once once path does not need to pass through the path does not need to pass through the root so it's not necessary that the path root so it's not necessary that the path should be passing through the root of a path is the sum of all the node values in that path so whatever path is all the values or sum of all the values in the of nodes in that path will be the path sum so we have two we have we are given the root of the binary tree and we need to find the maximum path sum of non-empty bath maximum path sum so let's take this test case here uh basically what we have to find is we have to find the path sum what is Pat sum basically this can be one path okay or this could be one path like from here to here like this so path sum is the sum of sum of all nodes which are in their all nodes which is in that path so for example if we take this blue path 9 minus 10 plus 20 plus 7 this will be the sum of this path okay if you take the path of this yellow uh this yellow uh some of this yellow path so it will be 15 plus 20 plus 7 which is 42. and this will be uh 26. okay so obviously we have to find the maximum path sum we have to find the maximum path sum so here the maximum path sum will be 42. that is this path so output will be 42. so basically what they are trying to say so basically what they are trying to say is we have to find any path and it's not is we have to find any path and it's not uh it's not mandatory that the path uh it's not mandatory that the path should pass from root path should pass from root path should not like it's not mandatory so he should not like it's not mandatory so he path could be this one also it's not path could be this one also it's not like it has to pass through the root like it has to pass through the root this is the root right this is the root right okay okay so so either your so there are two cases either your so there are two cases either your either your uh path uh path can pass through root through root or it does not pass does not pass okay so pause the video and try to think uh how you can solve this problem see the problem understand it and see what is given so minus 10 trees binary minus 10 9 20. 15 and 7. right 20 15 and 7. so whenever we have t right we visualize it like this that we visualize it like we'll be given the root of the binary and we have some left sub tree we have some right sub tree we will work on the root and the rest of the work recursion will do right so here what is the thing we have to return the maximum path this is a work so one thing is that the this is a work so one thing is that the path can pass through the root like this path can pass through the root like this right so if the path is passing through right so if the path is passing through the root the root so what will be the sum so what will be the sum that case sum of the path will be that case sum of the path will be whatever the sum of left sub tree whatever the sum of left sub tree the left sub tree plus sum of the right the left sub tree plus sum of the right sub tree Plus sum of root that is root value so this could be one sum other sum could be like uh the sum is not passing through the this like the sum is not passing through the root so if sum is not passing through the root this could be the maximum some left sub tree or right some somewhere in the left subtree or somewhere in the right subtree you will get the maximum paths so there are two cases right so what we will do right base case is we all know what will be the base case base case is if root is null if root is null so what will be the sum if root is null sum will be what 0 so return 0. this is your base case now let's say we are here we are at this now let's say we are here we are at this position our root is here position our root is here so there are two things so there are two things there are two things there are two things one can be one can be this is your sum this is your maximum this is your sum this is your maximum path sum like passing from this value path sum like passing from this value right something like this right something like this so if this is the case when you are here so if this is the case when you are here so what you will do 20 plus so what you will do 20 plus whatever is coming from the left sub whatever is coming from the left sub tree tree whatever is coming from the right whatever is coming from the right subtree subtree this will be your this will be your sum sum this could be one case right this could be one case right other case could be that other case could be that you have to pass the maximum sum from you have to pass the maximum sum from this node to the parent node this node to the parent node because it might happen that from this because it might happen that from this path you get the this is a part of that path you get the this is a part of that path path right right for example let's say from here to here for example let's say from here to here something like this from here to 20 something like this from here to 20 so which is more beneficial from this 20 so which is more beneficial from this 20 either you go to 15 or you go to 7. so either you go to 15 or you go to 7. so obviously 15 1 is more beneficial so it obviously 15 1 is more beneficial so it might happen this is the path might happen this is the path right right so to this minus 10 what you should so to this minus 10 what you should return return to this minus 10 you should return the to this minus 10 you should return the most optimal sum most optimal sum right most optimal part sum which is 20 right most optimal part sum which is 20 what is the current value root plus what is the current value root plus maximum which you are getting from left maximum which you are getting from left or right subtree what is the maximum you or right subtree what is the maximum you are getting from the left to right are getting from the left to right subtree that is maximum of whatever you subtree that is maximum of whatever you are going getting from left and whatever are going getting from left and whatever you are getting from right subtree that you are getting from right subtree that this value you will return this value you will return to the parent node because minus 10 to the parent node because minus 10 should know right whatever what is the should know right whatever what is the maximum path sum maximum path sum maximum sum in its maximum sum in its like subtree child subtree like subtree child subtree so so we'll have two cases we'll have two cases right let me draw 3 again so minus 10 right let me draw 3 again so minus 10 9 9 20 15 and 7. right you will have a global variable sum initialize to 0 when you are let's say you are at this node right this is your root so first you go to the left you make the recall left you go to right first of all you go to Left subtree DFS basic basic DFS we have basic DFS you go to left you are your root is here right now okay not here so your root is here from left you get 0 base case from right you get 0 so 9 plus if the path is like this only so 9 plus 0 plus 0 will be 9. so this is greater than some ninth and to the parent root parent uh node you will return 9 plus what is the whatever is the maximum of left or right because one path will be there right if you either left path will be there or right path will be there both cannot be there obviously because if both is there then it will be something like this right so whatever is the maximum so 9 or plus maximum of left is zero right is also zero so it will be 9 plus 0 which is 9. so 9 will be returned from here okay so from here 9 will be returned to the parent node 9 is returned okay now you are here now you'll make the right call it will go to right so 20 here root will be 20. okay so first you go to Left 15 plus 0 and all that so 15 will be the sum then you go to the right you go here root will become 7 so 7 is not greater than 15 so it will not be updated but from here you will get 15 as a return value and from here you will get 7. okay so now your root is here you from here you get 15 from here you get 7. now see what you will do now there are two cases either your path could be this one that is this passing from this root like basically this path Okay so 15 whatever you get from the sum is equal to will be maximum of the whatever the current sum is comma the current root value Plus whatever you get from the left subtree left sub 3 plus whatever you get from the right subtree because that could be one path right so here maximum of current sum is what 15 comma root value is 20 plus left you are getting 15 right you are getting 7. so here your sum will become 42. here it will get 42. okay so here we have done this root work now we have to return now what we will return from to the parent node now there can be two cases either this could be the maximum path for this parent like it can go from 10 to 20 and 15 like this or it can go to minus 10 20 and 7 like this so obviously you will return the beneficial one which whatever is beneficial so that would be to the parent node you will return to the parent node you will return root value root value plus maximum plus maximum of whatever you get from the left and of whatever you get from the left and right right whatever is maximum so 15 and 7 you're whatever is maximum so 15 and 7 you're getting from left sub 3 and right sub 3 getting from left sub 3 and right sub 3 so 15 is greater so 20 plus 15 that is so 15 is greater so 20 plus 15 that is 35 we will return that maximum if you go 35 we will return that maximum if you go from minus 10 you want to go you this from minus 10 you want to go you this will you will get the max path will you will get the max path so from minus 10 minus 10 plus so from minus 10 minus 10 plus 9 you are getting from here 35 you're 9 you are getting from here 35 you're getting from the right sub tree either getting from the right sub tree either this could be the sum this could be the sum right maximum but this will give you right maximum but this will give you um 34. um 34. right this is not the optimal one so 42 right this is not the optimal one so 42 is the maximum which you can get so is the maximum which you can get so output will be 42. output will be 42. so I hope you understood the approach uh so I hope you understood the approach uh let's see the code once it will become let's see the code once it will become more clear dry run the code once more clear dry run the code once yourself yourself so we have taken this Global variable in so we have taken this Global variable in initialize it with minimum value because initialize it with minimum value because we'll be storing the maximum value we'll be storing the maximum value inside it inside it then we have we are calling this then we have we are calling this function DFS and we'll return this function DFS and we'll return this maximum sum maximum sum in this DFS we will populate this value in this DFS we will populate this value so this is the base case that if root is so this is the base case that if root is null just return 0 null just return 0 otherwise you are making the left call otherwise you are making the left call you get some you get some and you'll be storing the back like the and you'll be storing the back like the maximum value if you get Negative from maximum value if you get Negative from here here so guys see if any time you're getting so guys see if any time you're getting negative value negative value there is no benefit benefit of there is no benefit benefit of considering that considering that right because negative will only reduce right because negative will only reduce your sum your sum so but we want maximum sum right so if so but we want maximum sum right so if it we are getting negative we will just it we are getting negative we will just get take 0 only get take 0 only will not go that path only for example will not go that path only for example let's say let's say this is your root this is your root and this is your root this is your root and this is a left subtree this is your this is a left subtree this is your right sub tree right sub tree from this left subtree you are getting from this left subtree you are getting some negative sum some negative sum so there is no there is no benefit of so there is no there is no benefit of considering this negative path just take considering this negative path just take this only because negative will only this only because negative will only reduce your some value we want to reduce your some value we want to maximum sum maximum sum okay so 0 taking 0 here means that we okay so 0 taking 0 here means that we will not consider this only we will not will not consider this only we will not consider this only consider this only write also same thing write also same thing now now the sum could be the sum could be the root Value Plus whatever you get the root Value Plus whatever you get from left whatever you get from right from left whatever you get from right this is what we were doing doing here this is what we were doing doing here right right whatever you get from the root Value whatever you get from the root Value Plus whatever you get from the left Plus whatever you get from the left whatever you get from the right maximum sum get the maximum sum and when you are returning so return the root Value Plus maximum of left and right because you have to give to the parent so whatever is the maximum sum in the subtree child subtree give that right so I hope you understood the problem uh o of n is the time complexity we are doing a single traversal okay and yeah if you found the video helpful please like the video subscribe to my channel if you have any doubts let me know in the comments and thanks for | 2024-03-21 11:21:04 | 124 | Binary Tree Maximum Path Sum | Leetcode 124 | Binary Tree |
|
ofumfel6mRE | I will come in this edition they appeal to discuss about one of the common interview questions one of the common interview questions friends this question bill out at least five friends this question bill out at least five times and top-10 interview given input times and top-10 interview given input singh identified length of the longest subscribe singh identified length of the longest subscribe according to must be without any according to must be without any rippling character zara cloth examples rippling character zara cloth examples For example the reader in here a b c For example the reader in here a b c swaroop shivling without any characters swaroop shivling without any characters similarly bca like subscribe along it's something similarly bca like subscribe along it's something rank spent in this example the rank spent in this example the longest serving intestine repeated with example person and longest subscribe i saudi answer woman or me to identify the like this i saudi answer woman or me to identify the like this problem substance solution problem substance solution Stuart Broad This Problem But Will Discuss Stuart Broad This Problem But Will Discuss Various Liquid Sliding Window Based Various Liquid Sliding Window Based Approach Paris Of Inputs And Jerry Index Approach Paris Of Inputs And Jerry Index Is Mask Andar Top 10 Will Have Two Point Is Mask Andar Top 10 Will Have Two Point Five Five Because I Will Be Representing 10 Top 10 Because I Will Be Representing 10 Top 10 Sliding Window And Jet Will Be Sliding Window And Jet Will Be Representing Ten Sliding Window Representing Ten Sliding Window Sliding Sliding Sliding Any Repeated Characters Subscribe Window Will Be Subscribing Link Initially Both That In Iteration Will Increase The Valid Notes Will Keep That In Iteration Will Increase The Valid Notes Will Keep Adding One Character Internet Adding One Character Internet Sliding Window In Which Direction Which Will Sliding Window In Which Direction Which Will Form A Sub Strength Will Form A Sub Strength Will Form A Sub Strength Will elections and in such a situation even encounter animated character I will be changed only when contacted animated character interest sliding window will be amazed and index of repeated character list a distinct and experiment and logic will be taking a map for the character that In which all say will declare available for the length of the thing in which direction software name is science an initial 1200 initially both in the appointing 201 depression like this point mintu character subscribe and not present computer era of your is aa 0512 Size Want 0512 Size Want 0512 Size Want That Boat Store Character Interment Razor That Boat Store Character Interment Razor Storing Index 1208 Will Toe Current In Na Storing Index 1208 Will Toe Current In Na Exclusive Way Will Strive Doing This Exclusive Way Will Strive Doing This Little Letter Internet Station J One Point * Little Letter Internet Station J One Point * Indicates Character Same Process Vidmate App Indicates Character Same Process Vidmate App Will Reach Computers Want Na Sliding Will Reach Computers Want Na Sliding Window Character Subscribe Chief Tom Window Character Subscribe Chief Tom Subscribe Subscribe Should Be Updating Computer And Subscribe Should Be Updating Computer And That In Front Value Will Update With That In Front Value Will Update With Maximum Benefit Saw This A Maximum Benefit Saw This A Mac One Earning ₹2 Chu Boat Will Update Inter Mac One Earning ₹2 Chu Boat Will Update Inter Map With Special Needs In Its Current Map With Special Needs In Its Current Inductive Will Give Which Actions In Nation Inductive Will Give Which Actions In Nation Will Be Will Be Will Be Subscribe And Will Se Max To VIP End Subscribe And Will Se Max To VIP End Finally Bigg Boss Left Finally Bigg Boss Left CA Inter Map Current Industry Situation Different Subscribe Cr Reddy Inter Map Depend Value Will Be Co Electrician Job Will Appoint Leaders Buffett will to Buffett will to Buffett will to enter into the next generation Will be enter into the next generation Will be appointed to intense pain Already present its appointed to intense pain Already present its time to update your value on and time to update your value on and initial discussion Will receive new updates Will be equal to a maximum of current well Wishes for 100 I will be updated Vaikunth point with oo I Just Before Adding Inter Map In Such Cases Will Be Appointed To Character C Which Will Result In Duplicate Character Industry Leaders In The Year In Preventing Bike 150 Wedding Inter Map Justice That Duplicate Character Late Computer Science Jewelry Phase 351 Stree Thama Thama Thama 3225 Noticed Sliding Window Have Only 3225 Noticed Sliding Window Have Only Three Characters But Subscribe 500 Fuel Subscribe Three Characters But Subscribe 500 Fuel Subscribe Last Wicket Next Subscribe Now Will See Last Wicket Next Subscribe Now Will See Inter Element Peeth Inter Element Peeth President And Different Activities In The President And Different Activities In The World Will Be World Will Be Updated With Sticks Updated With Sticks That Internet Station JV Point *Indicates That Internet Station JV Point *Indicates Character See Next Stitch Already Character See Next Stitch Already Character See Next Stitch Already the map Vittori Computer Value Is Equal To A Maximum Of Its Current Value Which Is The Best App 200 Districts Minute Update I Pointer Share Subscribe And The Appointing 60 Plus One White Maximum Of 0535 Exclusive Five Eighth August Inter May Free Computers Pay Anil Jain Riches And You Will Anil Jain Riches And You Will Anil Jain Riches And You Will Notice All The Best All Created Things Which Will Return Notice All The Best All Created Things Which Will Return In Which Is The Largest In Which Is The Largest Subscribe Button Click Subscribe Button Click Ho Ki Main Ho Ki Main A Character In Teaser A Character In Teaser A Map Quarter New Face Man A Map Quarter New Face Man E Will Declare Aware Total 10 Science And E Will Declare Aware Total 10 Science And Final Result Quarter Heroes And Final Result Quarter Heroes And Final Result Quarter Heroes And return the value of a literate and processes character int i quarters amazon half aa j electronic input blank co z map.com input well half withdrawal equal dot maximum current map.com input well half withdrawal equal dot maximum current actor will oo will get in do Final Result A Rebound Method 8 Maths Final Result A Rebound Method 8 Maths 8th Previous Value Final Result Kya 8th Previous Value Final Result Kya Maje - Festivals and Maje - Festivals and Main Finally Add Character Inter Map Map Duck Main Finally Add Character Inter Map Map Duck Points Input Director Know Z Plus Points Input Director Know Z Plus One Middling Notification Avoid Subscribe Subscribe Jhala Ne Virat Ka Output End Brothers Saeed Jhala Ne Virat Ka Output End Brothers Saeed Akhtar Lajjit Stuff Akhtar Lajjit Stuff Akhtar Lajjit Stuff characters in inch input thanks for watching please do you like the video and | 2024-03-18 10:35:02 | 3 | Length of Longest Substring Without Repeating Characters - LeetCode 3 |
|
KjUScxOb3pc | let's solve lead code 16864 count the number of consistent 16864 count the number of consistent strings so the question gives you two strings so the question gives you two inputs first is inputs first is allowed which is a allowed which is a string so allowed for example could be something like ab and it will be a string of unique characters so there won't be any repeats on this something like a b c d there cannot be another A or B or C or D so it will be a string with unique characters and then there are there is a array that they providing a list and this list includes several other words something like A B C D A B C D or B C D A or B C D A or h g j a so something like this or h g j a so something like this right so you need to right so you need to return the number of return the return the number of return the count of count of words within this right so these words words within this right so these words can have duplicates as well something can have duplicates as well something like like this right this can have this right this can have duplicates like this and you all you duplicates like this and you all you need to check is how many words out of need to check is how many words out of this in this list are such that which this in this list are such that which are made up of these Char some are all are made up of these Char some are all of this character remember some or all of this character remember some or all of these characters which means that of these characters which means that this is a valid string this is a valid this is a valid string this is a valid string that is that I'm comparing so string that is that I'm comparing so I'll consider this as one because it is I'll consider this as one because it is using A and B out of these a b c d this using A and B out of these a b c d this is a valid string it's using all of is a valid string it's using all of it this it this is a valid string also is a valid string also it need not be in the same it need not be in the same order so this is also valid string it is order so this is also valid string it is made up of only these made up of only these characters this is not a valid string h characters this is not a valid string h g j are not part of this a is part of it g j are not part of this a is part of it so this is not and G is not again so this is not and G is not again because there's no G in because there's no G in this so I'll add a top so it gives me this so I'll add a top so it gives me three so I'll return three so I'll return three okay so that's what the question three okay so that's what the question says now how will says now how will I enable this let me comment this out I enable this let me comment this out and write the code so I'll do the same and write the code so I'll do the same so what I was doing is I was checking so what I was doing is I was checking with each one of them and giving it a with each one of them and giving it a count of one or zero right and if it is count of one or zero right and if it is not matching than zero if it is matching not matching than zero if it is matching than one and than one and if and finally sum it all up and return if and finally sum it all up and return it right so the same I can do so first it right so the same I can do so first thing first what I'll do is I'll change thing first what I'll do is I'll change allow allow is a string so I'll convert allow allow is a string so I'll convert that into a set okay so that I can that into a set okay so that I can easily do operations on it you can look easily do operations on it you can look up into a up into a set in order of one you know in a set in order of one you know in a constant order so that's why it's constant order so that's why it's important to convert it into a set if I important to convert it into a set if I don't convert it into a set and look up don't convert it into a set and look up the characters directly in the string the characters directly in the string that will be order of n every time for that will be order of n every time for each character it would be order each character it would be order of then what will I of then what will I do do I'll create a variable I'll create a variable count set it to count set it to zero okay and I could do for word zero okay and I could do for word in word words for each word okay what I'll do I'll create a set of it set of word okay I'll take this word and create a set of it so it will create an uh create a set uh like this it will create a a comma B right for the second one one a comma B right for the second one one it will create a set of a comma B comma it will create a set of a comma B comma C comma C comma D for the third one again it D for the third one again it will create a set of ab C for the fourth will create a set of ab C for the fourth one it will create a set of hedge a h g j and for the fifth it will create a set of just one character which is so it will take unique characters and create set is nothing but a set collection of unique characters Al so it will take the unique characters and then I can compare this with it should be less than or equal to allowed which is also a set okay so this operation what it does is it checks if all the characters in this are a subset of this right it may not be exactly if I do dou equal to that will say that they should be they should have all those characters that are there in this not even one character extra or less but if I do this which means that this is this has all the characters from this are part of this and may not necessarily be entire so and so here when this is a C comma D so which C comma D so which means that this is less than this means that this is less than this AP is less than this right AP is less than this right and this is equal to and this is equal to this right this right so I'm doing here is using less than or so I'm doing here is using less than or equal to but this example h g j a this equal to but this example h g j a this set ah GJ this is not a this is neither set ah GJ this is not a this is neither less than or equal to to this because it less than or equal to to this because it has cut has cut characters which are not in characters which are not in this this set okay so this this set okay so if this condition holds true then I'll if this condition holds true then I'll increment increment count and finally return it right let's run this and it worked 175 milliseconds let's look at the best solution here they are using the same methodology in the other way around they are basically finding all those which do not which are not part of a which have some letters which are not part of alloud and they're taking that that count and then finally subtracting it from the length of words so that gives them all the words which are part of alloud okay I could simplify this code in this example that we saw so what I could do is I could if if set of word is less than equal if if set of word is less than equal to to allowed then I'll return zero and I could remove all of this I zero and I could remove all of this I could remove the count and take a sum of could remove the count and take a sum of it okay and return the Su simple as that it okay and return the Su simple as that so this entire discussion that we had so so this entire discussion that we had so it will go through each it will go through each word return the word return the word the word will be compared with word the word will be compared with allowed and if it is less than or equal allowed and if it is less than or equal to it will return one else it will to it will return one else it will return return zero and finally I'm taking a sum of all zero and finally I'm taking a sum of all the ones and zeros and returning it the ones and zeros and returning it let's run and see and that it and that work 167 millisecond better it and that work 167 millisecond better than 80% of sub | 2024-03-20 12:13:46 | 1,684 | Leetcode 1684. Count the Number of Consistent Strings |
|
fKe5iZ1nqE8 | hey what's up guys so let's one over three check if a word is valid after three check if a word is valid after substitutions substitutions so given string s determine if it's so given string s determine if it's valid valid so string s is valid if you're starting so string s is valid if you're starting with empty string and you can form a t with empty string and you can form a t into s after performing following into s after performing following operations so basically you will have operations so basically you will have the the string called abc and you can add any uh string called abc and you can add any uh left and right and left and right and compose it with abc compose it with abc okay uh properties is hard runners that okay uh properties is hard runners that baby see example so aabc baby see example so aabc a a bcbc right so you can take abc and a a bcbc right so you can take abc and you see abc all right so you can take you see abc all right so you can take this and use abc this and use abc and for this one you can say bc abc so and for this one you can say bc abc so these are all okay and then for this one these are all okay and then for this one right you get the same thing right you right you get the same thing right you can you once you take abc out and you can you once you take abc out and you see another abc see another abc and it is impossible because if you take and it is impossible because if you take one abc out then cba cannot force babc one abc out then cba cannot force babc also uh there's no if you take abc out also uh there's no if you take abc out you get cib you get cib okay so you get the answer right okay so you get the answer right basically uh basically uh whenever you see abc you just mod up whenever you see abc you just mod up right so while abc s you just mod up right so while abc s you just mod up and uh and uh finally finally if there's some remaining that means if there's some remaining that means they're on our way bc i know if you see they're on our way bc i know if you see that means you don't you can know you that means you don't you can know you don't you cannot do anything right so don't you cannot do anything right so you should return to false you should return to false if it's empty that means you can keep if it's empty that means you can keep using abc so return true using abc so return true okay so that's it so this is a very okay so that's it so this is a very simple question okay see you guys next simple question okay see you guys next video | 2024-03-25 13:04:26 | 1,003 | Leetcode 1003 Check If Word Is Valid After Substitutions |
|
Jobb9YUFUq0 | hello everyone welcome back here is vanamsen today we have an exciting vanamsen today we have an exciting problem to solve it's called letter problem to solve it's called letter combination of phone number and guess combination of phone number and guess what we will not only write the solution what we will not only write the solution in Python but also share implementation in Python but also share implementation in various languages in the description in various languages in the description below so let's Dive Right In imagine you below so let's Dive Right In imagine you have a old-fashioned telephone keypad have a old-fashioned telephone keypad and you want to find all the possible and you want to find all the possible letter combination for a given number letter combination for a given number just like texting with an old-fashioned just like texting with an old-fashioned phone so we will be using python to phone so we will be using python to solve this problem and I will be guiding solve this problem and I will be guiding you through step by step you through step by step so for example given digits two and so for example given digits two and three we need to Output all combination three we need to Output all combination of letters so first of letters so first uh think we will need a mapping between uh think we will need a mapping between the digits and corresponding letters the digits and corresponding letters just like on the telephone button just like on the telephone button that's where our phone map comes in and that's where our phone map comes in and then we will use technique called then we will use technique called recursive effect tracking to explore all recursive effect tracking to explore all possible combinations so sounds fun all possible combinations so sounds fun all right so let's code right so let's code first let's handle the base case if the first let's handle the base case if the input string digits is empty we will input string digits is empty we will simply return an empty list and then simply return an empty list and then we'll create our phone map and this will we'll create our phone map and this will map each digits to its corresponding map each digits to its corresponding letter for example two maps to ABC three letter for example two maps to ABC three maps to DF and so on maps to DF and so on so so if not digits if not digits return return empty and phone map will be empty and phone map will be 2. 2. 3 DF or six eight nine and yes so uh next we will Define a recursive function called backtrack and this where the magic happen we will explore each digit corresponding letter and recursively build the combination so now let's look at the heart of our function so the backtrack function and this recursive function is where the real magic happen so I want to spend some time breaking it down so why recursive backtracking well recursive allow us to explore all possible combination by dividing into each level of choice and it's like navigating a tree where each node represents a choice and we want to explore every possible branch and backtracking on the other hand allow us to go back and explore different path when we hit a dead end so let's implement it Dev back track combination next digits and if Len next digit equals zero combination combination else else or letter in or letter in phone phone map map next digit zero backtrack plus letter plus letter next digit one next digit one so so this part this part checks so length 0 and this part checks checks so length 0 and this part checks if there are no more digits left to if there are no more digits left to explore and if we reach the end of the explore and if we reach the end of the digits it means we have a complete digits it means we have a complete combination so we append it to Output combination so we append it to Output think of this as reaching a leaf in our think of this as reaching a leaf in our tree of choice tree of choice and then we have a backtrack combination plus letter next digit from one so now here's where things get interesting if there are more digits to explore we look at the first digit in next digit and find its corresponding letter from our phone map imagine the current digit is 2 that means we have three choices a b and c and we will explore each choice one by one so we add a to our current combination and call backtrack with the new combination and the remaining digits so we backtrack all right b instead and again call backtrack so finally we backtrack once more time and add C and call backtrack again so this Loop continue recursively exploring every possible combination for each digit it's like navigating through every branch of the tree ensuring we don't miss any possibility and finally we call our backtrack function with empty combination and the given digit and return the output so output will be this backtrack empty digits and return output and recursive backtracking is a powerful and elegant way to solve this problem and by understanding the logic behind the backtrack uh function we can appreciate the depth and efficiency of the solution so let's uh run it so for given test cases to free all looks perfect so we can also so let's see so let's see and yeah so our implementation bit and yeah so our implementation bit 68 with respect to uh runtime I think if 68 with respect to uh runtime I think if we rerun it we rerun it it might be a bit different so let's see it might be a bit different so let's see so yeah now it's uh 81 uh milliseconds so yeah now it's uh 81 uh milliseconds and I have even 34 with the same and I have even 34 with the same implementation so probably the test implementation so probably the test cases are quite different so I reach cases are quite different so I reach even 96 of bidding at 34 milliseconds even 96 of bidding at 34 milliseconds but the logic is the same and that's it but the logic is the same and that's it we have uh implemented recursive back we have uh implemented recursive back tracking solution to find all possible tracking solution to find all possible letters combination of a phone number letters combination of a phone number and you can find the codes in other and you can find the codes in other languages like C plus Java rust and more languages like C plus Java rust and more in the description below and I hope you in the description below and I hope you found this tutorial and lightning and if found this tutorial and lightning and if you enjoy it don't forget to hit the you enjoy it don't forget to hit the like button subscribe uh ring the like button subscribe uh ring the notification Bell for more exciting notification Bell for more exciting cutting content tutorials and much more cutting content tutorials and much more and leave a comment if you have any and leave a comment if you have any question or suggestion for next uh video question or suggestion for next uh video until next time keep coding keep until next time keep coding keep exploring exploring happy layering | 2024-03-19 16:00:50 | 17 | Solve LeetCode 17 Letter Combinations of a Phone Number Exploring Recursive Backtracking with Python |
|
Dyj8EeupuiA | hello guys now I would solve the letter combinations of a phone number let's do combinations of a phone number let's do the problem statement first the problem statement first given a string containing digits from 2 given a string containing digits from 2 to 9 inclusive return all possible to 9 inclusive return all possible letter combinations that the number letter combinations that the number could represent a mapping of digits are could represent a mapping of digits are two letters are like under telephone two letters are like under telephone patent city even below not that one turn patent city even below not that one turn on map to end letters they see the on map to end letters they see the example input her two three I will example input her two three I will return the ad a EF V D and so on so return the ad a EF V D and so on so forth we are given two and three and forth we are given two and three and there is the three choices of the two there is the three choices of the two and there is spiritual all the three so and there is spiritual all the three so we come every I will choose one from we come every I will choose one from this is three there is an N choose one this is three there is an N choose one from there it can letters so basically from there it can letters so basically we see the backtracking program because we see the backtracking program because we should exhaust all the possible we should exhaust all the possible combinations let's do it so basically combinations let's do it so basically the time complexity will be the expec the time complexity will be the expec exponential because we for further lands exponential because we for further lands of their time complexity will be the of their time complexity will be the three chooser last older serve letters I three chooser last older serve letters I have three choices and time so for have three choices and time so for chooser numbers of their better the chooser numbers of their better the number could have four choices because number could have four choices because they're seven and nine may have four they're seven and nine may have four choices of the best suit in either the choices of the best suit in either the least solution without our result least solution without our result release a register and to educate track release a register and to educate track is the given T treats dollars equal to is the given T treats dollars equal to zero or some countries there we have cat zero or some countries there we have cat the mapping of their number to their the mapping of their number to their letters maybe zero mega to empathise 3 and warm air to emphasis tree under to metro ABC 3 mm to t EF and the form M 2 gh I unify map to j ka oh and there are six map to M and oi7 map to PQRS 8 am actually tu v 9 X to W X Y Z again we will use a help function because then I can carry more parameters finally we return the result I will kill the pyramids afterwards okay that's the first serve right to the help function help function let's think what appearance do we need the first we need our string next I wish the result now also we needed a current street and there we also needed the string ages of course so we need other mapping and we also need an index because we want to know where we are in the digit string and is the okay then best case basically if for we reach the Ender which means we have we have chose older choices we should have added a culture stirring our result list so index is equal to the teaches tolerance where is either the current string will return and there else that will be our recursive situation well first get cancels our number because we are given a digit that is drink right so we we get it out to a character and a convert out treat digits charge adds her index and their - 0 then we can in integer and also we will get their candidates which means water the representation of data number mm camera present oh yeah repeat what what letters can this number represent there will be mapping position there now we will try every possibility for into I go to 0 I left it can be the starless and I plus plus I use the help function and a result curl with class that can be sitt substrate I then digits and mapping index that's all the reason out iostream because if I a stringbuilder oh sorry I forgot to fill this parameters without her curries empathy and the third victory and real that I use the string no distributor because if I use string builder I should have first appendix Eric tenders yeah I should have said to the lens 2-1 so is a little bit of annoying so adjuster as data in the function data I will not have to choose untruth it's a will be much easier so okay happy coding | 2024-03-19 16:01:54 | 17 | LeetCode 17. Letter Combinations of a Phone Number Explanation and Solution |
|
0n_s2D1Y9z0 | hey hey everybody this is Larry this is is it the first day it is of the is it the first day it is of the December the code day challenge hit the December the code day challenge hit the like button hit the Subscribe button 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 bomb we'll be doing think about today's bomb we'll be doing the December things or month because I the December things or month because I don't know we've we have a big street don't know we've we have a big street going so it's not gonna stop here uh going so it's not gonna stop here uh yeah uh today's part I miss 1704 yeah uh today's part I miss 1704 determined with string halves are alike determined with string halves are alike so basically you have a string as of so basically you have a string as of evenings but this string into two halves evenings but this string into two halves of equal lengths a of equal lengths a they're like if they're the same number they're like if they're the same number of valves uh AIU and okay we don't shoot of valves uh AIU and okay we don't shoot their like what does that mean their like what does that mean uh or like uh or like is it just wow it's like it doesn't is it just wow it's like it doesn't matter which one right so a and okay not matter which one right so a and okay not just oh all right well uh I mean I think you just count the number of aeio's right so um as lower uh for I don't know I mean we could probably do in a better way but if x is in aiou um count increment by one and then return count to zero zero right I think that's pretty much it you're probably right in a better way like some if or something like that did I messed it up oh they have to be gig of links okay so I must read this one whoops um that's what I get for being too fast and it happened to work on the tax cases now because uh when I thought I missed the two halves or I missed the equal length spot so um the reason why then that's why I wrote it this way right because um if there was no if the link doesn't have to be equal then you could do a pigeonhole thing where if it's odd number of um odd number of vowels then you can't do it if it's even then you can always there's always a point in the middle but I I think I just missed what the equal length support this is why don't they just give you two uh two strings this is kind of weird but okay fine I don't know so yeah so you can do I don't know so yeah so you can do something like cam Wells something like cam Wells um s right something like this um s right something like this um and then um and then and then just do something like return and then just do something like return cameras cameras um s plus one or minus one I don't know plus one or minus one I don't know is it always even length it is even like is it always even length it is even like okay so I don't have to worry about it okay so I don't have to worry about it um um foreign foreign this is what I get for not reading no this is what I get for not reading no problem I guess uh yeah just right let me [Music] oh it's just being too fast to be honest uh if I could have done it uh all right let's give it some it yeah okay it won't answer last time too or two times ago what did I do hmm oh I didn't do the lower no I did oh I put n is equal to oh because I didn't set S as you go to lower so again and maybe this one is a little bit deceptive and that I I apparently I made two silly mistakes in the three times I've tried this even though it is a very easy problem I hope no one else have trouble with it if you do have trouble with this let me know um but yeah I mean I think I just missed oh I miss we I missed the part about Jacob length so I just thought that you know and I did a reduction in my head and I was gonna explain it but well I'll explain it for another one um this is gonna be linear time constant space obvious reasons I don't know if I have to explain this one so yeah let me know what you think um like I said would be to here all month so stay good stay healthy take your mental health I'll see y'all later | 2024-03-20 14:51:56 | 1,704 | 1704. Determine if String Halves Are Alike - Day 1/31 Leetcode December Challenge |
|
0PiH6Beqif8 | hey what's up guys think whitey already you're talking coding stuff on twitching you're talking coding stuff on twitching YouTube check the description for all my YouTube check the description for all my information I do the premium problems on information I do the premium problems on my patreon for two bucks and you can my patreon for two bucks and you can join my discord I'm building a community join my discord I'm building a community here if you message me I try to respond here if you message me I try to respond to everyone this is fine pivot Index to everyone this is fine pivot Index this is an easy problem very easy one of this is an easy problem very easy one of the easiest on leak code I think given the easiest on leak code I think given an array of integers nums write a method an array of integers nums write a method that returns the pivot index of this that returns the pivot index of this array you might have heard of pivot if array you might have heard of pivot if you know a quicksort is if you don't you know a quicksort is if you don't they give you a definition of what pivot they give you a definition of what pivot is in this case here we define the pivot is in this case here we define the pivot index as the index where the sum of the index as the index where the sum of the numbers to the left of the index is numbers to the left of the index is equal to the sum of the numbers to the equal to the sum of the numbers to the right if no index exists we should right if no index exists we should return negative 1 and there's multiple return negative 1 and there's multiple pivots we should return the leftmost one pivots we should return the leftmost one okay great so what this is telling us is okay great so what this is telling us is let's look at an example we give it an let's look at an example we give it an array of numbers in this method that array of numbers in this method that we're implementing we're trying to find we're implementing we're trying to find the pivot where the pivot is you know in the pivot where the pivot is you know in this case it says index 3 it's an index this case it says index 3 it's an index so 0 1 2 3 this is the pivot in this so 0 1 2 3 this is the pivot in this case and they're saying the pivot is the case and they're saying the pivot is the index where the numbers to the left all index where the numbers to the left all these numbers summed add it up is equal these numbers summed add it up is equal to the numbers to the right summed and to the numbers to the right summed and add it up so we could see the numbers to add it up so we could see the numbers to the left 7 plus 3 plus 1 is 11 in 6 plus the left 7 plus 3 plus 1 is 11 in 6 plus 5 is 11 so that is correct okay in this 5 is 11 so that is correct okay in this case there's nothing there's no pivot so case there's nothing there's no pivot so negative 1 now how do we do this well negative 1 now how do we do this well you should think it's pretty easy you should think it's pretty easy honestly it's not too bad like let's honestly it's not too bad like let's think about this like if you look at think about this like if you look at these numbers like how are we gonna if these numbers like how are we gonna if just looping through like you can't just just looping through like you can't just go ok 1 plus a is a how and then you go ok 1 plus a is a how and then you can't just check if that's equal to this can't just check if that's equal to this right we don't know anything about these right we don't know anything about these numbers so I mean you could do a double numbers so I mean you could do a double for loop so you could like loop the for loop so you could like loop the reach number and then like loop through reach number and then like loop through the array again and check but like the array again and check but like that's pretty stupid when you the that's pretty stupid when you the obvious thing is probably just get a sum obvious thing is probably just get a sum first right so you you want to sell them first right so you you want to sell them all the elements so you loop through all the elements so you loop through once that's just a linear loop so you once that's just a linear loop so you loop through and you go ok 1 plus 7 is 8 loop through and you go ok 1 plus 7 is 8 plus 3 is 11 plus 6 is 17 plus 5 22 plus plus 3 is 11 plus 6 is 17 plus 5 22 plus 6 20 6 20 boom not 28 you know the some of it now boom not 28 you know the some of it now okay let's loop through it again now we okay let's loop through it again now we already have the sum is 28 let's keep a already have the sum is 28 let's keep a left cell now left on the zero and let's left cell now left on the zero and let's check the current element if total sum check the current element if total sum minus left's on - current element is minus left's on - current element is equal to left sum and then that will equal to left sum and then that will give us the answer so we just do ok give us the answer so we just do ok let's check this nut let's check let's check this nut let's check we have zero this is the main condition we have zero this is the main condition right here I don't know if I have to right here I don't know if I have to explain this to you but total sum - left explain this to you but total sum - left some - nomes of I equals left sum if some - nomes of I equals left sum if this happens we found the right index this happens we found the right index because if 28-0 because if 28-0 which is the sum right now - 1 so 27 if which is the sum right now - 1 so 27 if 27 is equal to 0 well then that means 27 is equal to 0 well then that means that all of the numbers to the right are that all of the numbers to the right are equal to the numbers to the left but equal to the numbers to the left but that's not true that would mean there is that's not true that would mean there is nothing here right if we saw this one nothing here right if we saw this one and there was a zero here then that and there was a zero here then that would make sense because the left sum is would make sense because the left sum is zero the numbers to the left of 1 equal zero the numbers to the left of 1 equal to the number of the right you know like to the number of the right you know like in this case right you know like in this case right you know like whatever but I don't know that was a bad whatever but I don't know that was a bad example but what am I talking about here example but what am I talking about here whatever dude basically what you're whatever dude basically what you're gonna do is you're gonna check the gonna do is you're gonna check the current number the current number isn't current number the current number isn't a part of the left or the right some so a part of the left or the right some so you're gonna check the current number you're gonna check the current number first and you're gonna say if the left first and you're gonna say if the left and right aren't equal then you're going and right aren't equal then you're going to add it on so you're gonna say 1 and to add it on so you're gonna say 1 and then you're gonna say 8 and you're gonna then you're gonna say 8 and you're gonna check this condition every time and check this condition every time and you're gonna say ok then you're gonna you're gonna say ok then you're gonna say 11 and then you're gonna say okay say 11 and then you're gonna say okay total sum minus 11 minus 6 so 28 minus total sum minus 11 minus 6 so 28 minus 11 28 minus 11 is equal to what is equal 11 28 minus 11 is equal to what is equal to 19 or someone like that maybe no 17 to 19 or someone like that maybe no 17 right 17 okay and then 17 minus 6 is right 17 okay and then 17 minus 6 is equal to 11 is that is equal you know equal to 11 is that is equal you know and if 11 is equal to and if 11 is equal to than the left and right or equal because than the left and right or equal because we know the total we subtract what we've we know the total we subtract what we've seen and we subtract the current number seen and we subtract the current number the current number isn't part of the sum the current number isn't part of the sum that we've seen and then we know what's that we've seen and then we know what's on the right it's pretty straight on the right it's pretty straight forward I'm not sure if I'm the best at forward I'm not sure if I'm the best at explaining it but I mean it's pretty explaining it but I mean it's pretty straightforward straightforward now we'll coat it I should've made this now we'll coat it I should've made this video this long either way anyways I video this long either way anyways I already messed up a few times I always already messed up a few times I always mess up I know I got a stop I gotta get mess up I know I got a stop I gotta get over it I feel like everyone you know over it I feel like everyone you know let me know below if other people don't let me know below if other people don't mess up at all I mean it might am I just mess up at all I mean it might am I just in the worst likely coder or whatever in the worst likely coder or whatever but so just get the total sum not too but so just get the total sum not too difficult right you've all done a for difficult right you've all done a for loop where you add to a sum get the left loop where you add to a sum get the left some so you go to zero I lost them not some so you go to zero I lost them not once again the same loop we have to once again the same loop we have to check first so we're not adding it on we check first so we're not adding it on we don't add it on right away because we don't add it on right away because we have to do a check first to make sure have to do a check first to make sure that the left and right are not the same that the left and right are not the same already so we have to do okay if you already so we have to do okay if you know what are we even saying if total know what are we even saying if total sum minus the left sum that would be the sum minus the left sum that would be the right sum right but we need to exclude right sum right but we need to exclude the pivot so minus nums of I because it the pivot so minus nums of I because it doesn't count for either is equal to the doesn't count for either is equal to the left sum that means they're the same if left sum that means they're the same if right sum is equal if right this is the right sum is equal if right this is the formula for right sum is equal to left formula for right sum is equal to left sum and we exclude the pivot then we sum and we exclude the pivot then we return the index we're at because we return the index we're at because we found the pivot that was a good found the pivot that was a good explanation there at the end so if you explanation there at the end so if you watched this whole long video you know watched this whole long video you know and now you finally get it so sorry I and now you finally get it so sorry I took me that long to finally articulate took me that long to finally articulate it correctly and then we return negative it correctly and then we return negative one if we don't find anything thank you one if we don't find anything thank you guys for watching sorry it took so long guys for watching sorry it took so long I know at the end I kind of said that I know at the end I kind of said that correctly what the help numbers of I correctly what the help numbers of I minus one oh my god okay you have to add minus one oh my god okay you have to add the previous elements sorry the previous elements sorry dang dude I am The King of mistakes dang dude I am The King of mistakes there you go that's there you go that's you have to do numbers of eyeness one you have to do numbers of eyeness one because we skip over it at first so that because we skip over it at first so that we could do the check so we add it we could do the check so we add it previously after we already checked it previously after we already checked it for pivot then we can add it on there for pivot then we can add it on there you go you go you should understand now I think I you should understand now I think I explained it it's an easy problem you explained it it's an easy problem you can look at it and figure it out anyway can look at it and figure it out anyway I'm getting frustrated I'm moving my mic I'm getting frustrated I'm moving my mic around and stuff please just respect me around and stuff please just respect me and you know respect your community and and you know respect your community and respect your environment so thank you respect your environment so thank you for watching see you in the next one | 2024-03-21 10:52:43 | 724 | LeetCode Find Pivot Index Solution Explained - Java |
|
gG3aJrbszFI | So hello friends, new day of Blind 75 and today is our today is our 69th day Sam of Tu Inteasers question 69th day Sam of Tu Inteasers question is easy type medium type but it will be easy is easy type medium type but it will be easy because I will explain the logic so it is going to because I will explain the logic so it is going to happen so in this we have given two interiors A and happen so in this we have given two interiors A and B, they have to be solved. B, they have to be solved. B, they have to be solved. using Sam, it is okay, so one has two joined three, two have three joined punch, so here Sam has to be done, but this plus and minus operation is not to be done, so what are we going to do I have explained it I have explained it I have explained it well today, well today, let me explain it again a little, so let's go to the notebook, let me explain it again a little, so let's go to the notebook, first offer, first offer, so in this question, we have to so in this question, we have to find the sum of Van and Tu, which is 3. If find the sum of Van and Tu, which is 3. If we cannot get through addition, then we know we cannot get through addition, then we know bitmapulation. then what we can do is that we then what we can do is that we can see the observation that if we sum zero can see the observation that if we sum zero then the answer comes zero, if we sum van and van then the answer comes zero, if we sum van and van then the answer comes zero and above if we sum then the answer comes zero and above if we sum van and zero then it comes -If it is a different number then the answer is A. -If it is a different number then the answer is A. -If it is a different number then the answer is A. If it is a different number then the answer is zero. If it is a different number then the answer is zero. In which case does this happen? You must remember that it In which case does this happen? You must remember that it is in the case of tide, is in the case of tide, first thing, what are you going to reduce, first thing, what are you going to reduce, second thing, how to handle the scary thing, this carry second thing, how to handle the scary thing, this carry also. also. also. that we are adding to it, we are doing one shift ahead of it i.e. we are doing it on the left side, one thing you are looking at is that 'A' is being added only in the case of Van and Van, So, So, So, which is such a table? Do you remember that which is such a table? Do you remember that if both of ours are van then we can make it only because of the end, then it means [Music] If we [Music] If we shift to the left side, then one shift to the left side, then one We have understood the thing. We have understood the thing. Example So, if N is added to the eighth, then So, if N is added to the eighth, then what can we do for 1000, what can we do for 1000, 8 will be 8 will be 123 123 8910, it is from zero to zero, so what is our answer [Music] [ Correct. Correct. Correct. I will see both of them and will continue to do such operation till our carry becomes zero. Okay, let's it for the last one and shift together. it for the last one and shift together. Stop these two. Stop these two. Stop these two. carry, see in which car they are coming, just by looking here it is clear that the carry is coming because of the van and the van, if you had put a carry here, if you had put a carry here, then I wrote ka di and there are I wrote ka di and there are I wrote ka di and there are two zeros in front of it, there are two zeros behind it, so two zeros in front of it, there are two zeros behind it, so put carry, zero, zero 16 8 4 2 1, so 16 + 4, how much is it, it is 20, if if if code is there, so what will we do, we will make the key in C plus plus, which will it will be evening, now we have to remove the carry also, so it will be evening, now we have to remove the carry also, so carry is written here, now I am going to return here. now I am going to return here. now I am going to return here. will fix the return for Sam and Carry. If I also tell you what to do, then what will be our base case of initial K for return, if our carry which is or B which is becomes zero, If this happens then a similar If this happens then a similar If this happens then a similar case will happen that case will happen that if the person is busy then the returns will not be given if the person is busy then the returns will not be given because I had because I had shown you how by doing this, we are doing zero in shown you how by doing this, we are doing zero in The Carry, The Carry, so just run it and submit it and see, you can do it directly from there. Just for today, see you Just for today, see you in the next class. | 2024-03-24 11:33:41 | 371 | Leetcode 371. Sum of Two Integers. Bit Manipulation [C++ / Java] |
|
RQZgYCyWdPs | okay 35th task of flip code to search insert position insert position okay we have sorted array in the new okay we have sorted array in the new element and we should either find it element and we should either find it or we should give a position in which we or we should give a position in which we would insert it would insert it so that we can keep the sortedness of so that we can keep the sortedness of the array the array so so this time would use std lower bound this time would use std lower bound okay so okay so sorry sorry the lower bound will the lower bound will give us give us the position the position of the first element that of the first element that is not less than the current target is not less than the current target so if it is not less than it means so if it is not less than it means either we have already found it so that either we have already found it so that is going to be the position itself is going to be the position itself because we because we found the target found the target or it is the law the location after or it is the law the location after which we have to insert it which we have to insert it so in so in in both of the cases the the returning value is numbers that begin in the same so let's run oops not equal minus submit submit okay okay and we're done | 2024-03-20 08:53:04 | 35 | LeetCode 35 Search Insert Position |
|
7aa13a9uKeo | A Azam is going to call list d4 extra bittu is a st andrews extra bittu is a st andrews questions statement you are you want to identical questions statement you are you want to identical addition you have access to now addition you have access to now building with and plural form 121 that building with and plural form 121 that vinod were juice of lower left strong 90 vinod were juice of lower left strong 90 slide and drop test very slide and drop test very Beneficial Beneficial That An Alarm Clock Set And Billu Slow App That An Alarm Clock Set And Billu Slow App Will Not Take Any Movement And Broken And Will Not Take Any Movement And Broken And Dropped From Any Elections When Someone To Dropped From Any Elections When Someone To Admire You Can Not Love You Can Avoid However When Did Admire You Can Not Love You Can Avoid However When Did Not Being Human Resource Center Not Being Human Resource Center Forum Us Written On Winning Numbers Of Units Forum Us Written On Winning Numbers Of Units Forum Us Written On Winning Numbers Of Units determine the wishes when the value of our subscriptions, we have to tell the minimum number of which it is, that is, we have to point out that the DMK plot number is to send the minimum number of movements so that both of us remove our egg and mine That explanation and they have to dorm us this That explanation and they have to dorm us this That explanation and they have to dorm us this if we had testis given to if we had testis given to us number of loss to change then in this us number of loss to change then in this we have to take at least two tons we have to take at least two tons to treat that which flourished to treat that which flourished eye drop back Siddhant Sharma is the worst thing from eye drop back Siddhant Sharma is the worst thing from Unknown number one and all Unknown number one and all half inch so that we first of all from you people half inch so that we first of all from you people jo point se prince vinod episode 202 jo point se prince vinod episode 202 ruk agar save my number we need to bring it down us ghr ruk agar save my number we need to bring it down us ghr ghr me ghr me a b c baat hai otherwise Bebo surviving a b c baat hai otherwise Bebo surviving terrorist terrorist terrorist prostitute who was followed by which both of them are the most minutes on the same from the same both of them Pune otherwise 0 4 but the cervical friend is a similar abstinence has happened now we understand it through a sketch and do something like if we have that Given minutes, we have Given minutes, we have Given minutes, we have given employees and we have to tell given employees and we have to tell which buffaloes, how much minimum number of which buffaloes, how much minimum number of moons we should take so that the increase in this will be known moons we should take so that the increase in this will be known which red chilli I have given it, if which red chilli I have given it, if we will not do it on both Androids then like we are here if my we will not do it on both Androids then like we are here if my we will not do it on both Androids then like we are here if my value of these is one, if I have one and we have to find out, you used to try Domax on all the fruits, Kunwar, now these people do business that first from their side, they try it on this fruit with Striker, Isn't it Isn't it Isn't it that we are some ware trend, you vote and there is a that we are some ware trend, you vote and there is a front part on it, there is nothing like this, you are a front part on it, there is nothing like this, you are a network, there is gourd in the market, wed 21 network, there is gourd in the market, wed 21 subscribe, this is the noose which is here, if it swells from here, subscribe, this is the noose which is here, if it swells from here, then I am going to subscribe, if then I am going to subscribe, if I had it, I would I had it, I would I had it, I would my don't do that if I have 2 eggs and to support I have and key value to so thank you thank you to so support I am trying with decisions right now so So So So I can have only two options here, I can have only two options here, if I have a particular item, either that if I have a particular item, either that exam duck will not break after falling, or it will exam duck will not break after falling, or it will fly away, if one of mine bursts, to support it, fly away, if one of mine bursts, to support it, in this case, I only in this case, I only dropped that one and my dropped that one and my dropped that one and my check for the other welding machine. Solid and on top of that, there is no need to check. Firstly, how did this happen? Secondly, if one of mine did not break, then we know that there will be Now Now Now we need to check on this, then we must have we need to check on this, then we must have seen that it is possible that it is a fraud and seen that it is possible that it is a fraud and if I don't have a break, then I if I don't have a break, then I will get bigger by adding my answer once, will get bigger by adding my answer once, because I took a chance here or because I took a chance here or click on it with fiber. click on it with fiber. click on it with fiber. we will have to make it, so we are taking a chance on it, only after seeing our size 11, the out will be less but we will take one from me to do this vitamin, please You see in the time manner, You see in the time manner, You see in the time manner, hey, if you drop two exams from the floor, hey, if you drop two exams from the floor, if you drop one from any explorer, then you should get Amazon My and Twitter, if my means will be then you should get Amazon My and Twitter, if my means will be less than 11, then less than 11, then here is a two-man promise. here is a two-man promise. here is a two-man promise. in explorer, if it agrees, I will have to put The The fold is just my is fold is just my is not fair subscribe on top of that and not fair subscribe on top of that and this which after we do this let me take you one this which after we do this let me take you one step so subscribe me on this side of yours and make it under your control so It is It is It is not that I am first class 10, not that I am first class 10, my one month may be broken, maybe my my one month may be broken, maybe my class is very bad, I have to fry all the rolls, class is very bad, I have to fry all the rolls, so how in this situation, we have to minimize our max, so how in this situation, we have to minimize our max, so so basically there is one problem or two in this. basically there is one problem or two in this. So I have a great tax and So I have a great tax and my A is not making a break. Now please tell me that my A is not making a break. Now please tell me that tomorrow I need the account statement but the culprit is important - attention - please call. How am I depositing both of them right now In that we have to take one strip, In that we have to take one strip, In that we have to take one strip, because we are taking one strip, that's why because we are taking one strip, that's why I am checking on it that the I am checking on it that the illusion is breaking below, we have to go up, so we will illusion is breaking below, we have to go up, so we will add one on this side in our step, we will add one on this side in our step, we will see it as body part. see it as body part. see it as body part. do it in the same manner by taking the land and then we will mash it, then first of all we pick up a return phone and in it the number of players and the number of unity are two, then we pass it to him, after that we take leave and Let's define it and Let's define it and loot it in front of the country. First of all, we will understand that if we are troubled at home, then we are one because I have saffron in it, so I would have taken it last but I will try to ignore it. Must be that one of my pistols Must be that one of my pistols Must be that one of my pistols and is selecting on this Lokesh Bhai is and is selecting on this Lokesh Bhai is not doing you direct oil riders not doing you direct oil riders function and country but if my Android does function and country but if my Android does not do it Ameer did the same then I add a not do it Ameer did the same then I add a reminder to take meaning - 102 and The number is A and while doing this we have to think about the maximum of his account that maybe my condition is bad and we have to check all the plants and after doing this we will add it to A. Because we are taking a chance to check that the withdrawal business and whatever answer is coming after maximizing them, it is clear to us that it is minimized, this is my phone that whatever my dominance dominance we have to remind him of that. After we will return to our dream answer the complaint of this constipation we told that hey I have one leg only one till it thinks that whatever number of mp from plants I have if that then As for me, I have given as many as two or as many As for me, I have given as many as two or as many As for me, I have given as many as two or as many three processors as 321, we will have to three processors as 321, we will have to take ads on all of them and try to try, if take ads on all of them and try to try, if this goes, then if I have one this goes, then if I have one end left, then I need to try all the remaining end left, then I need to try all the remaining clothes clothes because in the awards case, we may have because in the awards case, we may have All the remixes have to be checked. Let's All the remixes have to be checked. Let's see the syllabus on the address which is saying that the time limit is exceeded, which side is brother, which picture is sex, then they have seen 220 kiss wrong, e Agri Gyanpeeth type will go to the end yes, this is correct. that hindi mistress is in vitamin c turmeric red chilli a table was happened happened i just i just with sexual force with sexual force again mesh mean that this i again mesh mean that this i india made in this india made in this which request closed organization which request closed organization that and guy that and guy a folder answer a folder answer After all, After all, this pattern mobile religious and 350 Bluetooth this pattern mobile religious and 350 Bluetooth on week shoulder 1108 song that this return gift heroic arrangement sentence white laker to half hour time solid to memory soft quarter inch 100 latest quality went back yes I am 100 number of 1200 engineer Security cutting tax dip length the ripper Security cutting tax dip length the ripper Security cutting tax dip length the ripper edifice and definition of birth - but edifice and definition of birth - but that you are scientific that you are scientific and after this we have to decide which and after this we have to decide which free computer stage we have avoided free computer stage we have avoided then we have to decide if I have then we have to decide if I have answered any other floor worthy already answered any other floor worthy already answered any other floor worthy already then the answer is A, we will return it, there is no need to go ahead and check, you finally give me whatever my DP and deposit will be, now I will match it in my 162 league, on both sides of the road Tags English Meaning of Romance Tags English Meaning of Romance Tags English Meaning of Romance that Haridev Shastri that Haridev Shastri had a hint, I am typing in a person after seeing your every day or culture, tomorrow morning I will reply to it as a friend, thank | 2024-03-25 11:53:29 | 1,884 | 1884.Egg Drop with 2 Eggs and N floors |leetcode dp series|leetcode |
|
A1kbhbOCHlA | hi everyone welcome to sudokoda my name is raveena and today we are going to is raveena and today we are going to solve lead code problem number 42 which solve lead code problem number 42 which is trapping rainwater so let's start by is trapping rainwater so let's start by reading the question it says that uh reading the question it says that uh given non-negative integers representing given non-negative integers representing an elevation map where the width of each an elevation map where the width of each bar is 1 compute how much water it can bar is 1 compute how much water it can trap after raining so let's see an trap after raining so let's see an example here we have been given a list example here we have been given a list of height where there are all of height where there are all non-negative integers in there and uh non-negative integers in there and uh let's look at this height list as you let's look at this height list as you know the height of the buildings okay know the height of the buildings okay and then here if you look at this graph and then here if you look at this graph you'll see that all these black box uh you'll see that all these black box uh are the buildings and if it rains are the buildings and if it rains heavily uh you know how much water can heavily uh you know how much water can the can be trapped between these the can be trapped between these buildings so that's the question so if buildings so that's the question so if you see the between these two buildings you see the between these two buildings this uh blue thing here is the water this uh blue thing here is the water that has been trapped that has been trapped uh between these two there is water uh between these two there is water trapped in this t-shape and there's trapped in this t-shape and there's there's a small petal here okay so how there's a small petal here okay so how do we actually uh you know count the do we actually uh you know count the number of units that have been stored number of units that have been stored right so uh you'll see that each right so uh you'll see that each building is of one unit and if you look building is of one unit and if you look at it you know uh between these and this at it you know uh between these and this building there is one unit of water building there is one unit of water stored because it's off with one and stored because it's off with one and then the height of it is one so it's then the height of it is one so it's actually one if you come here if you actually one if you come here if you drop boxes around this T you'll know drop boxes around this T you'll know that you'll understand that there are that you'll understand that there are actually Four units of water here one actually Four units of water here one two three and then the bottom one which two three and then the bottom one which is four and then there's one right here is four and then there's one right here so how many it is one four and then one so how many it is one four and then one which is six and that is our output so which is six and that is our output so this is I hope this question was clear this is I hope this question was clear and let's move on to the notepad and see and let's move on to the notepad and see how we can solve this how we can solve this okay so I have taken an example the same okay so I have taken an example the same example where I have the height right example where I have the height right here and then I have drawn the graph here and then I have drawn the graph okay so uh how I'm gonna solve this okay so uh how I'm gonna solve this problem is by having two arrows with me problem is by having two arrows with me a left Max array and a right Max array a left Max array and a right Max array now what are these arrays so the left now what are these arrays so the left Max array is going to determine how much Max array is going to determine how much maximum water can I store when I go from maximum water can I store when I go from left to right left to right and the right Max either denotes how and the right Max either denotes how much maximum water can I store when I go much maximum water can I store when I go from right to left okay and then once I from right to left okay and then once I have those values what I'm going to do have those values what I'm going to do is I'm going to take the minimum of the is I'm going to take the minimum of the 2 and then you know uh subtract the 2 and then you know uh subtract the height from it now what does that mean height from it now what does that mean so for example so when you come from so for example so when you come from right to left suppose your maximum right to left suppose your maximum height is here and when you go from left height is here and when you go from left to right the maximum height is somewhere to right the maximum height is somewhere here and if we want to calculate the here and if we want to calculate the amount of water that has been stored amount of water that has been stored right here in this particular unit so right here in this particular unit so what's going to happen is you're gonna what's going to happen is you're gonna be subtract you you're going to be be subtract you you're going to be taking the minimum of the two because taking the minimum of the two because the amount of water that is that will be the amount of water that is that will be stored will be based or if there is a stored will be based or if there is a building that is you know that is building that is you know that is smaller than the bigger building then smaller than the bigger building then the water store will be dependent on the the water store will be dependent on the smaller one and that is why we are going smaller one and that is why we are going to take the minimum of it and then if to take the minimum of it and then if that's true then we take the minimum fit that's true then we take the minimum fit minimum of it and we see that there is minimum of it and we see that there is water stored here but you will see that water stored here but you will see that there's a building right here so we have there's a building right here so we have to subtract the building as well so to subtract the building as well so that's an overview of the problem let's that's an overview of the problem let's really see how we can solve this so the really see how we can solve this so the first thing I have I need is my left Max first thing I have I need is my left Max array okay and how I'm gonna calculate array okay and how I'm gonna calculate it the first thing I need to do is it the first thing I need to do is initialize it with 0 so I'm going to initialize it with 0 so I'm going to initialize my whole thing with 0 and initialize my whole thing with 0 and then I am going to have the first then I am going to have the first element of my array as the first element element of my array as the first element of my height so I'm going to take the of my height so I'm going to take the first element as 0 why because there is first element as 0 why because there is nothing on the left hand side so ah for nothing on the left hand side so ah for the margin I need to have something the margin I need to have something solid on my left where I have to start solid on my left where I have to start from and so I'm going to take the first from and so I'm going to take the first element of my height element of my height now I'm gonna calculate it I I'm gonna now I'm gonna calculate it I I'm gonna calculate the left Max area is by taking calculate the left Max area is by taking the maximum of the current height of the the maximum of the current height of the building and the previous height of the building and the previous height of the building so since I am calculating the building so since I am calculating the heights as I'm moving forward from left heights as I'm moving forward from left to right the previous height will be to right the previous height will be from my left Max array and then I am from my left Max array and then I am going to take the maximum of my left Max going to take the maximum of my left Max arrays previous height and my current arrays previous height and my current height so let's see so I'm going to take height so let's see so I'm going to take maximum of 0 and 1. so maximum of 0 and maximum of 0 and 1. so maximum of 0 and 1 is 1 so it becomes 1. now I take a 1 is 1 so it becomes 1. now I take a maximum of 0 and 1 again the maximum is maximum of 0 and 1 again the maximum is 1. I take maximum of 2 and 1 which is 2 1. I take maximum of 2 and 1 which is 2 so it becomes 2 maximum of 0 and sorry 1 so it becomes 2 maximum of 0 and sorry 1 and 2 is 2 then I again take maximum of and 2 is 2 then I again take maximum of my previous uh building and then my my previous uh building and then my current so 0 and 2 is 2. now 2 and 1 is current so 0 and 2 is 2. now 2 and 1 is 2 maximum of 3 and 2 is 3 2 and 3 is 3 2 maximum of 3 and 2 is 3 2 and 3 is 3 and then 3 and 1 maximum is again 3 3 and then 3 and 1 maximum is again 3 3 and 2 maximum is 3 and then 1 and 3 and 2 maximum is 3 and then 1 and 3 maximum is 3. so I've calculate my left maximum is 3. so I've calculate my left Max array it's basically maximum of what Max array it's basically maximum of what is the current height and the previous is the current height and the previous building based on the maximum array that building based on the maximum array that I'm calculating I'm calculating so that is my left array now let's talk so that is my left array now let's talk about my right array so I am going to about my right array so I am going to initialize my right array initialize my right array and what I'm gonna do I'm for my right and what I'm gonna do I'm for my right area I'm gonna move from right to the area I'm gonna move from right to the left and for the right hand side I'm left and for the right hand side I'm going to initialize it with the last going to initialize it with the last element of the height similar thing that element of the height similar thing that we did with the left left array since we we did with the left left array since we did not have anything on the left we did not have anything on the left we took the first building now since we took the first building now since we don't have anything on the right we will don't have anything on the right we will take the first value from the right take the first value from the right now I'm gonna do a similar thing I'm now I'm gonna do a similar thing I'm going to take the maximum of the going to take the maximum of the building on my right and the current building on my right and the current building so let me get rid of these building so let me get rid of these markers here markers here okay so I'm going to take maximum of 1 okay so I'm going to take maximum of 1 and 2. what is that that is 2. now I'm and 2. what is that that is 2. now I'm going to take maximum of 1 and 2 which going to take maximum of 1 and 2 which is 2 maximum of 2 and 2 is again 2 is 2 maximum of 2 and 2 is again 2 maximum of 3n is going to be 3 maximum maximum of 3n is going to be 3 maximum of 1 and 3 is going to be 3 0 and 3 is of 1 and 3 is going to be 3 0 and 3 is going to be 3 maximum of 1 and 3 is going to be 3 maximum of 1 and 3 is again 3 2 and 3 maximum is 3 again 3 2 and 3 maximum is 3 0 and 3 is maximum 3 1 and 3 is maximum 0 and 3 is maximum 3 1 and 3 is maximum 3 and lastly 0 and 3. the maximum here 3 and lastly 0 and 3. the maximum here is 3. is 3. so now I have so now I have now I have my left and right array what now I have my left and right array what I need to do next is to calculate my I need to do next is to calculate my answer now let I'm gonna quickly draw answer now let I'm gonna quickly draw and show you what the left and Max left and show you what the left and Max left Max and right Max is really Max and right Max is really okay so uh let's draw the left Max array okay so uh let's draw the left Max array first first it's starting at 0 okay it's going to it's starting at 0 okay it's going to one cool it's staying to one one okay one cool it's staying to one one okay and then it's going to 2 and then it's and then it's going to 2 and then it's staying two for four blocks and then staying two for four blocks and then again it goes to three and then stage 3 again it goes to three and then stage 3 till the end so this is what the left till the end so this is what the left Max array looks like now let's draw on Max array looks like now let's draw on the right Max array the right Max array the right Max array the right Max array actually starts at three oh sorry my actually starts at three oh sorry my right my side actually starts at one so right my side actually starts at one so one and then it goes to two so it goes one and then it goes to two so it goes to 2 and then stays for two for three to 2 and then stays for two for three instances and then it goes to three and instances and then it goes to three and then it stays three till the end so it then it stays three till the end so it stays three till here okay so let's see stays three till here okay so let's see what's happening my left Max is the one what's happening my left Max is the one in purple my right Max is the one in in purple my right Max is the one in Orange now if I have to calculate how Orange now if I have to calculate how much water is stored what do you think I much water is stored what do you think I have to do uh if you'll see that have to do uh if you'll see that sometimes the orange marking is the one sometimes the orange marking is the one that is closest sometimes the purple that is closest sometimes the purple marking is the one that is closest so marking is the one that is closest so what do we do we take the minimum of the what do we do we take the minimum of the two when we take the minimum of 2 we two when we take the minimum of 2 we will be able to get to the lowest line will be able to get to the lowest line and in order to calculate the water so and in order to calculate the water so for example let me do this for example let me do this let me draw it out so this is my or the let me draw it out so this is my or the orange part is my uh left may I write orange part is my uh left may I write Max and my left Max if I take minimum of Max and my left Max if I take minimum of the two I the two I end up with my purple line okay so I end end up with my purple line okay so I end up with this particular block here up with this particular block here okay I'm getting very bad at this I'm okay I'm getting very bad at this I'm getting this particular block here does getting this particular block here does that mean that this is all water that mean that this is all water um no why why because this there is a um no why why because this there is a building here it's right here this is building here it's right here this is the building the building so what we have to do is we have to take so what we have to do is we have to take minimum of my right and left and then we minimum of my right and left and then we have to subtract the height of the have to subtract the height of the building so if we do that then we'll see building so if we do that then we'll see that there's water here which is that there's water here which is actually the correct thing did you saw actually the correct thing did you saw that t thing in the example below that's that t thing in the example below that's the left part of it the left part of it so this is going to be the water and so this is going to be the water and that's how the formula works so what's that's how the formula works so what's the formula the formula initially my formula is going to be my initially my formula is going to be my minimum of left and right and then I'm minimum of left and right and then I'm going to subtract my height so initially going to subtract my height so initially my answer is going to be 0 my answer is going to be 0 and and my answer is going to be 0. my answer is going to be 0. and now let's work through it so it's and now let's work through it so it's going to be minimum of left and right so going to be minimum of left and right so minimum of 0 and 3 which is 0 minus the minimum of 0 and 3 which is 0 minus the height which is 0 0 minus 0 minimum is 0 height which is 0 0 minus 0 minimum is 0 and 0 is 0 and 0 minus zero is zero so and 0 is 0 and 0 minus zero is zero so it's gonna be zero okay so minimum of 1 it's gonna be zero okay so minimum of 1 and 3 is 1 and the height of the and 3 is 1 and the height of the building is also 1 so 1 minus 1 0 okay building is also 1 so 1 minus 1 0 okay now minimum of 1 and 3 is again 1 but now minimum of 1 and 3 is again 1 but this time the height of the building is this time the height of the building is zero so one minus zero one so I'm gonna zero so one minus zero one so I'm gonna add one add one now minimum of two and three is two and now minimum of two and three is two and then minus two so two minus 2 is 0. okay then minus two so two minus 2 is 0. okay so minimum of 2 and 3 is 2 minus 1 so it so minimum of 2 and 3 is 2 minus 1 so it becomes one becomes one okay plus minimum of two and three two okay plus minimum of two and three two again and then minus 0 so it becomes 2. again and then minus 0 so it becomes 2. minimum of 2 and 3 is 2 minus 1 which minimum of 2 and 3 is 2 minus 1 which becomes 1 so this becomes 1. minimum of becomes 1 so this becomes 1. minimum of three and three is three three and three is three minus 3 0 so it's becomes zero minus 3 0 so it's becomes zero now minimum of 3 and 2 is 2 2 minus 2 0 now minimum of 3 and 2 is 2 2 minus 2 0 minimum of 3 and 2. minimum of 3 and 2. is 2. 2 minus 1 is actually one so one is 2. 2 minus 1 is actually one so one now minimum of 3 and 2 is 2 minus 2 is 0 now minimum of 3 and 2 is 2 minus 2 is 0 and the minimum of 3 and 1 is actually 1 and the minimum of 3 and 1 is actually 1 and minus the height which is 1 so 0. so and minus the height which is 1 so 0. so let's see what our answer is it's one let's see what our answer is it's one plus one two plus one two plus two four plus two four plus one five and then six so our answer plus one five and then six so our answer comes out to be 6 and that is what we comes out to be 6 and that is what we are expecting that is the solution so I are expecting that is the solution so I hope this explanation was clear let's hope this explanation was clear let's see how we can convert this into code see how we can convert this into code first things first though we have to first things first though we have to look for any edge cases now this problem look for any edge cases now this problem did not talk about the constraints where did not talk about the constraints where you know length of the height cannot be you know length of the height cannot be zero so first thing that we have to zero so first thing that we have to think is if my height list is 0 then think is if my height list is 0 then what do I have to do I have to return 0 what do I have to do I have to return 0 because there will be no water okay so because there will be no water okay so that's what I'm going to do first I'm that's what I'm going to do first I'm going to uh actually store my length of going to uh actually store my length of height height in a variable because I'm going to use in a variable because I'm going to use it multiple times that is a very good it multiple times that is a very good practice that you can do oops I think practice that you can do oops I think I'm doing something wrong yeah so there I'm doing something wrong yeah so there is a best practice that you can do if is a best practice that you can do if you are using a variable again if you're you are using a variable again if you're calculating something again and again calculating something again and again store it in a variable store it in a variable so I have my length n now I'm going to so I have my length n now I'm going to check if n is less than 1 then I am check if n is less than 1 then I am going to return 0. now I have to for uh how many things do I need I need three things I need my answer I need my left Max array I need my right Max array so I'm going to initialize my answer to 0. my left Max array is going to be initialize to 0 with length n similarly my right Max array is going to be initialized to 0 with length n now I have this I have now I will start calculating my left Max array for starting for starters I have to initialize the first element of a left Max with the first element of my height so I am going to do that I'm going to do left Max of 0 is going to be my height of 0. and then I write a for Loop starting from the first element from the first index going to the end so I do for I in range starting from 1 going till n minus 1 and since it is python it's going to exclude that last last part so it's gonna even if I'm writing n it's n minus 1 and then I am going to calculate my left Max my left Max of I is nothing but left Max of my left Max of I minus 1 this is the previous building minus my current height okay now that's all my left Max is done let's try it and do it the right part of it so my right Max is uh my right Max's last element is going to be my Height's last element and in Python you can write just minus 1 to get the last element so that's that and then I'm going to write my for Loop ranging from so I have to start with my second last item similarly how for the left left array I started with my second item right so I'm gonna start with my second last item here so it's going to be n minus 2. I have to go till zero and since the last thing is excluded last index is excluded I'm going to write minus 1 and for every iteration I have to subtract minus one so that's how you write for Loop in Python and then I am going to do write Max of my I is going to be really Max of my right Max of I plus 1 so maximum of the so that's all my right Max is calculated so that's all my right Max is calculated now so now finally I have to calculate now so now finally I have to calculate my answer so for that I have my I in my answer so for that I have my I in range going from 0 to n range going from 0 to n I am going to calculate my answer my I am going to calculate my answer my answer is going to be answer plus my answer is going to be answer plus my minimum of my left Max minimum of my left Max of I my right Max of I okay in the end okay in the end I'll return the answer I'll return the answer let's see if we can run it let's see if we can run it okay let's submit okay let's submit okay yeah so you see this solution was okay yeah so you see this solution was accepted now let's talk about the space accepted now let's talk about the space and time complexity of this problem so and time complexity of this problem so uh if you talk about the space uh if you talk about the space complexity you can see that we are using complexity you can see that we are using three for Loops here which are not three for Loops here which are not nested they are independent so each time nested they are independent so each time the space complexity is n plus n plus n the space complexity is n plus n plus n which is 3n and then we drop the which is 3n and then we drop the constant so the time complexity of this constant so the time complexity of this is O of n is O of n now let's talk about the space now let's talk about the space complexity how much space are we using complexity how much space are we using we have a variable here we have a variable here we have a variable here which is which we have a variable here which is which stores constant and then my left and stores constant and then my left and right Max which is actually an array of right Max which is actually an array of size n and what is this n n is the size n and what is this n n is the length of the height length of the height so it's going to be o of 1 plus o of n so it's going to be o of 1 plus o of n plus o of n which is going to be 1 plus plus o of n which is going to be 1 plus 2 N and uh if you know that you know in 2 N and uh if you know that you know in time and space complexity we actually time and space complexity we actually drop the constants so the space drop the constants so the space complexity of this becomes o of n if you complexity of this becomes o of n if you don't know how to calculate space and don't know how to calculate space and time complexity I have created a video time complexity I have created a video on it uh I think two weeks before I will on it uh I think two weeks before I will include the link in the description include the link in the description below and you can refer that it will be below and you can refer that it will be much easier to calculate space and time much easier to calculate space and time complexity if you watch that video so uh complexity if you watch that video so uh to conclude it the space and time to conclude it the space and time complexity of this particular algorithm complexity of this particular algorithm is O of n if you like my videos give it is O of n if you like my videos give it a thumbs up comment below if you want me a thumbs up comment below if you want me to solve any additional problems of your to solve any additional problems of your choice please let me know in the choice please let me know in the comments below you can also connect with comments below you can also connect with me on my Discord and let me know there me on my Discord and let me know there you want to see similar videos from me you want to see similar videos from me please subscribe to my channel uh so please subscribe to my channel uh so that it can give you a notification that it can give you a notification every time I upload a new view I upload every time I upload a new view I upload videos every week videos every week so have a nice day and I will see you so have a nice day and I will see you next time thank you bye | 2024-03-20 09:21:05 | 42 | Leetcode 42. Trapping Rain Water (Python) |
|
D6zucvsR2Tg | hello everyone welcome to the backtracking series of videos backtracking series of videos so in the previous video i have so in the previous video i have explained the permutation 1 problem so explained the permutation 1 problem so in this video i will explain permutation in this video i will explain permutation 2 problem and the problem number is 47 2 problem and the problem number is 47 so the problem statement is saying given so the problem statement is saying given a collection of numbers norms that might a collection of numbers norms that might contain duplicates return all possible contain duplicates return all possible unique permutations in any order unique permutations in any order so suppose one array is given to you so suppose one array is given to you that has duplicate numbers one one two that has duplicate numbers one one two you have to find all the permutations you have to find all the permutations like 1 1 2 will be a result then 1 2 1 like 1 1 2 will be a result then 1 2 1 and 2 1 1 and 2 1 1 so uh in some examples maybe there is no so uh in some examples maybe there is no repetitive numbers so that case also 1 2 repetitive numbers so that case also 1 2 3 has this many combinations 3 has this many combinations so how is this problem is different from so how is this problem is different from permutation one problem that is in permutation one problem that is in permutation one problem there were no permutation one problem there were no duplicates duplicates that's why it was easy to handle but in that's why it was easy to handle but in this case you have to handle the this case you have to handle the duplicate case also because 1 1 2 1 2 1 duplicate case also because 1 1 2 1 2 1 2 1 1 all are different combinations 2 1 1 all are different combinations how to solve that thing now we'll check how to solve that thing now we'll check but before that i will highly recommend but before that i will highly recommend you to go to the video permutation one you to go to the video permutation one because because that logic is almost similar we will use that logic is almost similar we will use here let's take one example numbers here let's take one example numbers array which has duplicate numbers like array which has duplicate numbers like one one two three three one one two three three and we have to create all the and we have to create all the permutations of this numbers array permutations of this numbers array before that we will do a quick recap before that we will do a quick recap like what we did for permutation one like what we did for permutation one so in permutation one we have one array so in permutation one we have one array where only distinct values are there where only distinct values are there like 1 2 3 like 1 2 3 and we draw one decision tree out of it and we draw one decision tree out of it and this was looking like this and this was looking like this so what we are doing for this decision so what we are doing for this decision tree tree so basically what we are doing is first so basically what we are doing is first we are starting with one number we are starting with one number then then that number we are keeping that number we are keeping in a in a list list and that list will have three as a and that list will have three as a length then only we can collect that as length then only we can collect that as a result a result next time if we have to choose anything next time if we have to choose anything then we have to make choice apart from then we have to make choice apart from one because one is already taken one because one is already taken so that's why we choose between two and so that's why we choose between two and three but first time we went with two three but first time we went with two now we fill the second position also now we fill the second position also for third position what are the choice for third position what are the choice left for us that is three left for us that is three because because three don't contains in this list three don't contains in this list but two and one already contents so but two and one already contents so that's why three that's why three was left as a choice for us was left as a choice for us so every time when we are going forward so every time when we are going forward we are checking that in the list we are checking that in the list this item which i am going to include is this item which i am going to include is already present or not already present or not if it is not present then i will make if it is not present then i will make use of it as a choice use of it as a choice so as only distinct numbers was there so as only distinct numbers was there that's why it was easy for permutation that's why it was easy for permutation one one because in the growing because in the growing list we were just checking if the list we were just checking if the current number is already included or current number is already included or not by doing a not by doing a list dot contents list dot contents right right but the same logic we can't apply here but the same logic we can't apply here for duplicate case for duplicate case because ultimately we have to make use because ultimately we have to make use of all the numbers like of all the numbers like 2 1 1 2 1 2 3 2 1 1 2 1 2 3 in this case if we do a list dot in this case if we do a list dot contents then what will happen is contents then what will happen is suppose first suppose first value is there value is there and if we check that and if we check that other values we can include or not this other values we can include or not this one we will not take because this list one we will not take because this list already contains one already contains one so that time so that time we have to omit this one we have to omit this one but that will produce a wrong result but that will produce a wrong result instead of that instead of that what we have to do is what we have to do is we have to keep count of all the we have to keep count of all the distinct numbers and we have to check distinct numbers and we have to check like how many time i have used that one like how many time i have used that one if they have still count then i can if they have still count then i can again make use of that again make use of that suppose for a growing list i have used suppose for a growing list i have used one once one once that means next time again i have choice that means next time again i have choice to use one two and three to use one two and three because one is because one is one time used still i have left one one one time used still i have left one one so when that will also be used so after so when that will also be used so after one i have used another one one i have used another one that time one is already fully used so that time one is already fully used so that time i have a choice to use 2 and 3 that time i have a choice to use 2 and 3 because they have count still greater because they have count still greater than 0. than 0. so so what kind of data structure will help us what kind of data structure will help us to keep the distinct numbers and their to keep the distinct numbers and their count count obviously the choice will be a hash map obviously the choice will be a hash map so we will take one hashmap first and we so we will take one hashmap first and we will build this map will build this map like what are the like what are the distinct numbers are there and how many distinct numbers are there and how many times they are available times they are available then we will then we will do our decision tree and structure it do our decision tree and structure it that we will see next so now we will that we will see next so now we will tackle this problem so numbers array tackle this problem so numbers array from there first i created the map where from there first i created the map where it is saying what are the distinct it is saying what are the distinct elements are there and how it is their elements are there and how it is their count count so one is present two times two is so one is present two times two is present one time and three is present present one time and three is present two times two times so if we start from here so if we start from here the decision is we can use either one the decision is we can use either one two and three so i can start with one or two and three so i can start with one or i can start with two i can start with two or i can start with three or i can start with three let's say first start with one let's say first start with one then in the next level what are the then in the next level what are the elements i can use elements i can use so if i already used one so if i already used one then that will be reduced then that will be reduced by count one by count one so it will be now one so it will be now one now i have to check how many other now i have to check how many other possibilities are there which is greater possibilities are there which is greater than 0 than 0 all are possible because everyone is all are possible because everyone is present greater than 0 present greater than 0 so from here i have taken decent to use so from here i have taken decent to use either 1 either 1 or 2 or 3. now let's say i started with another one so this one will become zero because so this one will become zero because this is fully used this is fully used so next time i have choice only to use 2 so next time i have choice only to use 2 and 3 because they are greater than 0 and 3 because they are greater than 0 so i can use 2 so i can use 2 or 3 let's say if we started with 2 then what will happen 2 also i have to reduce so it will become 0 now what choice i have only i can use 3 so i have to use 3 here then 3 will be reduced to now next what choice i have now next what choice i have which one is greater than 0 only 3 so i which one is greater than 0 only 3 so i have to take another 3. and as the count is now five so we collected one result and that will be one one two three three right now how i'll get the other combinations so now we have to check that from here we don't have anywhere to go so we have to backtrack here here also no other junctions created so we have to backtrack to here till and while we are doing backtracking from here onwards i have to go to the other part so this two three and three will be again available so i have to like put it back right so this is where backtracking work also so now i have like three two three is there but one is completely used because one but one is completely used because one and 1 is already there and 1 is already there so second time i can use so second time i can use 2 and 3 again but 2 is already used in 2 and 3 again but 2 is already used in this path so i can use 3 here this path so i can use 3 here and then as 3 is used so it will be 1. now from here what are the choice left so i can use either 2 or 3. cool if i go with 2 then 2 is used and it will become so so after this i have only choice to make as after this i have only choice to make as 3. 3. so if you look at now 1 1 3 2 3 this is so if you look at now 1 1 3 2 3 this is also a permutation also a permutation similar way in this case after 3 similar way in this case after 3 only 2 will be remaining so that i can only 2 will be remaining so that i can use use if you do continuously for the other if you do continuously for the other cases also you will get all the cases also you will get all the combinations combinations so so this is the way we have to use map this is the way we have to use map and we have to and we have to decrease or increase the ground to make decrease or increase the ground to make all the all the possible permutations possible permutations while going deep as a dfs while going deep as a dfs if i am going deep that time we have to if i am going deep that time we have to reduce the counts from the map reduce the counts from the map while coming back or while doing a back while coming back or while doing a back tracking tracking so whatever things is again available we so whatever things is again available we have to have to like increase the count for that like increase the count for that i hope you understood this one i hope you understood this one now we'll see the coding now we'll see the coding so now here we will talk about the so now here we will talk about the solution solution the solution is simple maybe it is the solution is simple maybe it is looking longer code but it is very looking longer code but it is very simple simple so first what we have to do is this so first what we have to do is this method will be provided to us and we method will be provided to us and we have to additionally write one method have to additionally write one method for doing the for doing the dfs call dfs call so first what we will do is we have to so first what we will do is we have to define a list of list of integer result define a list of list of integer result because that is our return type because that is our return type and then we have to define a map as i and then we have to define a map as i told told and in the map we have to and in the map we have to take all the distinct numbers and their take all the distinct numbers and their count so this is a very common code used count so this is a very common code used in every program in every program right to take the number and its count right to take the number and its count now we have to do a dfs call where i now we have to do a dfs call where i have to pass the numbers array have to pass the numbers array then the then the result result and the new error list and map and the new error list and map so if we look here uh so if we look here uh this numbers array only we are using to this numbers array only we are using to take its length so you can directly pass take its length so you can directly pass the length also no need to pass the the length also no need to pass the whole number sorry whole number sorry now what we have to do is in the dfs now what we have to do is in the dfs call what we are doing is the best call what we are doing is the best condition to stop it is condition to stop it is if my list size is equal to the if my list size is equal to the numbers.length numbers.length that means we completely grown one that means we completely grown one result result then we have to collect that as a result then we have to collect that as a result and as a new error list and as a new error list and we have to destroy the and we have to destroy the like link or reference because java is like link or reference because java is passed by reference now what you have to do is we have to iterate over every key so we are iterating on the map for every key so we are getting the key and value out of the set entry set and you are checking if the value is greater than 0 or not that means for this particular number is there any count left or not if it is there then we are adding it to the list which is my running list where we are collecting the current result and then we are doing a map dot put the value minus 1 that means we are reducing that as a count because just now we use that one and we are doing again a dfs call to go to the next level and passing the same things after finishing the dfs call when we are coming back or doing a backtracking that time we are removing that element means the last element from the list and as well as we are increasing the count also because now that particular number is again available in the map so for that key we have to increase the count also by 1 and then if we do this thing repeatedly or recursively we will get all the combinations that we have to written as a result now if we submit it it is working | 2024-03-20 09:35:11 | 47 | Leetcode 47 | Permutations II |
|
nD-cJnduJ1M | hello there so let's look at the today's legal in China question it's called legal in China question it's called online stock span we need to implement a online stock span we need to implement a class stock spanner which will be class stock spanner which will be updated with daily stock prices and updated with daily stock prices and after the update you will be able to after the update you will be able to return the span of the stock's price of return the span of the stock's price of the current day the the definition for the current day the the definition for the span is as follows the maximum the span is as follows the maximum number of consecutive days starting from number of consecutive days starting from today and going backwards for which the today and going backwards for which the price of the stock was less than or price of the stock was less than or equal to today's price but that's quite equal to today's price but that's quite a mouthful so let's actually just maybe a mouthful so let's actually just maybe draw a picture about actual changes in draw a picture about actual changes in the stock price to work on a few example the stock price to work on a few example to see what you get and what you can to see what you get and what you can actually it's mean what actually means actually it's mean what actually means so we're gonna use the horizontal line so we're gonna use the horizontal line to indicating the phase so they want a to indicating the phase so they want a two days three something like this maybe two days three something like this maybe the stock price is rising in the the stock price is rising in the beginning and until day four is also beginning and until day four is also it's always increasing then maybe they it's always increasing then maybe they find it starts the job to a sudden job find it starts the job to a sudden job to some lower number than day six it's to some lower number than day six it's kind of stabilized and day seven is on kind of stabilized and day seven is on the rise again now let's think about if the rise again now let's think about if we just update it at a seven we want to we just update it at a seven we want to calculate this span it's basically if we calculate this span it's basically if we put a vertical line here ignore the put a vertical line here ignore the stuff on the right that's not counted stuff on the right that's not counted because we haven't see the new days yet because we haven't see the new days yet that's in the future we're just looking that's in the future we're just looking the left and we want to also pretty much the left and we want to also pretty much draw draw horizontal line that's draw draw horizontal line that's separating this today's price with the separating this today's price with the price that's larger than today's price price that's larger than today's price just go towards the left and and and and just go towards the left and and and and count how many of how many of those count how many of how many of those little bars we can have before we find a little bars we can have before we find a price that's a higher than this price that's a higher than this horizontal line so we find that we can horizontal line so we find that we can count three so we turn three for this count three so we turn three for this given day given day so then let's just looking at another so then let's just looking at another example maybe we continue on this stock monitoring the price of the stock for the 1/10 date night where the price just keep rising so for day eight the vertical line and the horizontal line would look like this so if we call into the number of little bars before we find something that's above the line will be four so if it has the span of the price for the day eight the span will be four let's just look at one last example let's say that we have really good quarterly reports the the price on day nine goes very high and so for that reason the bar would be even above this that means it's pretty much above anything then we count the number of bars towards the beginning so it's a one two three four five six seven eight nine so then we return nine so that's what the spamming it's basically having today's price as a cut off and looking towards the left until we find something that's higher than the cutoff we count the number of days in between that's the definition for spam so we have a little bit understanding about this if we look at pictures this is a little bit mouthful the example we have 180 60 70 60s 75 80 85 so it's decreasing going up so we can actually have something that's interesting on the day for here and going down again the pretty much resets because 70 there's nothing because we have something that's above the line on was settled by 70 so this resets to 175 the the bar rised of higher so we can actually take three and if 85 that's higher than the this five so the total is six so the the answer for this example is one one one two one four and six so that's the answer for this example so I guess the the book for solution is just going to be keep keep the whole thing and whenever we insert one thing we just look back until we find some price that's higher than today and just we just returned the number of elements so we look back to two as the spam that's just using the definition it's going to be slow because if we have a lot of stock prices numbers like huge numbers with potentially a lot of abundance every time we have to look back it's going to be worse it's not good so we need to something smarter so let's look at the picture again so if we are at a day day nine there's something that the day eight can provide us that that can ease our effort into looking back all the way day by day so there is actually something that we can do we can basically and they aid we summarize the despair for day eight and also the price for day eight so that's just because if we ever to have something that that were actually used is three days front day six to the eight to form a new span that this price is going to be at least a higher than or equal to day AIDS price so instead of the keeping track of these three values consecutive values for six to eight we can summarize that in two you know dates price let's just say it's sweet and we if you have something that's larger than the sweet price that's coming after the date you can effectively just directly add three days and the Skip list three go back to this day five here so that way we can sort of like doing compression along the way we process remembering this prices so another example would be if a day for instead of keeping track of day one day two day three day four we're gonna keep track of we're gonna compress this this upward trend to be the first price which is four and actually also have four days for whenever we have a downward trend then we couldn't really compress any more because those downwards are doing resets so for day 5 we're just gonna put five and one so with this we can instead of storing all the numbers in as it is we're doing a little bit compression so that when we look back the calculation can be much simpler so that's pretty much the idea behind this approach so to maintain this compression we can use a stock whenever we see something that's larger than Pryor's day we can basically compress the two days into one thing so just last example we have a one with price one and day two is price two so once we process the day two so initially when we just have they want we just put instead of only putting the single price there we put one and one that's the current span then when they - comes in which has a value of two we will pop this out and store to two in there because on day two and the price is two and the current span for that is two let's actually do some dumb words I guess if we have this way to be one again day to day one stuck at they - is this stuck at day three thinks that we are now having a downward they the span the continuously increasing span just to end it there we have to reset so the stack will be two two and online so yeah so the idea is just using a stack to keep track of the price Kasturi and we're going to do compression whenever we can when we do the compression is done when we have the current days price to be larger larger than or equal to a priors day that means we can expand the previous span to be even longer so let's say that just just for the sake of demonstration let's say that on day four we have a price that's three we're going to look at the previous current two striking kind of span values it's one we surprise one so we can the first thing of course to expand this this span here of course to expand this this span here let's say your picture that we can let's say your picture that we can extend this current to span with one day extend this current to span with one day to be two because we now see a price a to be two because we now see a price a price of three price of three then then what we can also do is to then then what we can also do is to check on the priors priors the span check on the priors priors the span which actually ends on something that's which actually ends on something that's lower than the today's price so we can lower than the today's price so we can actually combine those two spans into actually combine those two spans into one then we end up with a span with a one then we end up with a span with a 5.3 and the four days under the belt 5.3 and the four days under the belt after that we can continue to process after that we can continue to process day 5 if the price drop the to the day 5 if the price drop the to the mystic at the file would be the this and mystic at the file would be the this and - with the current of Spain strike of - with the current of Spain strike of value of 1 so that's the image how we value of 1 so that's the image how we maintain this stock yeah so let's just maintain this stock yeah so let's just cut this thing up just further for this cut this thing up just further for this context let me just call this the context let me just call this the spanner which is a museum vector you spanner which is a museum vector you will store the pairs integer to integer it's gonna be the the horizontal the the horizontal line that the park current days price is gonna set on there and the second element is the number of days that's below that line towards the left before we find something that's even higher so that's that's what this couple here stores in look at this picture so for example here you will be today's price that's this line and how many days towards left we can include under the line before we find something that's upper higher than this so for this you will be the price and number of number of days or little bars so that's going to be the stuffily we keep on this stock the constructor and this you could just set this to empty and then when we get the new price we would try to do this compression yeah so in the case of its decreasing or well if it's the first day you're going to have a card to strike value off line so that's the default just the thing we need to do is to look after the stack and on the top that's the previous [Music] [Music] based on this example we see that we can based on this example we see that we can actually do due to compression along actually do due to compression along with the current value is the prior span with the current value is the prior span then we find the two current span can be then we find the two current span can be further consolidate so it's not a if further consolidate so it's not a if condition it's a wire condition here so this means we can do some compression so this means we can do some compression the thing we do is to grab the expander the thing we do is to grab the expander the span and then throw out to this the span and then throw out to this pocket events after this compression we pocket events after this compression we can put the the consolidator pass on to can put the the consolidator pass on to the consolidated span information onto the consolidated span information onto the staff for the current price and the the staff for the current price and the conscious man so that's the code yeah conscious man so that's the code yeah submit this yes it's working submit this yes it's working so so yeah so so yeah picture it basically is maintaining for picture it basically is maintaining for any given day we draw a horizontal line any given day we draw a horizontal line and looking back try to compress and looking back try to compress everything that's under this horizontal everything that's under this horizontal line into a topo with this today's price line into a topo with this today's price and how many of those thoughts so this and how many of those thoughts so this is this is the stuff that's we put on is this is the stuff that's we put on the stack because because all these the stack because because all these little individual details after we are little individual details after we are passing today is irrelevant passing today is irrelevant the only thing important is just the the only thing important is just the price and how many little bars under the price and how many little bars under the horizontal line before we find something horizontal line before we find something that's higher so that's the only thing that's higher so that's the only thing that's important when we recalculate the that's important when we recalculate the new span for the following days so the new span for the following days so the the space complexity for this is I guess the space complexity for this is I guess in the worst case it's all decreasing in the worst case it's all decreasing we're going to have the prize of is 1 we're going to have the prize of is 1 pairs of price and one all the way pairs of price and one all the way towards the end so it's a order of N and towards the end so it's a order of N and in terms of time complexity it's a it's in terms of time complexity it's a it's a it's a I think amortize that it will a it's a I think amortize that it will be one so on some of the days we would be one so on some of the days we would just do constant work but on some time just do constant work but on some time some some days with when we need to do some some days with when we need to do the compression we have to go backward the compression we have to go backward and can do some consolidations it will and can do some consolidations it will be let's say that the worst case will be be let's say that the worst case will be going down all the way and in the final going down all the way and in the final day we have something that's really day we have something that's really really high and then the compression really high and then the compression will take order n time will take order n time that's the worst okay worst single that's the worst okay worst single single operation case because we have to single operation case because we have to go back and add one more day one more go back and add one more day one more day add one more day to consolidate all day add one more day to consolidate all this top of us on the understand that this top of us on the understand that single operation will take order of an single operation will take order of an but but throughout the lifetime average but but throughout the lifetime average uses of this operation I think it's a uses of this operation I think it's a constant yeah so that's the question constant yeah so that's the question today | 2024-03-25 10:19:04 | 901 | Leetcode 901 Online Stock Span |
|
fG-6r2zZKl0 | hi there welcome to my channel i'm here to do some easy and medium i'm here to do some easy and medium legal problems legal problems and my goal is finish a hundred of them and my goal is finish a hundred of them today we have nico 101 today we have nico 101 so we're gonna finish this today it's so we're gonna finish this today it's symmetric tree symmetric tree so giving a binary check whether it is a so giving a binary check whether it is a mirror mirror of itself basically is of itself basically is if you see a tree in this uh example if you see a tree in this uh example is one on the top two in here is one on the top two in here the two in the left side is equal to the the two in the left side is equal to the two in the right side two in the right side and the further left will be and the further left will be the same as further right so basically the same as further right so basically you think it's a mirror in the middle you think it's a mirror in the middle and then they just copy the left to the and then they just copy the left to the right side right side another example is not true another example is not true when you see this the left note 2 when you see this the left note 2 this 2 left is not equal to the right this 2 left is not equal to the right 2 it's right so it will return 2 it's right so it will return false this program false this program will return a boolean the first time you will return a boolean the first time you think about this think about this question um you would think question um you would think if this is a note right here so what i if this is a note right here so what i need to need to check if this notes left check if this notes left is equal to this node's is equal to this node's right and in this node right and in this node um we have to also make sure um we have to also make sure left node's left equal to right nose left node's left equal to right nose right in the same time left nose right right in the same time left nose right have to be equal to right notes left have to be equal to right notes left so basically the logic of this question so basically the logic of this question so let's code it out function function and helper the root note is equal to no the root note is equal to no that will return true so this case will cover if it's no it will return true so after this line we'll see the root note is not no so in here though is not no so uh we don't need to check the root node because this is symmetric you only have one the what's next we have to check is return the helper function the helper function did is basically checking if root node.left and root node.right is symmetric the helper function is checking that and how to do that is and also have some sorry no sorry no laugh tree no laugh tree no right so if tree node left right so if tree node left is equal to no and right is equal to no and right equal to no equal to no return true and if left is equal to no or write equal to no what this mean what it this means is first they check if left or right is equal to no in the same time so when we check in this left three notes three is right here we need to check threes left is equal to uh three is right so this is a if they all node so return true so when one of the node after this condition is done we would we check this uh second condition so either one of them either left or or right write is no so only one of them are no that means they're not symmetric so we have to return false after checking those condition so what we need to do is check and right right and right right and helper laptop right and right dot left and that's it for this question uh to explain how that word is in this after all the conditions met so that will oh oh sorry this missing of lab dot value is not equal to write dot value so also false also return false so in this case we come to your root node right here and we'll check two and this and this two right two this is the same so they're both not no or their value is the same not the same so it returned false this condition is not met so i have to return lab dot left and right dot right they will check this three and this three are they the same or not so keep recursive and until they find it all the way to the bottom also i have to check lab dot rise is equal to right dot left so we cover all the condition in this case so let's run the test so yeah that's it the recursion method so yeah that's it the recursion method for this for this solution if you have any question solution if you have any question please leave it in the comment section please leave it in the comment section uh uh please like and subscribe our channel please like and subscribe our channel this is really helpful for this is really helpful for our channel otherwise we see you in the our channel otherwise we see you in the next video next video bye | 2024-03-21 09:53:44 | 101 | Leetcode 101 - Symmetric Tree (Java, Solution Explained) |
|
LKHE5AVTmTk | we're given a grid of intense and squares where each one times one square is either a black space or contains a slash or a backslash these characters divide the scores into different regions and the goal is to counter number of cognitive regions in the grid to solve this question we first divide each one times one square into four regions north east west and south the intuition behind this problem is to achieve slashes as boundaries that separate regions for example if a square contains a slash you can think of it as a boundary that separates a square into two parts one containing the north and west regions and one containing the south and east regions thus we can find and merge the regions together when they are separated by different characters if two horizontally adjacent squares both contain slashes we know that each Square gets separated into two parts and thus the east and south region of the left Square will get merged with the North and west region of the right Square in this case the two squares will have a total of three connected regions to accomplish this the best way is to use the unify method Union fan data structure keeps track of the number of connected regions if you're not familiar with Union fine check out the link in the description to learn about how it works and the standard template to import a union file there are many ways to implement unified data structure so you're free to choose any implementation that you feel comfortable with in our code we will store the roots of each region in a dictionary where the keys are the regions and the values are their roots initially each region is its own route when two regions are unioned together they are used become the same we will denote each version of the Tuple IJ direction for example 0 0 n represents the North Region of the square on the first row and the first column after that we'll iterate of the squares of the group and use the union operation to merge the regions based on the characters given for each square if the counter is slash we connect the North Region to the west region and connect the sound Fusion to the east region of the square I'll see if the character is Black slash we connect the north version to the east region and connect the South Region to the west region of the square else if the character is blank space we can have four Visions together we know that for two horizontally adjacent squares the east region of the left Square will always be connected to the west region of the right Square no matter what the combination of the character is also for two vertically adjacent squares the south region of the top square will always be connected to the north region of the bottom Square no matter what the combination of the character is to get the answer we can count the number of distinct Roots among all regions in the dictionary this is done by mapping the fine operation to all regions in the union fine data structure selecting their unique items with the set operations and finding the length of the set and that's it this is a simple but effective solution to the routine cuts by Slash's problem I hope you found this video helpful thank you for | 2024-03-25 12:20:27 | 959 | LeetCode 959. Regions Cut By Slashes | Union-find | Python |
|
qbFP-4hPJZk | so today's question is possible by partition so in this question we have partition so in this question we have given the set of n peoples and we have given the set of n peoples and we have to split them in two groups to split them in two groups we have given group of people who we have given group of people who dislike each other so we have to do is dislike each other so we have to do is we have to put them in different groups we have to put them in different groups so that they are known in the same group so that they are known in the same group so what can we do so as we have to so what can we do so as we have to divide them in two groups we get to know divide them in two groups we get to know that this is a standard quotient of that this is a standard quotient of graph by partition so for example if graph by partition so for example if this is a graph so how can we divide it this is a graph so how can we divide it in two parts what we can do is we take in two parts what we can do is we take any element and give it a red color any element and give it a red color maybe and then all its neighbor blue maybe and then all its neighbor blue color then all their neighbors red color color then all their neighbors red color so we can do it in this way so here we so we can do it in this way so here we have all the neighbors alternate colors have all the neighbors alternate colors red and blue so if we have this graph we red and blue so if we have this graph we can give the first element blue color can give the first element blue color maybe then its neighbor a red color then maybe then its neighbor a red color then the third neighbor the third neighbor what will we give it blue or red so the what will we give it blue or red so the conflict arises so when the conflict conflict arises so when the conflict arises we can say that it can't be by arises we can say that it can't be by partition or we can group it into two so partition or we can group it into two so for example in this case we have given for example in this case we have given the group of dislikes so one is related the group of dislikes so one is related to two one is related to three and two to two one is related to three and two is related to four all have different is related to four all have different colors so they are in different growth colors so they are in different growth so this is a valid case in this example so this is a valid case in this example one is related to 2 2 to 3 3 to 4 4 to 5 one is related to 2 2 to 3 3 to 4 4 to 5 and 1 to 5 but here conflict arises as 1 and 1 to 5 but here conflict arises as 1 & 5 are of the same color so we can't & 5 are of the same color so we can't group it so this is an invalid case and group it so this is an invalid case and we can't group it into 2 so let's try to we can't group it into 2 so let's try to write code for this so basically what we write code for this so basically what we have to do is we have to take a graph have to do is we have to take a graph give it one element any random color give it one element any random color like red then its old neighbors blue like red then its old neighbors blue then all neighbors of neighbors red and then all neighbors of neighbors red and earth so on and if at a point we are earth so on and if at a point we are given a node different color than its given a node different color than its previous one then we know that the previous one then we know that the conflict arises and we can't group it conflict arises and we can't group it into two so for here I into two so for here I taken vector of vectors as graph and map taken vector of vectors as graph and map to store its color now we are firstly to store its color now we are firstly forming the graph then we are iterating forming the graph then we are iterating over all the elements that is not over all the elements that is not colored previously and using DFS on it colored previously and using DFS on it in DSS what we are doing is then we are in DSS what we are doing is then we are searching in that map and if we have searching in that map and if we have that element previously then we are that element previously then we are checking its color if we don't have that checking its color if we don't have that element previously then we are giving it element previously then we are giving it the new color and after giving that new the new color and after giving that new color we are saying give all its color we are saying give all its neighbour animals the different color neighbour animals the different color and return so that's how we are doing and return so that's how we are doing our part so let's try to code in Python our part so let's try to code in Python do so this is that function I am using do so this is that function I am using different dictionary as graph and group different dictionary as graph and group is that container that is storing the is that container that is storing the colors of the graph now we are returning colors of the graph now we are returning DSS for all that are noting group DSS for all that are noting group previously and our Davis is doing it is previously and our Davis is doing it is checking if the element is present checking if the element is present previously then we are checking its previously then we are checking its color if node then we are giving it a color if node then we are giving it a color and then we are giving all its color and then we are giving all its neighbor the different color and so on neighbor the different color and so on so I hope this is somewhat clear to you so I hope this is somewhat clear to you you can give your suggestions in the you can give your suggestions in the comments below thanks for watching and comments below thanks for watching and have a nice day | 2024-03-22 17:38:45 | 886 | Possible Bipartition | Leetcode Day: 27 | graph | May challenge | question. #886 |
|
ZA5HImcVuCQ | hello and welcome to today's daily lead code challenge today we'll be solving code challenge today we'll be solving question 1,887 reduction of operations to make an array elements equal okay so let's go straight to the question um given an integer array nums uh let's see this integer AR nums your goal is to make all elements in Num equal to complete one operation follow these steps so through n or some number of operations we're going to attempt to make this input array uh equal or have all the elements in the array equal and these are the steps to reproduce one operation find the largest value in nums let that be let that index be I zero index and its value be largest Okay so so we uh assuming that the array is sorted we find the largest uh value and largest index sum largest index sum n um value if there's a if there are n um value if there's a if there are multiple elements with the largest value multiple elements with the largest value pick the smallest I if there are pick the smallest I if there are multiple X's we pick the smallest X right uh if the value largest if there are multiple elements with the larger value pick the smallest I find the next largest value in nums strictly smaller than largest let that value be next largest so there is some x minus uh some number that is going to be largest okay largest okay next next largest uh and then we largest uh and then we reduce and then we reduce nums I to next reduce and then we reduce nums I to next largest so we reduce largest so we reduce this uh largest value to whatever this this uh largest value to whatever this was x - one or xus whatever it is x - 2 was x - one or xus whatever it is x - 2 3 or whatever um so what it what is this 3 or whatever um so what it what is this one operation actually doing well if we one operation actually doing well if we were to visualize it and I will I like were to visualize it and I will I like visualizing these things because they uh visualizing these things because they uh make the problem more make the problem more solvable um it kind of seems like solvable um it kind of seems like assuming that this is a sorted array assuming that this is a sorted array that once we find we start off with one that once we find we start off with one point right here we look at the next uh point right here we look at the next uh we look at the next element and then we we look at the next element and then we see by how much we have to reduce this see by how much we have to reduce this um this next value now the process of um this next value now the process of reducing it is just one operation so reducing it is just one operation so once we reduce this we move on to the once we reduce this we move on to the next one and try to reduce this once again I'm wrong though that's not the way to do this because that would mean simply that we look at how many different values there are beside excluding the first one and we just say that the result is nus1 n being the number of elements uh right the result is n minus one if if this is the right approach so so I'm doing something I'm messing up right I'm messing up I I I realize why I messing up because I'm going from uh I'm going from bottom to to top whereas here the process is actually saying go from top to bottom so first um first look at this largest value find its next largest value subtract this number uh reduce it to what the next largest is pointing to and then go ahead and find the next largest value which would now be this uh reduce all of these so far two operations no so far four operations then find the next largest value this one reduce all of these which would be plus four more operations and then find the next largest and then 1 2 3 4 5 6 7 plus 7 so the result here would be 4 + 4 + 4 15 uh 15 am I correct here it seems like uh the process of reducing the array can't start from the initial value because if we start with the first value then we are easing the process of reducing the next values because we can automatically reduce it to the smallest possible value but the reduction here is gradual we first reduce the largest value to what we think could be the next largest value and so on and so on until we um until we get everything equaling one uniform array so how would this work how would this work well one approach is to mimic what what I just did which is to essentially have a start and a finish and each time I encounter this fluctuation between what is here and what is here each time I encounter that to some result I add um the difference between the start and the end so that would be this first uh plus equals would be a of the difference of uh just one right so it would be plus or equals to one uh and that would essentially me be cutting off these guys then I would push my start to the next possible start and cut off these three values so res plus equals three then I these guys so that would be res oh I I I these guys so that would be res oh I I I would extend my width to here this was what 7 seven wait why is it seven I messed something up um reduce this one reduce this three reduce this by four sorry I I missed I missed this portion when I reduce it first by three and then I reduce It Again by four and then 1 2 3 4 5 6 7 and then by seven so in this case it would be 3 + res + seven and here yes 15 right so 15 so that's one way of doing it I and that could be a solution what if we try to implement it maybe a bit faster going from still left to right but looking at let's see there's this there's this notion of a of a step that I can Implement for example that if I'm looking at oops if I'm if I'm still iterating from left to right and I'm looking at uh the current and the previous numbers that are different in value I could indicate that my uh that my change to have all the following guys be changed is being increased by a magnitude of one because it essentially means that in order to get to this value this value has to be changed once this value has to be changed once and this value has to be changed once if I'm looking at respect from this one to how many times does this have to change well this has to change twice so what if I do something like this one one one two this value has to be changed three times because there's three fluctuations this value also has to be changed three times this value has to be changed four times does this also equal uh 15 yes it does 15 and this one is a bit easier to go by because we don't have to keep track of the start and the end we can just keep track of the step that we're um that we're that we're changing so I'm going to try to go ahead and Implement that actually uh let's have the nums sorted let's have res equaling to one let's have the step equaling to zero let's have a while I in range one when nums and here I'll say that if uh nums I is greater than nums ius1 then step plus = 1 and then res plus equal step let's see if uh this works this is a very clean solution let's see if I was that did you mean that did you mean I oops I oops four for I in four for I in range silly range silly there we go okay that there we go okay that worked yeah worked yeah so very nuanced thing to notice you so very nuanced thing to notice you could characterize could characterize the uh the number the uh the number of steps One of These Bars has to go of steps One of These Bars has to go through in order to get to its final through in order to get to its final destination through this variable called destination through this variable called step and the way to know what that step step and the way to know what that step is equal to for each bar is just uh is equal to for each bar is just uh memorizing how many times that has to be memorizing how many times that has to be changed to get to this changed to get to this ultimate uh value and for these three ultimate uh value and for these three since the previous value was the final since the previous value was the final value then the change is just one if at value then the change is just one if at any point the next value is greater than any point the next value is greater than what what this what these guys are right then it this what these guys are right then it simply increases by one because we first simply increases by one because we first need to downgrade it to this value and need to downgrade it to this value and then we need to downgrade it here so then we need to downgrade it here so this notion of a step that increments or this notion of a step that increments or increases as you go on increases as you go on potentially this way uh let's me keep potentially this way uh let's me keep track of how many track of how many times the step is going to be what the times the step is going to be what the step is going to be for each one of step is going to be for each one of these bars and then it's just the sum of these bars and then it's just the sum of all of those steps and you can see that all of those steps and you can see that we've completed this successfully let's we've completed this successfully let's see if we're doing well we're not doing see if we're doing well we're not doing so well but this is an extremely clean so well but this is an extremely clean solution and I don't know if solution and I don't know if there's any there's any better no I I'm looking at these right better no I I'm looking at these right now now and it is I like my solution way more additionally these do similar yeah step plus yeah this is oh similar yeah step plus yeah this is oh this is one to one yeah absolutely I like this approach way more and uh yeah please use this um hopefully this was quick and easy and intuitive and that's what I'm really going for in these situations to visualize these things and then be able to apply them in later problems uh with that thanks for watching today's video please like And subscribe helps a lot | 2024-03-25 11:58:12 | 1,887 | Reduction Operations to Make the Array Elements Equal | 1887 Leetcode | Python3 |
|
BBX66zpkjjs | hey everyone welcome back and today we'll be doing another lead code problem we'll be doing another lead code problem one three eight copy list with random one three eight copy list with random pointer this is the medium one pointer this is the medium one so the description is pretty large but so the description is pretty large but what they are saying is what they are saying is we have a normal linked list uh with the we have a normal linked list uh with the next pointer but it does have another next pointer but it does have another pointer name random so what does the pointer name random so what does the render pointer do it points to a random render pointer do it points to a random node so the random pointer of 7 is node so the random pointer of 7 is pointing to the end of the linked list pointing to the end of the linked list and the random pointer the second node and the random pointer the second node points to First node and the random points to First node and the random pointer of third node points to fifth pointer of third node points to fifth node and that's it so what we can do node and that's it so what we can do here is just have a hash map so how our here is just have a hash map so how our map is going to help us so let's say if map is going to help us so let's say if our map is like this and putting on none our map is like this and putting on none as a key and a pair because there can be as a key and a pair because there can be a none pointer now let's just make the current for hours reversals so current will be starting from head so while current is not null but I will do is just make a copy node and passing it current dot well and passing it current dot well so now what they want us to do is just so now what they want us to do is just make the copy of the linked list just make the copy of the linked list just make the copy of the linked list but we make the copy of the linked list but we cannot just make the linked list and cannot just make the linked list and have all the other stuff like connecting have all the other stuff like connecting them and doing all the other stuff them and doing all the other stuff like the normal one because as you can like the normal one because as you can see when we are on pointer one when we see when we are on pointer one when we are on node one its pointer is going to are on node one its pointer is going to point to null okay but when we are node point to null okay but when we are node 2 its random pointer is going to point 2 its random pointer is going to point at 1 this is also okay we already have a at 1 this is also okay we already have a node one but when we are on three the node one but when we are on three the point random pointer of 3 is pointing to point random pointer of 3 is pointing to five so we do not have a 5 so how we are five so we do not have a 5 so how we are going to say that it points to five then going to say that it points to five then in this case the map is going to help us in this case the map is going to help us because we can just get the values and because we can just get the values and that's it the next and random values that's it the next and random values easily and but this Loop we'll be doing easily and but this Loop we'll be doing here is just making the copies here is just making the copies so not connecting the nodes and just so not connecting the nodes and just making the copies so if it is the linked making the copies so if it is the linked list is like this then this is just list is like this then this is just making the nodes making the nodes but not connecting neither the next but not connecting neither the next pointer or the render pointer these are pointer or the render pointer these are just separate nodes so now we will say just separate nodes so now we will say like map like map at current so current at current so current current address at map should point to current address at map should point to the copy we made okay now we will just update our current so current is equal to current dot next now we will start our current from the head again so while our current is not null we will take the copy we just stored so map at current okay we have the copy and now current at current dot next because obviously we at current dot next because obviously we have a reference and its dot next is have a reference and its dot next is going to give us its dotnet next the going to give us its dotnet next the next node and it can be saved to the next node and it can be saved to the node we just copied like this node so node we just copied like this node so that's it and its random is also going that's it and its random is also going to be the same so Random map at current dot random okay after that we can just say like increment the current so current is equal to current dot next and just return map add head so why map add because head is going to give us the reference and at that reference we can just return the head which will be the corporate link | 2024-03-21 12:20:41 | 138 | 138. Copy List with Random Pointer | Leetcode | Python |
|
eV45Y2vwy2w | Hello viewers welcome to test this pending in this video discuss problem pending in this video discuss problem very important interview problem gas very important interview problem gas station is taken from list code 134 station is taken from list code 134 problem and medium level problem is a problem and medium level problem is a very interesting problem if you very interesting problem if you want to watch then in this video we will first want to watch then in this video we will first understand the problem statement and understand the problem statement and understand the problem statement and see his different approaches including output Sainik Real Karta Hoon In this video we will also discuss the code and its explanation so let's start the video example. As it is well prepared then let's take this example which has sample input from late code This is the point, we have This is the point, we have This is the point, we have gas, withdrawal, I will tell you the status of it. gas, withdrawal, I will tell you the status of it. Hey, what have you got Hey, what have you got from the gas station in this case, there are from the gas station in this case, there are gas stations from 5825 stations, gas stations from 5825 stations, right circular is definitely ours in the circular route and the right circular is definitely ours in the circular route and the amount of gas and is stations gas I amount of gas and is stations gas I Muzaffar. Muzaffar. Muzaffar. all are considered to be zero. One unit of gas is available upon registration. Two your top gassers at the first station are available right near me. Not only the unlimited gas tank of the car we have, no matter You can understand the cost that will be incurred and the You can understand the cost that will be incurred and the You can understand the cost that will be incurred and the fuel conservation that will be done in going from fire fuel conservation that will be done in going from fire station to IS one of the sessions. station to IS one of the sessions. He has kept us in the cords side, meaning He has kept us in the cords side, meaning if we have reached 100 stations, there is a station, I will if we have reached 100 stations, there is a station, I will make a station here, then make a station here, then I am College Railway. I am College Railway. I am College Railway. 110, first, second, third, fourth and fifth, then let us start knowing the cost of subscription, then from here, three, this will be done similarly after consuming this corruption time. We have appointed gas That is, That is, That is, inside the gas here, inside the gas here, gas is available here and if you subscribe, then subscribe and after covering the whole, you will come back to the station road and if you subscribe, then how will it come from here, after subscribing, you will return here do two patterns that starting do two patterns that starting do two patterns that starting stage should you start from, you cannot soften every station here, there is only one station from where you start, you will be able to complete the circular road, here is the giver, united solution, it is a rented war, there is only All can fit, if you are All can fit, if you are All can fit, if you are not able to chat, if you are not able to chat, if you are not able to complete Qassam not able to complete Qassam taken the code of approach so that we can understand the exam a little quickly. Here this is our ghagra, inquiry and here, if we take it, then what will we do here, if I do it in the induction, then if we come after doing it, then first of all we have taken Rally of whatever we will get this here of gas Rally of whatever we will get this here of gas Rally of whatever we will get this here of gas and converted it into skimming this and from and converted it into skimming this and from its side we will ask for each index starting next give and starting in then we will take all these starting in then we will take all these items starting from here can we call items starting from here can we call this starting index this starting index this starting index me assume here first that I can make it, it is considered possible to make it, then we will see further whether it can be made or not, and inside the fuel, I will keep the gas high till the current system father that he is in his tank, so my Otherwise, Otherwise, Otherwise, I represent it as fuel, we have this I represent it as fuel, we have this note, now it's time to fill your legs, now we will note, now it's time to fill your legs, now we will start freeing ahead, so the current station, start freeing ahead, so the current station, what we will take out will be I+G, pizza what we will take out will be I+G, pizza people are feeling to move ahead, people are feeling to move ahead, till the end station. till the end station. till the end station. to the end, then what will be the current session? I want plus, now we are J, I am the first station, so let's go to fashion, we are here for daily life, so we will reach one station ahead of I, J2 will go to village heard from 22nd. Modern because it will be better prepared in some time after using the circular property, so let's see the current session, we have pimples station here, there is a card to take out the next, it has taken question mode, why is the time So this is a neck station. Hmm, So this is a neck station. Hmm, So this is a neck station. Hmm, I will differentiate it. Our current is I will differentiate it. Our current is written here. Fuel is written here. Now what will happen written here. Fuel is written here. Now what will happen that we want to reach the current situation, that we want to reach the current situation, Irfan, we will have to spend, that is the cost of Irfan, we will have to spend, that is the cost of current station, so do not spend 11km current station, so do not spend 11km - 11. - 11. - 11. fuel became negative Like Baikunth, it is not possible for negative people to continue. If fat cannot be converted into fruits and vegetables, then from here we will make bread to give our form. Next current starting Now one thing is Now one thing is Now one thing is important point from here and it is known important point from here and it is known that if the master of gas at any station that if the master of gas at any station is less and the cost of reaching the next stage is high is less and the cost of reaching the next stage is high then one cannot start from there then one cannot start from there then you will send eight units of but you then you will send eight units of but you need 1180 need 1180 need 1180 white or progressive, then it is important to keep this point in mind, so now it is possible here, we will do that in the future, we check the next station, then all this is over, daily problems are not going on, Now we will try to retreat from here, if we go Now we will try to retreat from here, if we go Now we will try to retreat from here, if we go near like this then some Stockholm will come near like this then some Stockholm will come to us. We will to us. We will go with 6 possible computers. We will go with 6 possible computers. We will close our eyes and say that the current session is ours close our eyes and say that the current session is ours and this is our extraction. Okay, so and this is our extraction. Okay, so from here we fry, if there from here we fry, if there is work then is work then is work then fuel did we have in the beginning? People said that the organization and teacher - Kara 054 Not quite united. We reached the tube channel again in Avnesh, so this is the one of it. So six plus one, how much The pass is available again but The pass is available again but The pass is available again but we need tubeless to reach like this. we need tubeless to reach like this. This is also not possible. This is also not possible. We will press ice cream. We will do that next. We will We will press ice cream. We will do that next. We will carry a garland of bombs to Karan station. This is carry a garland of bombs to Karan station. This is also possible. We will give current to myth TV to the crazy people. also possible. We will give current to myth TV to the crazy people. Once I tell you how and how to make extra money, Once I tell you how and how to make extra money, okay, so what is our okay, so what is our reason here today, the contribution of station women is so reason here today, the contribution of station women is so cute with us, this train is cute with us, this train is near the starting and we are considering it as Guru near the starting and we are considering it as Guru and we are saying the current situation as I plus mind, and we are saying the current situation as I plus mind, Guruji. Guruji. Guruji. next, this is the loot and ours which is the pipe to reach that mansion. Okay, so - after typing this, we are left with feet of fuel. Anytime on pension, then from there Bigg Boss housemate is For unity gas is available, we will For unity gas is available, we will For unity gas is available, we will fold it, it will not become important, if it fold it, it will not become important, if it comes to the next station, then the current will be ours, or if the comes to the next station, then the current will be ours, or if the bar increases, then the current system bar increases, then the current system of clans is closed, means three plus 114, of clans is closed, means three plus 114, now our current station is done, whatever turn you have now our current station is done, whatever turn you have taken, that taken, that taken, that what will be our current situation, frustration, Sona active, that's why we said that i plus job will come modified modified, zero will be modified, after this they will directly take me to form, there will be no change in the wanted criminals, If it is If it is If it is present here, then the present here, then the current system was found in those actresses, now we have started current system was found in those actresses, now we have started subscribing Rasool, whatever congestion happened, subscribing Rasool, whatever congestion happened, but there was more in which support - will be but there was more in which support - will be saved, wife saved, wife flash lights channel will go to this and in this case, flash lights channel will go to this and in this case, it is fit for you. it is fit for you. it is fit for you. computer, then you can take a break in between, check it if it is possible, yes, I had done the cutting metro, so we used to spend this amount of ₹ 1 here, no, here Mittu will return it. This is our answer here, but if you have found it possible at your home and have not searched all over - then this was our gravy approach So So So now we have to do a little bit of now we have to do a little bit of optimization in it, we had to do ticket optimization optimization in it, we had to do ticket optimization because of the time complexity, because of the time complexity, so let's see first, so let's so let's see first, so let's talk about the time complexity here. If we have to apply the powder above short and explain, then the network is our intensity. apply the powder above short and explain, then the network is our intensity. Will take and whatever will go on the channels, the time Will take and whatever will go on the channels, the time is running or the advection will run. If suppose we are is running or the advection will run. If suppose we are not able to get it, then the total which will be set on that timer will be the not able to get it, then the total which will be set on that timer will be the committee with it. Stupid committee with it. Stupid insecure which is very high, so whether insecure which is very high, so whether we can optimize it remains to be seen. we can optimize it remains to be seen. we can optimize it remains to be seen. few points, I am clear to you, see what you do here, let's do some optimization, which is observation, point number one, the first observation that I have is that see, is it possible So So So how religious in these custody how religious in these custody so that I gas rally here, this so that I gas rally here, this registration is standard unit of registration is standard unit of gas available on the waist and the cost is different for everyone, gas available on the waist and the cost is different for everyone, okay, I have come to do a little this site, I have taken an okay, I have come to do a little this site, I have taken an example, quite a good exam, example, quite a good exam, first, now. first, now. first, now. taken out the blood differential, the difference of what is the amount of gas and copied it, I will take out the difference, add it here, the difference - Pro 6's difference is 500 to 1000 and it will come here on 16th - 7th, 121. 121. 121. that our colleagues that our colleagues and I have taken out in a loot-loot manner, here, and I have taken out in a loot-loot manner, here, if the difference has been taken out that it if the difference has been taken out that it is available and how many people are there, where there is is available and how many people are there, where there is depression, they can start the custom, depression, they can start the custom, it is clear because brother for - it is clear because brother for - Time's top-10 login protein is happening again and again. To go ahead, you will be able to point your finger at the top. If you go circuit, it is a different matter, able to point your finger at the top. If you go circuit, it is a different matter, okay, you can use circular, otherwise you okay, you can use circular, otherwise you cannot do negative importance, cannot do negative importance, but what? but what? but what? because if the total gas available is right at every station, then forgive 80 rupees in the total gas cost, it is always great dan and equal to the total cost. If it is not so, then I can answer it anywhere, anytime. I have come in such a way that the total available gas can be so much that it can travel in the vegetables, if this condition is not met then the answer will come - Mother, it is not possible to get up in the circuit, it is good, so you We We We can convert the difference and go to it, if the can convert the difference and go to it, if the difference is less, the question is, the total difference is less, the question is, the total difference will be and the total gas will be the difference will be and the total gas will be the total difference of the total cost, that if the total difference of the total cost, that if the great daily is 120, done only, our answer will be great daily is 120, done only, our answer will be possible, so this is the first observation given, possible, so this is the first observation given, now where are we? now where are we? now where are we? explain to you how we set it, let's discuss the election approach, how we are going to walk on us, so what we will do, we will start from here, okay, so this is our stock index, this is the light above, We will keep it here and see We will keep it here and see We will keep it here and see if it is possible for you, otherwise the if it is possible for you, otherwise the difference that will come here is that we have the net, so for difference that will come here is that we have the net, so for those people like us, we will get one, those people like us, we will get one, here we have to reach further, okay, so gas is the here we have to reach further, okay, so gas is the tank and expense is fraud, birth is ahead. tank and expense is fraud, birth is ahead. tank and expense is fraud, birth is ahead. then here we will check. We are accusing I to move ahead, so here we will check the difference, how much is the difference here and - full right, so we have added it here and are moving forward after calculating our total difference. So if we deduct this from the total difference then it will be ours. Now the flavor of phone of four is in our bank and we would have reached here. Now we have to come and settle from here, the Now we have to come and settle from here, the difference is that education means only difference is that education means only admission. admission. admission. n't do 6 problems then only if we get strength then we will set them tankers will be available for expenses, so enjoy it from here only by adding time, so all this work is done at hand The The The total difference that is left is that baby tank t-90 total difference that is left is that baby tank t-90 tanks then we have we have reached here tanks then we have we have reached here now here with the difference and is - the now here with the difference and is - the height of eleven so if you take - seven then the total height of eleven so if you take - seven then the total difference will become - so from here it will not difference will become - so from here it will not reach here. reach here. reach here. n't be able to go further than this. It's not possible to move ahead. Salt, we need to use 11 to move ahead. Tumor plus minus one is on Brahma. 10 is gone. Okay, so I. This is So So So what should we do in this case? Now what should what should we do in this case? Now what should we do? This part NFC we do? This part NFC is closed, it means should we is closed, it means should we start the starting index from here or start the starting index from here or not, this is an important question, so not, this is an important question, so inside this we should not start from here, we inside this we should not start from here, we directly directly directly why am I speaking like this, let me explain it a little, okay, let me clear the intuition, so this one point to overs points, 220 points, this is a station and this station is also ours, okay, so I am here. Kushdhwaj can be shown by clicking on Kushdhwaj have car start from that and that judgment reach b that if from where it starts and Vipin between a n b loot countries on that any station in the uniform of which Can't even reach to even because it was given Can't even reach to even because it was given Can't even reach to even because it was given in small spoons because we started from A, so in small spoons because we started from A, so what amount of what amount of gestures hero was there in our tank, but when we gestures hero was there in our tank, but when we reached to even, we had already reached to even, we had already got some gas for 8 minutes. got some gas for 8 minutes. got some gas for 8 minutes. start this saver of zero, despite being from Meerut unit, editing was available here at this time. If we were starting from here, then if it does not reach after that, then how will we be able to reach it? If you This means that if This means that if This means that if we are starting a gas like this, it is okay we are starting a gas like this, it is okay and it is not able to reach B, then any question in between, and it is not able to reach B, then any question in between, you guys will also not reach from there till now you guys will also not reach from there till now because here the because here the benefit for you is not less than the loss for them. benefit for you is not less than the loss for them. This means that if you start like this then you will This means that if you start like this then you will not save anything, it is okay if you do not save anything, it is okay if you do not save anything then it will be zero or you will see some saving, then not save anything then it will be zero or you will see some saving, then editing is done there, there is no further, editing is done there, there is no further, but whatever benefit you bring here, which is left, will be for but whatever benefit you bring here, which is left, will be for your issue. your issue. your issue. start fresh from here, then your initial which now after the capacity of the tank is 100, cannot reach from here also, if you cannot reach from here, then our theorem of disease and stupid remedies, if we are Can do because now there will be no going back from here, if Can do because now there will be no going back from here, if Can do because now there will be no going back from here, if we talk from here, then what else will I do with my starting index, I will call the family mercury, now what else will I do with my starting index, I will call the family mercury, now I am my start next, I am my start next, start these taxes, make it full, start these taxes, make it full, dip the light pocket total and total from different. dip the light pocket total and total from different. dip the light pocket total and total from different. difference will keep going on, then the total has to be withdrawn, my co-worker, my condition, the affair, the market committee, the total difference, the meat, the record, the need, the answer is possible, the total difference is there, it will keep going on - discharge the difference, I will make the current difference expensive, The mobile will be The mobile will be The mobile will be switched off, zero, okay, you start from here, how much balance do we have here, favorite, the reason is the difference, how much balance do we have here, favorite, the reason is the difference, and if we add to it, then the total and if we add to it, then the total difference will be ours, that's it, God, it's difference will be ours, that's it, God, it's Friday. Friday. Friday. which is the difference, the total of 3 minor surgeries has become the total difference, one of the current different has dried up or is still current affairs-politics, here there will be a difference of this, the current difference of this has become It is done, we will set the day of intake, It is done, we will set the day of intake, It is done, we will set the day of intake, here the difference is - ₹ 70, the difference is here the difference is - ₹ 70, the difference is done, you are 0f the reason, the difference is done, done, you are 0f the reason, the difference is done, gote and we have reached the end, date means, if gote and we have reached the end, date means, if we start from here, then we we start from here, then we can cover the whole, I am here. can cover the whole, I am here. can cover the whole, I am here. we started the history and we reached the end, where is the end and as we will be able to end, this is the answer, apart from this, the answer is not possible, so if If you could If you could If you could not reach completely, it is 551 which is old last year, not reach completely, it is 551 which is old last year, then we will discuss it then we will discuss it in a little while, so the app is interesting, what we are doing in it is to in a little while, so the app is interesting, what we are doing in it is to take it from here and as it has been take it from here and as it has been said that it is amazing, this is our answer, said that it is amazing, this is our answer, now you all can also know that now you all can also know that now you all can also know that we did not get the power till we reached here, started again but could not go back but this has never happened, so if it had happened then somewhere Mark, you go first, I will also explain to you If he is speaking, then let's assume that if we If he is speaking, then let's assume that if we If he is speaking, then let's assume that if we start it from the point, then let's assume start it from the point, then let's assume that here we could not reach, that here we could not reach, okay, here on our jo difference, the okay, here on our jo difference, the current difference and which was correct current difference and which was correct Surya seller and our zero. Surya seller and our zero. Surya seller and our zero. light becomes negative balance, so here I had set that our rotating induction, so from here call this dress Max which I tried and tried and this fresco I call brother and let's name The The The Tilak requirement here is that now Tilak requirement here is that now have health or are associated with the campaign, have health or are associated with the campaign, then if we used to sense, it should be positive. After mixing our earlier posting, we started from here. If there are After mixing our earlier posting, we started from here. If there are technical tips, then we were torn here for the first time too. We did the technical tips, then we were torn here for the first time too. We did the valley press then like this. valley press then like this. valley press then like this. it is exports, I understood it and change the voice brother, what will happen, that is also posted, sorry brother, it is negative, so I did duty fast during Purnima, so that I could not reach here, it means it was virus, it was found negative, it was If it is negative, then what If it is negative, then what If it is negative, then what should be the broom? It should be on the roads, meaning there will be a plate. should be the broom? It should be on the roads, meaning there will be a plate. If it is quite possible, then only they If it is quite possible, then only they need positive because it is negative and this need positive because it is negative and this negative is not a big thing, that is why we could negative is not a big thing, that is why we could not reach here. Okay, so it should be of air, it should not reach here. Okay, so it should be of air, it should be positive and be positive and be positive and bread should be shifted by solid people but if bhaiya chat was positive then we would not have started from here, you understand starting here, we should start here so that Salman's, if this was If you If you If you start with understanding then it start with understanding then it may seem a little complete to you but I will take so much time from may seem a little complete to you but I will take so much time from here Amit says this is here Amit says this is not possible if you reach WhatsApp then I am not possible if you reach WhatsApp then I am from the beginning now I have proved from the beginning now I have proved that it is very good to understand you so that it is very good to understand you so no problem no problem no problem intuition, how do we reach to, so you fold it like this and it is very simple, okay, so we move ahead here, so this is the credit for the function input, so Now there is a little Now there is a little Now there is a little lifting, the children become visible, the colors are visible, the lifting, the children become visible, the colors are visible, the list code will be presented later, list code will be presented later, so what will we do, will we add the looper, so so what will we do, will we add the looper, so first let us define their value for 1 first let us define their value for 1 minute, I am pressed that I have reached India, there minute, I am pressed that I have reached India, there will be some entertainment here. will be some entertainment here. will be some entertainment here. gas dot 500 I got their value here cyber cafe from beginning to end pocket starting index take strange different but she gasp and same light goes on shift in the meeting so what will we do here which Tank is called Tank is called Tank is called fuel tank, fuel tank, how much will it be? Earlier, initially 20 inches how much will it be? Earlier, initially 20 inches were calculated from the states were calculated from the states and Excel difference was created, so what and Excel difference was created, so what difference is to be created, it should be coffee, while difference is to be created, it should be coffee, while starting Undhiyu, the fuel tank will starting Undhiyu, the fuel tank will take out as much gas as is take out as much gas as is available at the fire station. available at the fire station. available at the fire station. is okay to free the poster further, then in this way how much of our front time will be saved, we have to chant that the fuel tank is okay, to which I was So So So what should be our current difference? what should be our current difference? If it is negative and If it is negative and 10:00 then what will we do? If we will 10:00 then what will we do? If we will start Dindeshwari then it start Dindeshwari then it is if it will be movie time coffee then it will be is if it will be movie time coffee then it will be negative. If we will start advance then negative. If we will start advance then we will we will we will school, if they are not able to reach the next station then what will we do about the next station, restart from there, did 8, my will be 20, even if they are not able to reach, then the middle question, I have not reached yet, so that further Uttarakhand you I took the garlic as the target and restarted the refueling tank. It works like current affairs. Ok, total difference. Chawla, you will understand in total difference. If we do this work, then let's remove it. Here we make difference. Bulb this which is the front arm hole's this plus equal two differences a and inside the total difference this will be adding that Bluetooth data recovery site will not be there will be a negative of the fuel tank two which is the front arm is the same is settled and the starting indicator is our What has to be done here is this look What has to be done here is this look What has to be done here is this look enzyme will come out of this group then we will enzyme will come out of this group then we will check that the total difference which check that the total difference which should be gold is positive connected money equal to should be gold is positive connected money equal to zero. If it is so then we will return zero. If it is so then we will return our start index but if it is our start index but if it is not so then we not so then we not so then we voted, this is the total, so let's test it, copy it from here, color it here, test cases on Kunjam on all test cases, then submit this and Angara here, it was WhatsApp Twitter has been used very little by me, so WhatsApp Twitter has been used very little by me, so WhatsApp Twitter has been used very little by me, so come you have enjoyed this come you have enjoyed this complaint tuition example and code in this way, complaint tuition example and code in this way, I am here in which way we proof I am here in which way we proof and you just move towards optimizer east, and you just move towards optimizer east, 100-150 and this of this video. 100-150 and this of this video. 100-150 and this of this video. | 2024-03-21 12:05:48 | 134 | Gas Station | 134 LeetCode | Explanation, Intuition, Code | Greedy C++ |
|
NuD9X9feLyQ | welcome back to code Meets World and today we're looking at a leak code today we're looking at a leak code problem number 43 which is called problem number 43 which is called multiply strings multiply strings so if we're given two non-negative so if we're given two non-negative integers integers represented as strings represented as strings we need to return the product of the two we need to return the product of the two of them of them also represented as a string and we also represented as a string and we can't use any built-in libraries or just can't use any built-in libraries or just converting the inputs to integer converting the inputs to integer directly directly so so as an example if we're given the number as an example if we're given the number two and the number three is strings we two and the number three is strings we need to return two times three which is need to return two times three which is six as a string six as a string same thing down here if we do same thing down here if we do 123 multiplied by 456. 123 multiplied by 456. we should return fifty six thousand we should return fifty six thousand eighty eight as a string and what we're eighty eight as a string and what we're not allowed to do is simply convert the not allowed to do is simply convert the string to an integer convert this string string to an integer convert this string to an integer multiply them together and to an integer multiply them together and then turn it back into a string that then turn it back into a string that would be way too easy and so they say would be way too easy and so they say that we can't do that that we can't do that at the top I'm linking to a video I did at the top I'm linking to a video I did recently where I was doing addition with recently where I was doing addition with arrays where you had to go through digit arrays where you had to go through digit by digit and do the actual Edition from by digit and do the actual Edition from scratch so check that video out if you scratch so check that video out if you want to see a similar problem to this want to see a similar problem to this one one so let's go to the Whiteboard and I have so let's go to the Whiteboard and I have the second example pulled up which was the second example pulled up which was 123 times 456. 123 times 456. now I'm just going to solve this really now I'm just going to solve this really quickly using what we learned in school quickly using what we learned in school when we learned how to do multiplication when we learned how to do multiplication for the first time because we're gonna for the first time because we're gonna have to write code that can pretty much have to write code that can pretty much do that exact same thing do that exact same thing so what we do first is we multiply so what we do first is we multiply the six times each of the digits in the the six times each of the digits in the top number and feel free to follow along top number and feel free to follow along if you haven't done this sort of thing if you haven't done this sort of thing in a long time in a long time but six times three would be 18 so we but six times three would be 18 so we would write the eight and then carry the would write the eight and then carry the one one then we would do 6 times 2 which is 12 then we would do 6 times 2 which is 12 plus that one is 13. carry the one plus that one is 13. carry the one six times one is six plus that one is six times one is six plus that one is seven seven and then we can get rid of those and then we can get rid of those values that we carried and now we're values that we carried and now we're going to do the same thing but with five going to do the same thing but with five in the top number and you might remember in the top number and you might remember we have to add a zero we have to add a zero before we move on to the next digit before we move on to the next digit so 5 times 3 is 15 carry the one five so 5 times 3 is 15 carry the one five times two is ten plus the one is eleven times two is ten plus the one is eleven five times one is five plus one is six five times one is five plus one is six and then we can remove those ones that and then we can remove those ones that we carried we carried and then finally because we're going to and then finally because we're going to do this a third time with four in all do this a third time with four in all three of these numbers we have to again three of these numbers we have to again add zeros but this time we add two we add zeros but this time we add two we add an extra zero each time add an extra zero each time and then we do 4 times 3 which is twelve and then we do 4 times 3 which is twelve carry the one four times two is eight carry the one four times two is eight plus one is nine four times one is four plus one is nine four times one is four and then we add all of these together and then we add all of these together at the end at the end it was zero and one that's six one it was zero and one that's six one five five so we get fifty six thousand and eighty so we get fifty six thousand and eighty eight which is the exact answer that eight which is the exact answer that they told us in the example on the neat they told us in the example on the neat code website my plan is is to write code code website my plan is is to write code that can do this that can do this process and so we're going to need to process and so we're going to need to keep track of a lot of different things keep track of a lot of different things here and now that we've seen this done here and now that we've seen this done by hand I think it's easier to think by hand I think it's easier to think about what variables we need in what about what variables we need in what process we need to follow process we need to follow so to start out with so to start out with I know that we're going to need I know that we're going to need a carry variable to store whenever we a carry variable to store whenever we have to carry the one when we're doing have to carry the one when we're doing the multiplication the multiplication so I know we'll need a variable for that so I know we'll need a variable for that I know that we're also going to need a I know that we're also going to need a way to store way to store the final answer the final answer so like I just showed we need to add so like I just showed we need to add together each of these numbers that we together each of these numbers that we get at each successive step into the sum get at each successive step into the sum so my plan is going to be to have a sum so my plan is going to be to have a sum variable and each time I calculate one variable and each time I calculate one of these intermediate values I will add of these intermediate values I will add it to the sum so at the end we get the it to the sum so at the end we get the correct answer down here another thing we're going to need is a way to keep track of the current number that we're forming and what I mean by that is my plan will be to compute these values one by one so I'll first have to find the eight then the three then the seven I need to store all of those somewhere which I'll do in the current variable and then once I have the full value I will go ahead and add that to the sum and I think how I'm going to keep track of the current is with a Q data structure I'm not sure if we've talked about those yet on the channel but basically it's like an array but you can add easily to both ends and the reason I don't want to use an array here is because I'm going to be kind of working backwards I'm going to add the 8 first then the 3 then the seven so I'm going to be adding to the left hand side of whatever data structure I use which isn't really good for arrays because they append to the right hand side so I'm going to use a Q and I'll show you how to easily make a cue it's actually built in to python which is really nice then there's one more thing I think that I need which is I need a way to handle the fact that I have to add these zeros each time we move on to the next number that we're finding with our multiplication and I'm going to make that a variable called Factor I'll start with it equal to 1. because at the beginning we just multiply whatever we get by one but then after we compute the next value which is 615. we need to then add a zero to the end of it so we can multiply it by 10. same with the next value when we find that it's 492 we need to add two zeros to the end of that so we can multiply by a hundred so basically this Factor variable I'm going to use to keep track of what I need to multiply the value of whatever step online I'll multiply it by factor and that will leave me with the value that I'll actually bring to sub so that was a lot of info let's walk through the problem again for maybe a step using these variables that I just described so we can see how this is going to actually work so I'll write that again and this time I'm not going to do any math over here I'm only going to use the variables that I created to do everything so we'll start out by doing six times three just like last time and that equals eighteen so we know that there's an 8 that we insert into the Q and then we carry the one so next we would do five I'm sorry we would do six times two like this and that equals 12 but we have to remember to add the one from the carry so we actually get 13. meaning we'll put a 3 here and the carry stays is one because it's we're carrying one again now I do six times one which is six but then we need to add the one from the carry so we get seven and we'll just add that in to current and that's all we have to do so now we can clear the carry we can clear current and instead add that value to sum and again because the factor is currently one we don't need to do anything we don't need to add any extra zeros so we're finished with the first step I guess I'll go ahead and do all three so we can see how it works the whole way through so now we're going to start with the five and do five times three which is fifteen so we'll add the 5 to the Q and put the one in the carry then we'll do 5 times 2 which is 10 plus the one from the carry gives us 11. again we keep the one in the carry finally we'll do five times one which is five plus the one gives us 6. and now this time because I forgot to do this before I started this step but we need to increase the factor to 10 for this iteration which will allow us to multiply 615 by the factor so we'll add an extra zero there and then we'll bring that up to the sum and add it so this ends up being plus six one five zero zero now we can clear the carry clear the queue and what I should have done last time increase the factor by multiplying it by 10. now our final step we are on the four now so we do four times three which is 12. so we'll write down the two carry the one then we'll do 4 times 2 which is 8 plus the carry gives us 9. and finally four times one just gives us four and now because the factor is a hundred we need to multiply current by a hundred which adds the two zeros and finally we can clear and finally we can clear everything and because there are no more everything and because there are no more steps to process our final answer is steps to process our final answer is going to be the sum of those three going to be the sum of those three numbers numbers and if we look these three are the same as these three so we know that we are indeed going to get the final answer which is the same for both of them so I think this setup is what I'm going to go for and we'll be able to iterate over each of these numbers just using a nested for Loop so now let's jump to the code to see how we're going to do this right so the first thing that we need to do is actually import the Q functionality that I mentioned that we're going to use for the current which I am showing on the Whiteboard so we can do that by saying from collections import DQ is the name in Python and DQ is just the Q functionality and then I'll show you how to append a value to the left to insert something into the queue when we need that so the first thing I need to do is initialize my sum which I can set to zero as well as the factor which I will set as one and these are two of the four variables that I'm going to need the other two I need to reset each time the loop iterates so I'll add those in just a moment so the first thing I'm going to do is just like we showed on the Whiteboard I'm going to Loop over the second number so the bottom one starting at the six and then I'll work my way to the left so we will start by looping over num two so we can say for I and this is going to be looping and this is going to be looping backwards starting from the end of num2 backwards starting from the end of num2 and going back to the beginning I've and going back to the beginning I've talked about this in a previous video talked about this in a previous video but the way we can do that but the way we can do that is start at the length is start at the length of num2 of num2 minus one minus one then we're going to go until we reach then we're going to go until we reach negative one and we will decrement each negative one and we will decrement each time and going until we reach negative time and going until we reach negative one sounds weird but that's because it one sounds weird but that's because it is exclusive of the end bound so it'll is exclusive of the end bound so it'll stop at zero stop at zero so this is how we Loop over num2 so this is how we Loop over num2 backwards backwards and then we have to do the same thing and then we have to do the same thing for for the first number number one so we're the first number number one so we're going to Loop over num2 and for each going to Loop over num2 and for each value we have to Loop over all of num value we have to Loop over all of num one one so we can pretty much say the same thing so we can pretty much say the same thing for J and range for J and range this will be the length of num one this will be the length of num one minus one minus one and again uh we'll just say minus one and again uh we'll just say minus one and minus one and minus one and this is also where I can add the and this is also where I can add the other two variables so we need currents other two variables so we need currents and then we also need and then we also need carry right which I already done on the carry right which I already done on the Whiteboard there so carry we can start Whiteboard there so carry we can start out as zero because there won't be any out as zero because there won't be any carry at the start carry at the start current I can just set as DQ current I can just set as DQ and this is how you initialize an empty and this is how you initialize an empty cue using the DQ library that we cue using the DQ library that we imported imported great so now that we have both of those great so now that we have both of those the first step every time like I showed the first step every time like I showed on the Whiteboard is just to take the on the Whiteboard is just to take the first value first value and multiply them together and we need and multiply them together and we need to add any carry that might be there so to add any carry that might be there so we multiplied the two numbers and then we multiplied the two numbers and then add the carry if there is any add the carry if there is any so I'll say product so I'll say product equals and this is the one time where we equals and this is the one time where we have to convert the values into integers have to convert the values into integers because we just simply can't perform because we just simply can't perform multiplication without having integers multiplication without having integers at some point so this is perfectly at some point so this is perfectly allowed and completely following the allowed and completely following the rules of the problem rules of the problem but we can say product equals int but we can say product equals int num to num to a position I a position I and we can say times int and we can say times int ENT num1 position ENT num1 position J J like that so that's multiplying the two like that so that's multiplying the two numbers together and then we need to add numbers together and then we need to add whatever the carry is now the carry whatever the carry is now the carry starts at zero but as we go through the starts at zero but as we go through the problem I'm gonna set the carry based problem I'm gonna set the carry based upon what we figure out is the solution upon what we figure out is the solution to this multiplication problem to this multiplication problem so then we can say so then we can say we need to append whatever we get here we need to append whatever we get here the current because remember the current because remember um on the Whiteboard for example say um on the Whiteboard for example say that this results in eight that this results in eight we need to set eight we need to set eight in our current so basically we need to in our current so basically we need to put an 8 here and a one up here put an 8 here and a one up here so how do we do that so how do we do that so we can say current dot and the syntax so we can say current dot and the syntax here is okay and left here is okay and left which means we're going to place which means we're going to place whatever value on the left hand side of whatever value on the left hand side of the queue and insert it the queue and insert it we need to append product we need to append product which is in this case 18 when we which is in this case 18 when we multiply 6 and 3. multiply 6 and 3. modular division modular division which is which is that symbol that symbol by 10 because if we take any number and by 10 because if we take any number and we do modular Division 10 it always we do modular Division 10 it always leaves us with the ones place leaves us with the ones place so this will just take 18 and give us 8. so this will just take 18 and give us 8. and we'll append that on to current and we'll append that on to current then the other value which is the carry then the other value which is the carry we can set that equal to again it needs we can set that equal to again it needs to be the one and we can get that to be the one and we can get that by saying by saying product product integer division integer division because if we do 18 integer Division 10 because if we do 18 integer Division 10 we'll be left with 1.8 we'll drop the we'll be left with 1.8 we'll drop the decimals so we're left with one decimals so we're left with one now there is one additional thing we now there is one additional thing we have to consider here which is have to consider here which is in the case where in the case where for instance for instance we get to four or we get to the end we get to four or we get to the end and which is index zero and which is index zero at that point we don't want to append to at that point we don't want to append to current whatever the solution is modular current whatever the solution is modular Division 10 because if there's a carry Division 10 because if there's a carry we just need to add it what I mean is we just need to add it what I mean is for instance for instance if this instead of being a one was a if this instead of being a one was a nine nine and so on our last and so on our last our last calculation 4 times 9 is 36. we our last calculation 4 times 9 is 36. we can't just write 6. and carry the 3 can't just write 6. and carry the 3 because there's nowhere else we're not because there's nowhere else we're not going to do any more calculations with going to do any more calculations with the three we need to write the 3 with the three we need to write the 3 with the six so the Q needs to get both 3 and the six so the Q needs to get both 3 and 6. so we don't want to actually do the 6. so we don't want to actually do the modular division by 10 in that case modular division by 10 in that case so basically if J equals equals zero so basically if J equals equals zero meaning we're at the very last case meaning we're at the very last case we want to say and again I still want to we want to say and again I still want to do this do this in the other case so I'll just copy and in the other case so I'll just copy and paste that paste that but if J is 0 we just want to append the but if J is 0 we just want to append the full product we don't want to cut off full product we don't want to cut off any values we just need the whole thing but in the case where we're not on zero we only want the ones and then we will we will add the carry so that looks that looks good and then once we come out of this we need to do I guess something sort of tricky which is we now have current which is a q of all the values so for instance say we have 36 in there like in the case on the Whiteboard we need to take those values and we need to add them onto the sum the way we can do that is a little bit tedious in Python so we need to convert an array basically because a q is just an array we need to convert that into an integer and then add it to the sum the way we do that is if I'm not mistaken there's a few different ways but we can say sum plus equals and then we can do so basically when we do this step by so basically when we do this step by step step in Python a map function takes in Python a map function takes some function in this case it would be some function in this case it would be Str which means convert something to a Str which means convert something to a string string we want to do that to all the values in we want to do that to all the values in the current the current so this will take every value in current so this will take every value in current and convert it to a string and convert it to a string we want to join that set of strings with just the empty string so we can say empty string dot join this this looks funny but this is how you convert a array of something and smush it all together so we're taking every value in current and joining them all together and then we need to of course convert all of that to an integer and add that to some now I think we're missing one component which remember this Factor thing after we calculate current we need to check hey what's the factor and multiply that by current so I can just do that here so what this is saying is after we perform all the calculations for a given subset of the problem we're left with current which is a queue of all of the values we're going to combine that together into a string convert it to an INT because this is how we convert an array of integers into just a single integer and then we'll multiply that by factor and all of that will get added to the sum variable which we're going to keep track of over time finally we cannot forget to make sure that we multiply Factor by 10. so Factor times equals 10. at the very end we can return we just want to return sum but remember the problem once it is a string and we have it as an integer so we need to change this to our string so let's give that a run see if we've solved the first cases which will pop up down here and we have that passes for both of them yeah and that's working yeah and that's working it's good for memory it's it's not it's good for memory it's it's not amazing for runtime and I'm not quite amazing for runtime and I'm not quite sure why there's probably a a nicer way sure why there's probably a a nicer way to solve this but to me this one made a to solve this but to me this one made a lot of sense this is what came to mind lot of sense this is what came to mind first and I hope this has been first and I hope this has been insightful insightful so let me know in the comments if you so let me know in the comments if you have any other questions or if you know have any other questions or if you know a better way to figure this out I'd be a better way to figure this out I'd be interested to take a look at it see you interested to take a look at it see you in the next video | 2024-03-20 09:24:23 | 43 | LeetCode #43 (Multiply Strings) using Python | Solving all 150 NeetCode Problems | Episode 32 |
|
kyc7P1VgP-A | so hey guys welcome to my channel i am sithis and today we will be doing sithis and today we will be doing another very interesting problem from another very interesting problem from the lead code daily challenge day 25. the lead code daily challenge day 25. that is the lead code problem number that is the lead code problem number 1029 two city scheduling 1029 two city scheduling in the problem statement we are given a in the problem statement we are given a cost array where cost of i is basically cost array where cost of i is basically a pair of a cost and b cost where the a pair of a cost and b cost where the cost of flying the eighth person to the cost of flying the eighth person to the city a is a cost and the cost of flying city a is a cost and the cost of flying the eighth person to the city b is b the eighth person to the city b is b cost cost basically what we have to do is to basically what we have to do is to return the minimum cost to fly every return the minimum cost to fly every person to a city such that exactly n person to a city such that exactly n people arrive in each city people arrive in each city and i believe the question is pretty and i believe the question is pretty easy to understand and it will be more easy to understand and it will be more clearer when we will discuss the sample clearer when we will discuss the sample test cases so this is our first test case where we are given four pairs of a and b cost and we have to find the minimum cost to and we have to find the minimum cost to send half of the people to city send half of the people to city a and another half to city b for the first pair we see that we are given a value of 10 and 20 out of which we see that 10 is minimum so we decided that the person 0 must go to the city a for the second pair we are given a value of 30 and 200 out of which we see the 30s again minimum as a result we decide that this person must also go to the must also go to the city a for the next pair also we are given two values that is 450 and out of which we see that 50 is the minimum as a result we decided that that this person must go to ctp e and for the next pair as well we are given two values that is 30 and 20 out of which we see 20 is minimum as a result we again decide that this person must also go to the city b as a result our total cost of sending two people to city a and two people to city b comes out to be 110 which is our correct output as well so this is our second sample test case and here also we are given uh six pairs of cost of sending each person to either to city a or city b here we are also given the output 1859 which tells us that the minimum cost of sending these six people to either of the city a or city b is one eight five nine only since the explanation is not given we can't say which people goes to which city and you might say that all we have to do is to traverse the array and find the mean from the pair and sum it that should be our answer will it be let's try so for the first pair minimum is obviously 259 so we would be taking 259 for the second pair minimum is 54 so we'll be taking 54 for the third pair minimum is 667 so we'll be taking 667 for the fourth pair we see that 139 is minimum so we must take that in the fifth pair 118 is the minimum so we must take that also and as for the last two pair we see that 469 is minimum so we must take that and you might say that the sum of all this value will be the minimum possible value to send all the person to either city a or city b but here we are missing a very important point that we have to send and by two people in each of the city so about this distribution where most of the person is going to the ctp is actually not correct so you might say that okay we will try to find the first and by two smallest cause to travel to city a and some with the rest of the cost to travel city bay again we will try to find n by 2 smallest cost to travel to city b and sum with rest to the city a and mean out of both the sum should give us the minimum sum right so what can be done let's see so what can be done let's see let us suppose that we have only two let us suppose that we have only two person person person person x and person x and person why and for person x the cost to travel why and for person x the cost to travel city a is 8 and the cost to travel city city a is 8 and the cost to travel city b is 10 and for person y the cost to b is 10 and for person y the cost to travel city a is 15 and the cost to travel city a is 15 and the cost to travel city b is 20. travel city b is 20. now how would you distribute them such now how would you distribute them such that the cost of sending either of them that the cost of sending either of them to either of the city is minimum to either of the city is minimum now since we must assign one of them to now since we must assign one of them to city a and one of them to city b now in city a and one of them to city b now in spite of sending person x to city a and spite of sending person x to city a and person y to city b which nearly gives us person y to city b which nearly gives us 28 the optimal solution would be to send 28 the optimal solution would be to send person x to the city b and person y to person x to the city b and person y to the city a which will give us the the city a which will give us the traveling cost of only 25 which is traveling cost of only 25 which is definitely minimum than the previous definitely minimum than the previous cost we had found cost we had found so d2 we find an observation so d2 we find an observation we get three observation the first and we get three observation the first and most important observation is that the most important observation is that the relative difference is more important as relative difference is more important as compared to choosing the cost greedy compared to choosing the cost greedy in this test case that is 8 minus 10 in this test case that is 8 minus 10 minus 2 and 15 minus 20 that is minus 5 minus 2 and 15 minus 20 that is minus 5 we see that the relative difference of we see that the relative difference of person y person y is smaller compared to the relative is smaller compared to the relative difference of person difference of person x as a result it would be more cheaper x as a result it would be more cheaper to send person x to city a as compared to send person x to city a as compared to sending person x to city a to sending person x to city a and since we are bound to sending only and since we are bound to sending only one of them to either of the city one of them to either of the city we decided that we would send person y we decided that we would send person y to city b and person x to city a which to city b and person x to city a which would definitely give us the optimal would definitely give us the optimal result result our second observation is that our second observation is that regardless of what the individual cost regardless of what the individual cost be be only the relative difference matters only the relative difference matters again this is evident from the same test again this is evident from the same test case as well case as well no matter how much the cost of sending no matter how much the cost of sending person x to city a person x to city a all the cost of sending person y to city all the cost of sending person y to city a be it a be it only the absolute difference or the only the absolute difference or the relative difference matters relative difference matters and our third observation is that we and our third observation is that we have to greedily choose the cost based have to greedily choose the cost based on the relative difference on the relative difference we will find the relative difference we will find the relative difference each of the person to travel are in each of the person to travel are in either of the city and sort them after either of the city and sort them after sorting we will greedily choose sorting we will greedily choose the first n by 2 is the first n by 2 is smallest and last n by two values smallest and last n by two values that would give us the optimal solution that would give us the optimal solution so our algorithm comes out to be so our algorithm comes out to be something like this first of all we have something like this first of all we have to find the relative difference that is to find the relative difference that is the cost of eighth person to travel the cost of eighth person to travel through city a minus cost of eighth through city a minus cost of eighth person person to travel city b to travel city b after finding for each of the person we after finding for each of the person we have to sort the relative difference in have to sort the relative difference in ascending order if any i th difference ascending order if any i th difference is smaller or negative it means that it is smaller or negative it means that it will be cheaper to travel to city a will be cheaper to travel to city a but if any eighth difference is larger but if any eighth difference is larger it simply means that it would be cheaper it simply means that it would be cheaper to travel to city b so at the end we to travel to city b so at the end we will greedily sum the first and by two will greedily sum the first and by two cost to travel to city b and next n by cost to travel to city b and next n by two travel cost to city that will be our two travel cost to city that will be our result result now let's try to solve our third sample now let's try to solve our third sample test and see if our algorithm actually test and see if our algorithm actually works or not works or not so this is our cost for each of the so this is our cost for each of the person and person and and as our algorithm say first of all we and as our algorithm say first of all we need to find the relative difference need to find the relative difference for this the relative difference is for this the relative difference is minus 54 for this the relative minus 54 for this the relative difference is minus 262. for this the difference is minus 262. for this the relative difference is minus 172 for relative difference is minus 172 for this this the relative difference is minus 476 for the relative difference is minus 476 for this the relative difference is 76 for this the relative difference is 76 for this the relative difference is 397 for this the relative difference is 397 for this the relative difference is 291 and this the relative difference is 291 and for this test the relative difference is for this test the relative difference is 591. 591. now as per our algorithm our second step now as per our algorithm our second step is to sort the relative order in is to sort the relative order in ascending order ascending order so let's do that so let's do that [Music] [Music] and this is our sorted relative and this is our sorted relative difference difference as our n is equal to eight as our n is equal to eight from our algorithm we see that first n from our algorithm we see that first n by two people must travel to city a and by two people must travel to city a and the next n by two people must travel to the next n by two people must travel to city b city b as a result these four people must need as a result these four people must need to travel to city a and the next four to travel to city a and the next four must need to travel to city b so we must need to travel to city b so we would sum this values and our sum would would sum this values and our sum would come something like 3086 which is come something like 3086 which is actually our correct answer so we can actually our correct answer so we can say that our algorithm is absolutely say that our algorithm is absolutely correct now let's see how we implemented correct now let's see how we implemented this algorithm in our code this algorithm in our code so here is our code and inside our code so here is our code and inside our code and the first thing that we are doing is and the first thing that we are doing is to find the relative difference for to find the relative difference for eighth person between the cost to travel eighth person between the cost to travel to city a and the cost to travel to city to city a and the cost to travel to city b and we are storing it along with the b and we are storing it along with the ith index so that in the later value we ith index so that in the later value we can retrieve the cheaper cost next we can retrieve the cheaper cost next we are sorting our relative difference in are sorting our relative difference in ascending order ascending order and for the last part since our relative and for the last part since our relative difference array has already been sorted difference array has already been sorted we can safely assume that choosing first we can safely assume that choosing first and by two people to go to the city a and by two people to go to the city a and the next and by two people to go to and the next and by two people to go to the city b will give us the most optimal the city b will give us the most optimal result result thus we are doing the same and returning thus we are doing the same and returning our sum let's see if it successfully our sum let's see if it successfully execute execute which it does and let's submit to see if which it does and let's submit to see if our answer is correct or not our answer is correct or not which is and that is how we solve this which is and that is how we solve this very interesting problem to ct very interesting problem to ct scheduling hope you liked my solution we scheduling hope you liked my solution we will meet tomorrow again with some new will meet tomorrow again with some new problem until then keep going keep problem until then keep going keep learning learning [Music] [Music] so so [Music] [Music] do do [Music] | 2024-03-25 15:20:24 | 1,029 | Two City Scheduling | Leetcode 1029 | Greedy | Spill Code |
|
TO5zsKtc1Ic | Hello hello guys welcome back to take two this video will see press entry maximum video will see press entry maximum after we problem system list date one after we problem system list date one of the dead skin challenge so let's look at problem problem of the dead skin challenge so let's look at problem problem Thursday maximum can Thursday maximum can start a node for example you can see some 99 subscribe and subscribe 99 subscribe and subscribe 99 subscribe and subscribe the 1995 me stan at any point but it's always for the 1995 me stan at any point but it's always for example service and subscribe and not good quote 20 second example you can directly and get started and does not prevented this not to enter maximum is equal to 50 Root of the tree Root of the tree Root of the tree it and not improved by the third point is that can it and not improved by the third point is that can not minimum minimum set the volume not minimum minimum set the volume to the value - 151 - 151 - subscribe is subscribe is that we will sleep example you can see the that we will sleep example you can see the Maximum Edit Starts From This Note Maximum Edit Starts From This Note 2 End Service Note 3 And Fear And Use 2 End Service Note 3 And Fear And Use Not To Wear Is The Maximum Different From This Not To Wear Is The Maximum Different From This Note To Do The Root Of The Maximum Subscribe Note To Do The Root Of The Maximum Subscribe 598 Veer Veer Veer Veer Is Not The Subscribe 598 Veer Veer Veer Veer Is Not The Subscribe More than 90 Subscribe Subscribe Now More than 90 Subscribe Subscribe Now To To To Via Batuk E Pray For Maxim Switch Is Already Front Should You Will Handle Case Number 39 Minutes To Compare All Other Cases For Each And Every Month The Very Latest Example Will Take Away All Subscribe Number One Is The Maximum Compared With Its MAXIMUM OF THE THING WHICH WILL TAKE CARE OF MAXIMUM OF THE THING WHICH WILL TAKE CARE OF ALL THE NUMBER SUBSCRIBE REMEMBER MAXIMUM SUBSCRIBE TO PROCESS DISTRICT UNDERSTAND ALGORITHM SOUNF JUST PROCESS DISTRICT UNDERSTAND ALGORITHM SOUNF JUST STARTING AND DRUT NO WILL BE STARTING AND DRUT NO WILL BE MAKING CALLS AND WILL MAKE IT WILL MAKING CALLS AND WILL MAKE IT WILL BASICLY POSTERS FROM SUBSCRIBE WHAT BASICLY POSTERS FROM SUBSCRIBE WHAT BASICLY POSTERS FROM SUBSCRIBE WHAT from left to right Subscribe nodes in the maximum 100 no which will not be done current note will make the validity equal to what should discuss denotes that will take Word Which Will Be Word Which Will Be Word Which Will Be The Name Of The State And The Name Of The State And Subscribe Subscribe To The Channel Absolutely Complete Subscribe Subscribe To The Channel Absolutely Complete The Volume Maximum All The Best Choice Number The Volume Maximum All The Best Choice Number One Is The Value Of Root Will Be Subscribe Must Subscribe Dahan Disconnect Note Will Fall In The Maximum Disconnect Note Will Fall In The Maximum Pass Pirate's Paradise Pass Pirate's Paradise Pass Pirate's Paradise 98100 Test To You Can See In To The Con Is The Left Side Subscribe Will Compete With Now School subscribe And 2008 Will 2008 Will Be 810 Will Sufis To Ring Be 810 Will Sufis To Ring Velvet Navodaya Result Will Actually Velvet Navodaya Result Will Actually Velvet Navodaya Result Will Actually Initially Enter Because The Can Be Any Value Soul Valley School Negative They Will Be Replaced With It 21 2012 Subscribe Maximum 8282 Click A Subscribe Button On Left Side Mein Ka Macrame Samay Ajju Can See In This Time The Mein Ka Macrame Samay Ajju Can See In This Time The Will Have Been Latest Current Note-2 Will Have Been Latest Current Note-2 Handsfree Mode Turn On This Nuvea Research That Handsfree Mode Turn On This Nuvea Research That Is Not One Can Get Rid Of Dandruff Is Not One Can Get Rid Of Dandruff Russian Its Too Front To The Self Written Notes Russian Its Too Front To The Self Written Notes In Nod Nod For The Only In Nod Nod For The Only Don't Forget To Subscribe To Divya Divya Divya Channel And Subscribe to alarm set the current note volume which is point well so this is the maximum straight path value sweet will start this eighth included in this way you will know this for this you will compete with karan adhir will Roof Top Rain Roof Top Rain Roof Top Rain Water From This Point Water From This Point Subscribe Now to Receive New Updates Subscribe Now to Receive New Updates Comparing with the Guardian Comparing with the Guardian Practice of Previously Front Maximum Practice of Previously Front Maximum Value with the Best Value Do the Maximum Value with the Best Value Do the Maximum End Subscribe Must Subscribe Know What Will End Subscribe Must Subscribe Know What Will Not Return Return Face Value Not Return Return Face Value Only subscribe to Only subscribe to Only subscribe to The Video then subscribe to the Page if you liked The Video then subscribe to That SDO of newly formed board soft That SDO of newly formed board soft consider about 2820 plus five plus minus 10 which will be consider about 2820 plus five plus minus 10 which will be equal to - 500 you can see but clearly equal to - 500 you can see but clearly s s s value so and value here will be 125 check the the the the the the the the subscribe button more complain against its value is valued at increase request 231 know what about this Valueless Comparison and K to And Valueless Comparison and K to And Valueless Comparison and K to And S One Should Discuss the Class 12th Part S One Should Discuss the Class 12th Part subscribe and subscribe 802 Value Will Compete Against Subscribe Must Visit Will Return Value Which is the Value - 2nd T20 - 132 Subscribe Jhalda Maximum Value from the White Part Left for Maxim Left for Maxim Left for Maxim Time Elapsed Plus Puberty Exactly 12th Part Time Elapsed Plus Puberty Exactly 12th Part Plus Two Plus Minus 181 Switch Off the Face Plus Two Plus Minus 181 Switch Off the Face Value - Wave 2K Considered S to the Root of Value - Wave 2K Considered S to the Root of the Subscribe Thank You Will Not The Third the Subscribe Thank You Will Not The Third Result Will Be Amazed With This To-Do List Processing By the first to 10th result date By the first to 10th result date By the first to 10th result date final maximum first value knowledge center problem final maximum first value knowledge center problem and if you are able to understand the and if you are able to understand the running time complexity of running time complexity of algorithm in just three times subscribe algorithm in just three times subscribe the channel please subscribe The the channel please subscribe The Video then subscribe to subscribe Video then subscribe to subscribe quick comparing the maximum of all quick comparing the maximum of all quick comparing the maximum of all Cases To Return Result No Way Can Only Returns The Case One Value Soweer Viewers Problem Side And Solution Different Languages And Placid Like Share And | 2024-03-21 11:20:22 | 124 | Binary tree maximum path sum | Leetcode #124 |
|
yn6QoEECv8s | hello welcome to my channel i'm here to do my honzolico challenge do my honzolico challenge and today we have leeco 36 and today we have leeco 36 valid pseudocode so this question is valid pseudocode so this question is really classic really classic so we said determine if a nighttime so we said determine if a nighttime knight knight pseudocode board is valid so only the pseudocode board is valid so only the fuel cell fuel cell needs to be validated according to the needs to be validated according to the following rules following rules so first each rows must contain digits 1 so first each rows must contain digits 1 to 9 to 9 without repetition 2 without repetition 2 each column must contain the digit 1 to each column must contain the digit 1 to 9 without repetition 9 without repetition 3 each of the 9 3 x 3 3 each of the 9 3 x 3 sub boxes of the grid must contain sub boxes of the grid must contain the digit one to nine without repetition the digit one to nine without repetition so like we used to play uh so like we used to play uh pseudocode before and this is one of the pseudocode before and this is one of the map map in here so it said for row in here so it said for row right here so we have one two nine right here so we have one two nine there's no duplicate in here so one to there's no duplicate in here so one to nine we all nine we all put it in this box and in put it in this box and in column same thing we have one two nine column same thing we have one two nine filled in this box filled in this box and they all distinct no duplicate in and they all distinct no duplicate in either row and column and the last either row and column and the last is in each box we have one to nine is in each box we have one to nine no duplicate in here so in that case no duplicate in here so in that case then we'll see this uh current then we'll see this uh current pseudocode map pseudocode map is valid so for example if five is here is valid so for example if five is here and if i appear either somewhere here or and if i appear either somewhere here or somewhere in here somewhere in here so if it's invalid in in this row so if it's invalid in in this row and invalid in this column same thing is and invalid in this column same thing is here if here if any duplicate three in here another any duplicate three in here another three in this three in this grid then is not valid for um the easy way to think about this question we can have an array of set in here for this column array of set of the rows then we if we have five we go to the first index of that array and put five into the first set it puts three in the second set if and we keep looping all the way to the end of this every number in this group the big table if we see five in here and we go up to hit the array and the first hash set in here if you put five again inside that headset that headset already have five which the first five in here then we return false because you can have duplicate same thing in here you can see this headset in this index in the this index for this row so they all co-related and then that's one of the way that we can check and also the box to have another headset for this box this box this box but overall the code is over complicated and it's just a lot of work and a lot of code it takes a lot of time to code it you might have a lot of bugs so that's one way this really smart way that we discover is so we can think about a case like now we have uh we only need one headset and when we look through every integer in here and we see 5 for example and 5 is located in column 0 and we can see i'll put c which index is c0 so what number is 5 so we put c 0 column 0 and 5 as a string inside that uh headset and also in the same time this is row is row 0 5 that mean in the headset will contain oh row zero only have one fight so now we have five ready later on on the row to traverse this line if you see if for example 7 become 5 if you see duplicate 5 right here and we will keep we will find out it is also in row 0 and if this is 5 it will have row 0 5 again so we bring this inside the headset and it's see that has i already have uh i mean row 0 5 then that's not valid so now we look through everything keep putting those number inside this headset uh for the grid and i will show you in the in the code and how do we do the grid so basically we use the index divided by 3 then that will be the grid number for example in here is grid 0 and 0 grid 0 1 0 2 here is grid 1 0 how would come up the one i mean how it comes with 0 is in here the row right now is 0 1 2 so all this number divided by 3 we have 0 as this row 0 in here and here also it's just a mathematic calculation um we will have only one set so now the set is done then we have to so now the set is done then we have to loop through every number just the double for loop for looping all now this double for loop is looping now this double for loop is looping number from here number from here to here all the way to the last number to here all the way to the last number in here in here let's see what we're missing let's see what we're missing so now this is going like this so now this is going like this and this okay so we have we get the current charge called current will be i and j so this is current uh character so if oh sorry i didn't show you um of that array so now if of that array so now if the input is thought we don't need to the input is thought we don't need to care about it it's just care about it it's just empty in here so we only care about empty in here so we only care about uh number which is a valid for integer uh number which is a valid for integer so f so we only care so f so we only care when the when the current character is not dot current character is not dot so that will be an integer so that will be an integer and then we will have set at we have um row like what we said we put row plus i is the row and plus current which is the current so now what it means is in here we so now what it means is in here we have okay this is example have okay this is example like in the first integer here we have like in the first integer here we have row zero five row zero five so we have row which is zero so we have row which is zero and five column and five column [Music] [Music] zero the first call i mean zero the first call i mean the first column which is indexing zero the first column which is indexing zero column column zero five so contain all the information zero five so contain all the information so we put that so we put that this string this string inside the set if it doesn't have this inside the set if it doesn't have this the set doesn't have this string it will the set doesn't have this string it will add it add it to the set to the set for example if the set already had r05 for example if the set already had r05 then it will return uh next i mean if it then it will return uh next i mean if it returns returns false because it's already contained false because it's already contained the set actually contain this string so the set actually contain this string so this is one of the function this is one of the function for headset for set for headset for set for the add method so you can check for the add method so you can check and things that have the duplicate and things that have the duplicate inside the set already inside the set already then this if function will be valid then this if function will be valid after that will return after that will return false right false right but not only that this is only the roll but not only that this is only the roll away away we also need to check the set we need to add column plus j is j's column right now plus curve and also we need to check that dot plus i plus i divided by three plus j divided by three plus j di by 3. like what we mentioned about the grid like this grid and then this number will like this grid and then this number will be be uh the row and this number will be uh the row and this number will be the column and that's it i think that the column and that's it i think that will will solve the case it's kind of too solve the case it's kind of too long in here f long in here f f okay f okay after this for loop we see no problem after this for loop we see no problem with that we just return true what's going on in here what's going on in here let me double check okay i found out this film may stick right here so we need to add this because we need to check if it's added inside already and another mistake in here so because we need to inside this string inside this string so we have grid current number in so we have grid current number in this column row this column row and column okay i think that should and column okay i think that should be it cool let's submit it and that's it for this question uh yeah i think it's really clever for this solution and if you still have any question please comment below and i will see you in the next video | 2024-03-20 08:56:53 | 36 | Leetcode 36 - Valid Sudoku (JAVA Solution Explained!) |
|
0FPdOoht5Rc | hi guys welcome to algorithms made easy today we will go through the day 18 today we will go through the day 18 problem 8 index part 2 please like the problem 8 index part 2 please like the video and if you're new don't forget to video and if you're new don't forget to subscribe to our channel so that you subscribe to our channel so that you never miss any update given an array of never miss any update given an array of salutation sorted in ascending order salutation sorted in ascending order where each citation is a non-negative where each citation is a non-negative integer write a function to compute the integer write a function to compute the researchers edge index a scientist has researchers edge index a scientist has an index edge if edge of his or her n an index edge if edge of his or her n papers have at least edge citations each papers have at least edge citations each and the other n minus H papers have no and the other n minus H papers have no more than edge citation each for the more than edge citation each for the example given the input means the example given the input means the researcher has 5 papers in total and researcher has 5 papers in total and each of them had received 0 1 3 5 & 6 each of them had received 0 1 3 5 & 6 citations respectively since the citations respectively since the researcher had 3 papers with at least researcher had 3 papers with at least three citations each and the remaining three citations each and the remaining two with less than or equal to three two with less than or equal to three citations each her each index is 3 let's citations each her each index is 3 let's see it visually let's take the same see it visually let's take the same example so we can see that there are example so we can see that there are three values with value greater than or three values with value greater than or equal to 3 while other n minus H that is equal to 3 while other n minus H that is 2 less than or equal to 3 if you change 2 less than or equal to 3 if you change a value 3 to 4 we see that it does not a value 3 to 4 we see that it does not have any effect on the edge index it have any effect on the edge index it still has 3 values greater than or equal still has 3 values greater than or equal to 3 L 2 values less than equal to 3 if to 3 L 2 values less than equal to 3 if we change 3 to 2 the output changes to 2 we change 3 to 2 the output changes to 2 as now 2 values are greater than equal as now 2 values are greater than equal to 2 and n minus H that is 3 values are to 2 and n minus H that is 3 values are less than or equal to 2 let's see how to less than or equal to 2 let's see how to solve it solve it let's go through the first approach let's go through the first approach wherein we will iterate over the wherein we will iterate over the citations array of length n for each citations array of length n for each citation we check the below condition citation we check the below condition here n minus I will always give you the here n minus I will always give you the number of values greater than or equal number of values greater than or equal to the current value if the condition to the current value if the condition gets satisfied we return the value n gets satisfied we return the value n minus I if you do not get a value minus I if you do not get a value satisfying the condition we return 0 satisfying the condition we return 0 let's see it visually working with the let's see it visually working with the same example at the start same example at the start n is 5 and I will go through 0 to 4 n is 5 and I will go through 0 to 4 starting with the index 0 we see by starting with the index 0 we see by values with the value greater than or values with the value greater than or equal to zero which fails our condition equal to zero which fails our condition as five is not less than or equal to as five is not less than or equal to zero so we move forward again a zero so we move forward again a condition fails so we move forward this condition fails so we move forward this time the condition is satisfied as we time the condition is satisfied as we have three values with the value greater have three values with the value greater than or equal to three than or equal to three so we returned three the time complexity so we returned three the time complexity for this approach is o of n when the for this approach is o of n when the space complexity is o of 1 instead of space complexity is o of 1 instead of iterating over the whole array we can iterating over the whole array we can use binary search for this we initialize use binary search for this we initialize start to 0 and n to n minus 1 while start to 0 and n to n minus 1 while start is less than or equal to end we start is less than or equal to end we calculate the mint by using the formula calculate the mint by using the formula shown and if n minus med is equal to the shown and if n minus med is equal to the value of the citation at mid we simply value of the citation at mid we simply return n minus min else if the value is return n minus min else if the value is less than the citation at min we set the less than the citation at min we set the end to mid- pun else we set the start to end to mid- pun else we set the start to mid plus 1 at the end we return the mid plus 1 at the end we return the value for n minus start let's see it value for n minus start let's see it visually with an example initially start visually with an example initially start will be 0 and will be n minus 1 and we will be 0 and will be n minus 1 and we will calculate the min so the men will calculate the min so the men becomes 2 and the element at mid is 3 becomes 2 and the element at mid is 3 now we check our first condition and see now we check our first condition and see that it satisfies so we return in - mid that it satisfies so we return in - mid that is 3 the time complexity for this that is 3 the time complexity for this approach is o of login well the space approach is o of login well the space complexity is o of 1 here is the code complexity is o of 1 here is the code snippet also check out the link to the snippet also check out the link to the java code in the description below java code in the description below thanks for watching the video if you thanks for watching the video if you liked the video please like share and liked the video please like share and subscribe to the channel let me know in subscribe to the channel let me know in the comment what do you think about the the comment what do you think about the video | 2024-03-22 12:35:48 | 275 | H-Index II | Day 18 | [June LeetCoding Challenge] [Leetcode #275] [2020] |
|
sGhIaqiTN6o | Hai gas welcome to today's video and today we are going to do lead code problem 1008 going to do lead code problem 1008 which is named Construct Binary Search Tree which is named Construct Binary Search Tree from Prior Order Driver so basically from Prior Order Driver so basically we have a preorder area we have a preorder area and we have to construct a binary using this array. and we have to construct a binary using this array. And this binary And this binary search should be free okay so we will search should be free okay so we will see how we will approach this so see how we will approach this so first of all we know what is the first of all we know what is the relief of order care of proorder relief of order care of proorder first comes in proorder then comes the root then first comes in proorder then comes the root then comes left Right, Right, Right, if it was in order from this then I am if it was in order from this then I am sure that this is my sure that this is my root. The first element that comes will be my root. The first element that comes will be my root. Okay, so I know that right now root. Okay, so I know that right now my root is where the So, So, So, first of all, while making the tree, first of all, while making the tree, obviously we will travel from here 012345 because by doing these elements we have to make our binary. Okay, so now I have reduced my number by 8, which means it is zero, so I have This This This decision has to be made whether my index will decision has to be made whether my index will come on the right or on the left, so in binary come on the right or on the left, so in binary we already know that all the values that we already know that all the values that come on the left side of my root are come on the left side of my root are < roots of the note and < roots of the note and those on the right side become values. those on the right side become values. those on the right side become values. number, if we have a root, then my 5 A will go to the left side. I know it means up to 100, so can I say that all the notes in these are When will they come to the left of When will they come to the left of When will they come to the left of those values, when the range of those values is between mines to infinity, if you come to any node, any value, in this area, the values is between mines to infinity, if you come to any node, any value, in this area, the mines that belong to infinity, mines that belong to infinity, then it will come to the left side of my 8, then it will come to the left side of my 8, okay? okay? okay? similarly, which values will come on the right side of my 8, will they be my 8 and till infinity or can we say like this? Obviously this is non- inclusive because they should be given strictly greater, so we can also say seven like this Take the meaning that this is 8 and Take the meaning that this is 8 and Take the meaning that this is 8 and not inclusive, if the note is inclusive then not inclusive, if the note is inclusive then all the values less than 8 till infinity will all the values less than 8 till infinity will come in my left and then all the values except 8 to 8 till come in my left and then all the values except 8 to 8 till infinity will be infinity will be in my year, those values will all be on my left. in my year, those values will all be on my left. Coming to the right side, okay, I have come to Coming to the right side, okay, I have come to know this much, so now I can only do the same, know this much, so now I can only do the same, I can directly run the recursive function, I I can directly run the recursive function, I can run the can run the recursive function, what else will I do here, pass it here, I recursive function, what else will I do here, pass it here, I will pass it to me - 8 - Infinity will pass it to me - 8 - Infinity Tu 8 This is mine. Tu 8 This is mine. Tu 8 This is mine. here, the note that will come and similarly, for this mode, also keep building, meaning the note that will be built here, also keep building, meaning the note that will be built here, that minus infinity, you will be the that minus infinity, you will be the value of the note, its left range will be the value of the note, its left range will be the value of the note value of the note and similarly, well, Note will be here and similarly, Note will be here and similarly, Note will be here and similarly, what will be on its right, the range of its right child will what will be on its right, the range of its right child will be this, the value of North and be this, the value of North and infinity, so we have come to know from them also that infinity, so we have come to know from them also that if we make a note of a route, then if we make a note of a route, then in the route to its left, then note dot left. in the route to its left, then note dot left. I go to I go to note dot we will go to left right, okay so we have come to know about this approach, our okay so we have come to know about this approach, our approach was that first of all I am approach was that first of all I am this mother let that my note exists this mother let that my note exists mines infinity you mines infinity you mines infinity you because my fairy order has been given by driver cell, my current route is 8 but which node of the range to the left of 8 will come, Mines Infinity you come, Mines Infinity you come which node comes What will come on the right side of ' What will come on the right side of ' What will come on the right side of ' 8 Tu Infinity', what value 8 Tu Infinity', what value note will come? Similarly, we will keep making requests like this note will come? Similarly, we will keep making requests like this and we will get our answer. and we will get our answer. So, okay, our algorithm So, okay, our algorithm is like this, first of all we will is like this, first of all we will create note Our root note, what are we going to do after that? Second Corresponding left Android range, you are left and right okay tomorrow and then okay tomorrow and then what are we going to do after that, our root note, which has been what are we going to do after that, our root note, which has been made of our binary, we are going to return, so made of our binary, we are going to return, so step. step. step. r route note and created Okay, so now let's code it once and Okay, so now let's code it once and see, so first of all I'm here lay down see, so first of all I'm here lay down I and what will come in this, our dear I and what will come in this, our dear order one will come because we order one will come because we should know that should know that should know that so the free and these two will be our waiting and these two will be our waiting values, then after that we have to go to the next value every time values, then after that we have to go to the next value every time in ours, so this is to in ours, so this is to track the values and track these indexes. track the values and track these indexes. To do this, I am going to make an index To do this, I am going to make an index which will start from zero because which will start from zero because our egg zero is of best indexing, our egg zero is of best indexing, so we take this idea equal to zero. so we take this idea equal to zero. Okay, now first of all I will Okay, now first of all I will see what will be our base and then after that. After this, we ignore all the bases and now we directly apply our left and right tomorrow and before that, what are we going to do, our first note will be but in the example, we will create a tree note in the pre-order, then this will My tree note root is equal to you of Well of range and note, this is going to be our right range, this is going to be the Well of range and note, this is going to be our right range, this is going to be the right range, so this is going to be the right range, so this is going to be the left range which is passed to us and this is going to be right this is going to be right and now here what is going to be the left range of this is going to be the and now here what is going to be the left range of this is going to be the left range of this is going to Now, what can be our base? So, let's Now, what can be our base? So, let's see a little about how our base is, see a little about how our base is, if I have some range, if if I have some range, if my current note is on in this range, then obviously my current note is on in this range, then obviously I do not want to put that note here. Attack and I do not want to put that note here. Attack and Example: If my five Example: If my five Example: If my five my IDEX A goes from here, so should my seven be placed on the left of five, so this is the color, what does it mean that the range that has been passed in the range of five, We will We will We will create a note and attack him tomorrow, create a note and attack him tomorrow, if he is not in the arrangement then we are not going to if he is not in the arrangement then we are not going to attack, so we can write like this, attack, so we can write like this, first of all give the left range, meaning he If there If there If there is a note then we will not do anything so we will not do anything anyway we will return and now after that if and one base how or yes ke and now after that if and one base how or yes ke r jati which is if my index itself r jati which is if my index itself went out one you three four five if went out one you three four five if my index my index my index will I do if it becomes six, so here also we have to return null because no index exists in it, because I have gone directly to A, my index has gone to A, equal to the size of the date, so what I will do IF I DS = this note is equal you and what should be our left range then and what should be our left range then when I have seen this in the constant then the when I have seen this in the constant then the value of fairy order of any note is value of fairy order of any note is below one. below one. below one. my mines infinity can become -1 and my most right range right note will not be more than 1000, so I can keep ₹ 101, my right range will be kept in 100 one What is going to be done, the What is going to be done, the What is going to be done, the route is going to return our butt route is going to return our butt binary, so I return it binary, so I return it to BSP, it gets returned directly, okay, it is being accepted okay, it is being accepted and it is also getting submitted, so now we will do it once. and it is also getting submitted, so now we will do it once. and it is also getting submitted, so now we will do it once. you can also write it like this and if mine you can also write it like this and if mine comes here, okay, now I will create my new free order tree, then this will be free order tree, then this will be Renault route, equal to this, [music Okay, what happens is the Okay, what happens is the value is similarly applied in the root right, build GST and we pass the Priya order and now in its left trench right, infinity which is the right range which is already infinity which is the right range which is already passed, okay then that passed, okay then that passed, okay then that our route, then we do this tomorrow here in which we will pass and then something else after that, what is the route, created, increased, attacked in the left, left range route, well in the right, well of the route in the right and right The root done is fine, right now The root done is fine, right now The root done is fine, right now it is going smoothly and it is getting accepted, we will try to it is going smoothly and it is getting accepted, we will try to submit it once and it is also getting submitted, submit it once and it is also getting submitted, okay, now we will dry it very well okay, now we will dry it very well and understand what is actually happening. Here is my new page, Here is my new page, this is my tree, this is here, there is no problem then the right range then the right range which is passed which is passed and note, so so tomorrow we will write here zero Then what we do is, Then what we do is, Then what we do is, first of all and we add Idea Plus, so first of all and we add Idea Plus, so we made a route note, first of all, train remains -1 for 8 and right range is 1000, what we did is put left yesterday and And And And passed the right range, the value of the root which passed the right range, the value of the root which was eight, okay, then what happens after that, was eight, okay, then what happens after that, five itself, left range, left goes tomorrow five itself, left range, left goes tomorrow and then N. First of all, we have created this note and then N. First of all, we have created this note for 8 and for five. for 8 and for five. Also the idea gets flooded with you, here Also the idea gets flooded with you, here this note is created, the route is then flooded with IDEX, this note is created, the route is then flooded with IDEX, now we move from five to the left, tomorrow and one gets now we move from five to the left, tomorrow and one gets added, what does one do by itself, it added, what does one do by itself, it creates its own route, here IDEX + creates its own route, here IDEX + makes three. makes three. makes three. moves his left kal then the left range for one is near this, we will see first of all that for 1 kal is near his left range which is is fine. is fine. is fine. idea has become 3 and here it is inserted seven and what is the left range of seven put here see this is very important -1 then left range remains but right range Look logically now, Look logically now, can I hit seven to the left of one, then obviously I cannot hit seven to the left of one, so what we do is we return to our base, how Where is the Where is the Where is the value of note pre order of ID value of note pre order of ID Next is the right turn of five, so what do we do, the value of the root, we pass the left range and we pass the right range, but the was the value of the root, here and was the value of the root, here and there, the root there, the root there, the root is one and the right range was one's own right hand which is five and we put this tomorrow again for 7 and what happens here is again the same, Greater is given Greater is given Greater is given from one's right range also, hence this seven from one's right range also, hence this seven is again taken from the tag of and adds five. The one who moves to the right here adds Well, which Well, which Well, which is five and right range, which was eight and is five and right range, which was eight and again what do we put on seven tomorrow again what do we put on seven tomorrow because our IDEX is still free, because our IDEX is still free, so you also see our so you also see our note right now is between the left and right range. note right now is between the left and right range. This is my left range 5 My right This is my left range 5 My right range is 8 and 7 There are some 7's range is 8 and 7 There are some 7's in between that So this note gets created in between that So this note gets created Here from the free note this gets created 7 Here from the free note this gets created 7 And then what does Seven do? Seven is its And then what does Seven do? Seven is its own. his left range which is five and right his left range which is five and right rank which is his own value and passes that do I belong in this range, and when how does this buffalo return? and when how does this buffalo return? and when how does this buffalo return? goes again, seven moves its right kal, by moving right kal, it puts its own value to the left range and the right range puts its right range, which is what happens from this, from this also we see And the right does And the right does And the right does not come in the middle of the range so we do it again I not come in the middle of the range so we do it again I return from this OK what happens now after that we have done the whole left and right tomorrow for the seven so we add the seven Five goes to the right, okay, and when seven goes, then 5 notices that my left and right have also gone yesterday, okay, what happens now, my right okay, what happens now, my right goes tomorrow, jitter that. goes tomorrow, jitter that. goes tomorrow, jitter that. passes the left range which is 8 and passes its own right range which is and our no relief here is 10 because our idea is four on time also so now we have I do the fruits in the range I do the fruits in the range I do the fruits in the range 8 and 10 and so yes I do, 8 and 10 and so yes I do, hence the time is my own note, it is late here and my hence the time is my own note, it is late here and my own moves, own moves, then in the left tomorrow, he puts his own left range, then in the left tomorrow, he puts his own left range, left range and right range, he puts his left range and right range, he puts his own value and own value and own value and do I belong in this range? do I belong in this range? No, I don't belong in this range, No, I don't belong in this range, so I reduce one, I do so I reduce one, I do return and it and here to the left. and here to the left. and here to the left. then after that what does the time do? It moves right tomorrow. By moving right tomorrow, it itself puts its value in the left hand and puts 1001 in the right range and does it again tomorrow on Hey, I Hey, I Hey, I do it in this range, so if I do it in this range, so if I bring it in this range, then what will I bring it in this range, then what will I do, I will make a new note named Create 12 do, I will make a new note named Create 12 and then I have gone to my left, I will run it by doing and then I have gone to my left, I will run it by doing Idea Plus, oh mine, it is already finished. This six index does not exist, so how does this one work both the writes are done from yesterday also and we both the writes are done from yesterday also and we return it, then what do we do after this, return it, then what do we do after this, so the so it goes through the route and it goes through the route and strike and it becomes N like this and then what it does with its eight and again 8 returns its own route in I. If you are If you are If you are free, then you have come to know what we are doing. Basically, every time we will have left range and right range so this is so this is 7. Hey, we have to make it, it is okay Ours is okay here, so this is ours. is okay here, so this is ours. 7, first create our note let's go and then and then it goes, what it does is put the range, left it goes, what it does is put the range, left trench which is minus one and right range, trench which is minus one and right range, adds its own value and after creating the index plus note adds its own value and after creating the index plus note and and and four ko then four moves its own left kal in which it passes the left range same and the right range passes its value our kal no is already made. our kal no is already made. our kal no is already made. in four and similarly now 3 also does the same. Left creates a note before moving tomorrow because with this every time four also likes in one and seven and three is also in this range and like in 7 and then its then its then its moves to its left hand, so that here from left hand and right range, three becomes tomorrow, the index and the result is G, first of all, let's see whether I 3 and 3 and 3 and -1 and in this case I don't bring it, so it's -1 and in this case I don't bring it, so it's okay just return it directly. and puts the value of our writer here again and puts the value of our writer here again 5 I think tomorrow brother I have to 5 I think tomorrow brother I have to say again that I don't like in this range say again that I don't like in this range so I so I will return again otherwise so then this is 3, gone tax, this is 3, gone tax, and it goes to its so it notes itself five here, creates and goes to its left, tomorrow, doing IDEX plus, so this is We are on top of nine, okay, so right We are on top of nine, okay, so right We are on top of nine, okay, so right now for 9:00 tomorrow, there is a caste that I do not line in this range, after that five, I move to the right, after that five, I move to the right, in which it gives the range to the left range in which it gives the range to the left range itself. itself. itself. range Right range of five So again it seems to be tomorrow for nine But 9 has to say again that I do not belong in this range So I return again and Dangal is It also happens that it has already been returned, so I return my note to the right of 4, so it goes here and there is mine also both have gone yesterday, so I mine also both have gone yesterday, so I return myself to the right of my parents return myself to the right of my parents note. note. note. what happens now, 7, its right moves tomorrow, due to which it passes the what happens now, 7, its right moves tomorrow, due to which it passes the left train S7 and the Hey, I do it in this range, I take it, Hey, I do it in this range, I take it, so what will I do, I will so what will I do, I will create. create. create. tree note create and nine passes its left yesterday left yesterday nine passes its left range 7 and right range 9 passes its own value and when this nine is divided It remains It remains It remains index plus plus from here and we add it index plus plus from here and we add it here, to get the note, we have to say add. here, to get the note, we have to say add. Yes, I also belong to this range, Yes, I also belong to this range, so I myself also add a note, so I myself also add a note, 7 left range and 7 left range and 7 left range and our when it's flooded the index is six and which one is this 10 that I don't do it in this range and does it in the left range and right Passes in the range on nine but still has to say 10 that still I am not in this range so I will return again so now it from here and from here and after that ed has to be said after that ed has to be said so I so I so I after which I have to say nine. My right has after which I have to say nine. My right has not been moved yet, so I will not been moved yet, so I will move to the right tomorrow, I will pass the range, my own move to the right tomorrow, I will pass the range, my own left range, and I will pass mine in the left range. left range, and I will pass mine in the left range. left range, and I will pass mine in the left range. own value which is 9 and in the right range which is my right range which is 10001 and tomorrow we put 10 to say 10, I belong in this range so I will create a new note that is Note like this create Note like this create Note like this create then 10 your left kal moves what then 10 your left kal moves what happens and it makes plus plus when body happens and it makes plus plus when body itself is created then it index itself is created then it index plus but what happens now when left kal plus but what happens now when left kal moves then index is put seven moves then index is put seven so we so we so we condition of the index, hence we return it because no one with 7 indexes does this. Note exists, hence here we tap the return while moving to the left and we tap the return while moving to the right tomorrow also, both of them yesterday. both of them yesterday. both of them yesterday. returns to itself, goes to the right of the nine, right and left move, right and left move, so it returns itself and and and both left and right from intake yesterday, hence we call return mother function, so this is complete, let's check our code, have we done it right, then It is 7 3 4 7 4 3 4 5 4 9 then 8 then it is It is 7 3 4 7 4 3 4 5 4 9 then 8 then it is It is 7 3 4 7 4 3 4 5 4 9 then 8 then it is exactly like this and we have executed the code correctly so this was our virus got detected there was a little mistake in the driver But we But we But we too, as human beings, will have time complexity of how we are running, because we are creating each mode and there will so this is its time and space complexity. I so this is its time and space complexity. I hope guys, you have understood this very well, hope guys, you have understood this very well, mother? mother? mother? problem was that we were defining the color in it and passing it recursively in the range, so that we could know that the node that is my created, then whether the next note will come on my left or right, all this can be We were talking about ranges, that's We were talking about ranges, that's We were talking about ranges, that's why when we build binary, we why when we build binary, we mostly pass ranges only. If we have to mostly pass ranges only. If we have to create this then I hope guys, create this then I hope guys, you have understood this problem very well you have understood this problem very well and you will definitely solve this problem by yourself. and you will definitely solve this problem by yourself. and you will definitely solve this problem by yourself. also try to run this problem yourself and after solving it and submitting it, do tell in the comments whether I have solved it on my own or have submitted it and do like this video and that's all, we will see you in the Recording of mole length in and Recording of mole length in and Recording of mole length in and | 2024-03-25 14:22:45 | 1,008 | Leetcode 1008 |
|
i1jkKTbVXoI | uh hey hey everybody this is larry this is me going with q2 of the is me going with q2 of the lego contest 226. we stored it away from lego contest 226. we stored it away from adjacent pairs adjacent pairs so the key note for this problem is hit so the key note for this problem is hit the like button hit the subscribe button the like button hit the subscribe button join me on discord join me on discord let me know what you think about this let me know what you think about this form and so forth um but yeah form and so forth um but yeah for the key note for this problem is um for the key note for this problem is um there are a couple of things one is that there are a couple of things one is that making sure that it's unique otherwise making sure that it's unique otherwise if it's not unique if it's not unique then you have to figure out some sort of then you have to figure out some sort of or lydian path or loneliness psycho or lydian path or loneliness psycho depending on how they phrase the rest of depending on how they phrase the rest of it which is not hard per se but it it which is not hard per se but it depends on the constraints depends on the constraints so constraints are that you know n is 10 so constraints are that you know n is 10 to the fifth so you need a linear to the fifth so you need a linear algorithm algorithm but but again because this is unique um but but again because this is unique um if there's a solution and i guess they if there's a solution and i guess they didn't guarantee that there's a solution didn't guarantee that there's a solution i was actually looking for that i was actually looking for that um or just some numbers that has uh yeah um or just some numbers that has uh yeah so that means there's a path from the so that means there's a path from the beginning to the end so what does that beginning to the end so what does that mean right that means that every number mean right that means that every number will appear in this edge list if you will appear in this edge list if you call it that um twice because it has an call it that um twice because it has an in in degree and an out degree if you in in degree and an out degree if you want to call it that want to call it that so then there's only two possible so then there's only two possible answers really um answers really um where you know you have which is just where you know you have which is just you know going from backwards you know going from backwards or from the beginning to the end or the or from the beginning to the end or the end to the beginning end to the beginning um so the two answers are just kind of um so the two answers are just kind of like this or the reverse of this like this or the reverse of this but basically what the idea is um well but basically what the idea is um well for me what i did is that i put for me what i did is that i put everything in an edge list everything in an edge list um i i think i do something funky but um i i think i do something funky but but yeah i put everything in an etch but yeah i put everything in an etch list so that this is much easier to kind list so that this is much easier to kind of go through of go through um and then i just you know one of these um and then i just you know one of these so unless it's a cycle which there are so unless it's a cycle which there are no cycles there's at least there's one no cycles there's at least there's one place where place where um well actually decide the two places um well actually decide the two places where where a node which is a number has only one a node which is a number has only one edge which is the beginning edge which is the beginning and the end or you know whichever one and the end or you know whichever one you use can be the beginning or the end you use can be the beginning or the end so i just take the first one and so i just take the first one and i click i label this start and then i click i label this start and then that's that's pretty much the idea is that okay pretty much the idea is that okay greedily okay i started with greedily okay i started with to start um and then i removed to start um and then i removed you know i just removed the previous you know i just removed the previous edge so that we know that the second edge so that we know that the second edge edge is going to be the next edge and then i is going to be the next edge and then i add it to the list and i just add it to the list and i just kind of go in a greedy kind of way kind of go in a greedy kind of way because once you choose the first because once you choose the first node the rest of the nodes are forced um node the rest of the nodes are forced um and what i mean by that is that and what i mean by that is that you have no choice this this will always you have no choice this this will always contain only contain only one node always um if you do it one node always um if you do it correctly by removing the previous node correctly by removing the previous node uh from the edge list so once you do uh from the edge list so once you do that that uh there's only two possible answers uh there's only two possible answers depending which which um depending which which um which node you pick to start so yeah so which node you pick to start so yeah so what is the complexity of this well it's what is the complexity of this well it's going to be linear time going to be linear time uh because you know um uh because you know um redefining the the edge list is going to redefining the the edge list is going to be linear be linear uh in terms of the um yeah it's linear uh in terms of the um yeah it's linear this is a linear uh um loop this is a linear uh um loop and this is a linear loop so everything and this is a linear loop so everything is going to be linear is going to be linear and all these takes over one so uh so yeah um so overall this is linear time all together in terms of space because we we kind of put the list in a better easier place to look up um this is going to be um of n space as well so and in this case there is a distinction between edge edges when we say linear there's edges and vertexes but because this is um a linked list or if you want to call it that um there's um the number of edges is going to be n minus 1 or or the number of nodes minus one so in here o if n is you know so there's gonna be o n nodes and edges so when we talk about linear time and linear space even though technically if you want to be specific they're referring to two different things uh it's fine it's linear time linear space uh that's all i have for this problem [Music] you can watch me solve it during the you c uh yeah thanks everybody for watching uh uh yeah thanks everybody for watching uh let me know what you think about this let me know what you think about this problem i didn't do that well on this problem i didn't do that well on this contest just based on contest just based on some things that if you watch the some things that if you watch the contest video hopefully you'll see but contest video hopefully you'll see but yeah yeah um hit the like button again hit the um hit the like button again hit the subscribe button again join me on subscribe button again join me on discord again discord again um and hope y'all have a good day take um and hope y'all have a good day take care of yourself if you have care of yourself if you have the fortune you know take care of others the fortune you know take care of others um to good health um to good health stay good stay well you know and stay good stay well you know and pass it forward and you know treat pass it forward and you know treat people around you well um people around you well um and to good mental health and i will see and to good mental health and i will see you next problem bye-bye | 2024-03-20 18:07:05 | 1,743 | 1743. Restore the Array From Adjacent Pairs (Leetcode Medium) |
|
yDN2e96YMFA | hey guys welcome back to my channel and i'm back again with another really i'm back again with another really interesting coding interview question interesting coding interview question video video this time guys we are going to solve this time guys we are going to solve question number 1646 question number 1646 get maximum in generated array which is get maximum in generated array which is a dynamic programming question a dynamic programming question before i started the video guys just before i started the video guys just want to request you that if you have not want to request you that if you have not yet subscribed to my channel then please yet subscribed to my channel then please do subscribe and hit the bell icon for do subscribe and hit the bell icon for future notifications a more such future notifications a more such programming and coding related videos programming and coding related videos let's get started with the problem let's get started with the problem statement now so basically guys we are statement now so basically guys we are given an integer n and we are going to given an integer n and we are going to generate an array with this integer n generate an array with this integer n it is a zero indexed array that means if it is a zero indexed array that means if we are given an integer n the r is going we are given an integer n the r is going to have a size of n plus 1 to have a size of n plus 1 and the way we are going to generate and the way we are going to generate this array is that this array is that the 0th element that means num 0 is the 0th element that means num 0 is going to be 0 the first element the going to be 0 the first element the index 1 element is going to be 1 index 1 element is going to be 1 but after that if the index is even that but after that if the index is even that means 2 into i so that means if the means 2 into i so that means if the index is even index is even then uh then uh the nums 2 into i will becomes equals to the nums 2 into i will becomes equals to nums i so basically if it's even you nums i so basically if it's even you just have to uh half that value the half just have to uh half that value the half the index and that will become become the index and that will become become the value of that even index the value of that even index and if it is an odd index so if it's 2 and if it is an odd index so if it's 2 into i plus 1 then in that case it will into i plus 1 then in that case it will become equals to nums i plus nums of i become equals to nums i plus nums of i plus 1 that means plus 1 that means if it's an odd uh if it's an odd uh odd index then you just have to find out odd index then you just have to find out the the value of the nums array at its middle value of the nums array at its middle element and its midi plus one element element and its midi plus one element and just add them up and that will and just add them up and that will become the value of the odd index of become the value of the odd index of that particular array okay that particular array okay uh and after that once we have created uh and after that once we have created this array we have to return the maximum this array we have to return the maximum integer in the array numbers uh so here integer in the array numbers uh so here you can see in the example guys when n you can see in the example guys when n is equals to 7 is equals to 7 obviously num 0 and 1 are 0 1 obviously num 0 and 1 are 0 1 but for n equals 2 of for i equals to 2 but for n equals 2 of for i equals to 2 the value becomes equals to nums 1 so the value becomes equals to nums 1 so obviously if it's an even index obviously if it's an even index then you just have to half the index and then you just have to half the index and that value will become that value will become that value of that half index that value of that half index array will become the result so in this array will become the result so in this case for 2 if you have 2 you will get 1 case for 2 if you have 2 you will get 1 so that's when nums 1 is actually equal so that's when nums 1 is actually equal to nums 2 which is 1 to nums 2 which is 1 and if it's odds for example if it's and if it's odds for example if it's nums nums 3 the index is three so in that case we 3 the index is three so in that case we have to find out the middle element and have to find out the middle element and the mid plus one element so for index the mid plus one element so for index three the middle element will be the three the middle element will be the index one element and the mid plus one index one element and the mid plus one element will be the index two element so element will be the index two element so we have just summing those two and then we have just summing those two and then we get one plus one becomes equal to two we get one plus one becomes equal to two and so on and so forth uh you will keep and so on and so forth uh you will keep on doing this thing and finally on doing this thing and finally we have to find out the maximum value so we have to find out the maximum value so obviously the error is this this uh this obviously the error is this this uh this array and the maximum value is three so array and the maximum value is three so that's what we have written that's what we have written um all the other examples are also um all the other examples are also similar guys this constraints are very similar guys this constraints are very straightforward uh the value of n ranges straightforward uh the value of n ranges from 0 to 100 that's the only constraint from 0 to 100 that's the only constraint now let's jump to the solution part guys now let's jump to the solution part guys so the first thing which we have to do so the first thing which we have to do in this solution is to check if n is in this solution is to check if n is equal to 0 or if n equals to 1 because equal to 0 or if n equals to 1 because if it's 0 or 1 then it is pretty if it's 0 or 1 then it is pretty straightforward straightforward then in last case the maximum value we then in last case the maximum value we already know right so if it's 0 already know right so if it's 0 then we just have to return 0 but if then we just have to return 0 but if it's 1 we just have to return 1 because it's 1 we just have to return 1 because that becomes our maximum value that becomes our maximum value maximum value if that's not the case maximum value if that's not the case then we will just declare max variable then we will just declare max variable and i am going to by default it to 1 and i am going to by default it to 1 right because if n is equal equals to if right because if n is equal equals to if n is greater than 1 then the minimum n is greater than 1 then the minimum value which value which we can have we can have is one so that's where default the max is one so that's where default the max value to the uh one value and then i'm value to the uh one value and then i'm going to create the nums array going to create the nums array so this nums array is going to be so this nums array is going to be declared as a n plus one declared as a n plus one um um size array because uh we have a zero size array because uh we have a zero index static right index static right now in this num sorry guys num zero will now in this num sorry guys num zero will becomes equals to zero and then nums one becomes equals to zero and then nums one will sorry will sorry nums 1 will becomes equal to 1 nums 1 will becomes equal to 1 because that's given to us in the in the because that's given to us in the in the description as well description as well now we are going to start our for loop now we are going to start our for loop and this for loop is going to get and this for loop is going to get started from 2 started from 2 to i less than equals to n to i less than equals to n i plus plus okay i plus plus okay now as i stated to you guys if i now as i stated to you guys if i mod 2 is equal to 0 sorry mod 2 is equal to 0 sorry if i mod 2 is equals to 0 that means if i mod 2 is equals to 0 that means it's an even element so if it's an even it's an even element so if it's an even element element or if it's an even index then nums i or if it's an even index then nums i will become equals to you half the index will become equals to you half the index and you find out the value of that half and you find out the value of that half index index so nums i divided by 2 and that will so nums i divided by 2 and that will actually becomes equals to your num's actually becomes equals to your num's value okay in the second case when we have got our odd value right so if we have got an odd value then we have to find out the middle element and the middle plus one at the element so middle element is i plus two right and what is the mid plus one element that is i divided by two plus one so that will becomes equals to mid uh plus one at element you just sum both these values and that will become equal to your num side and finally guys once this if else is over we are going to check the maximum value so the maximum value is going to be either the existing maximum value or the num sayeth value whichever is greater and finally when this for loop is over we just have to return max so let's run this code guys let's see if this works for our example cases and i'm just going to submit it as it has worked for one of examples yes and there you go guys you can see that it is submitted successfully talking about the time complexity now so the time complexity for this solution is going to be order of n guys because we are going to have a forum which is running from 2 to n so approximately n times and that's why the time complexity is order of n space complexity space complexity is also order of n guys because we are creating an array of n plus one element okay so that's why in big notation you can say that space complexity is also order of n because we are storing an elements in a error okay so that was the video guys and that was the solution i hope you guys like the solution and i hope it was clear to you if you did like it guys and please do not forget to like this video and share this video with your friends if you have any questions comments suggestions feedback if you have any better solutions please post them in the comment section below i would be happy to address your comments and guys india please do not forget to subscribe to my channel and hit the bell icon for future notifications of more such programming uh videos thank you so much for watching i'll see you guys in the next video | 2024-03-19 18:05:46 | 1,646 | Get Maximum in Generated Array | Leetcode 1646 | Amazon Google Facebook interview question |
|
9_H-4HoqnAk | [Music] Hello everyone welcome, Hello everyone welcome, today's problem is today's problem is alternating bits, so in the problem statement alternating bits, so in the problem statement we are given a positive expectation and we have to we are given a positive expectation and we have to tell whether tell whether alternating beats are present in it or not, like alternating beats are present in it or not, like mother, take the first example, N = 5. mother, take the first example, N = 5. mother, take the first example, N = 5. if we represent it in binary, it will be 101. So in this we can see that there is a gent on the alternating beat, like there is a zero after the van and then a van, so how will we solve it, so let us How can we do this? How can we do this? So mother, we have a number three, okay, so if we do it in binary, it becomes 101, so this is the alternating beat, after van, zero comes after that, after that van, after that, Let us Let us Let us see one thing that if we shift it to the right or if see one thing that if we shift it to the right or if we shift it from van we shift it from van then it will come zero van is fine and then it will come zero van is fine and after that if we push it hard then after that if we push it hard then you will see the result that it will come you will see the result that it will come 1111 meaning. 1111 meaning. 1111 meaning. that it has been changed in both of them, that it has been changed in both of them, like these equals were 10, earlier it was 1010, okay, like these equals were 10, earlier it was 1010, okay, now if we change it with right shift van, then the now if we change it with right shift van, then the beat which is 101A means it is gone. beat which is 101A means it is gone. beat which is 101A means it is gone. zero, now it has become one, then one has become one, then zero has become zero, so after emphasizing this, if there is opposite in both the numbers, then one will go to one, then one will go to one, okay, so now we have to check it, Also, the Also, the Also, the numbers with alternating beats will be present. numbers with alternating beats will be present. If we shift one of them to the right and If we shift one of them to the right and push them together, then all the Vansh will always be push them together, then all the Vansh will always be present in it. Apart from that, nothing present in it. Apart from that, nothing can be present. Zero will not be present, so can be present. Zero will not be present, so we have to check it manually. we have to check it manually. That if after our emphasis and That if after our emphasis and after applying this formula, if all those after applying this formula, if all those numbers of One See are present, all One See are present in it, then numbers of One See are present, all One See are present in it, then our number with alternating beat will our number with alternating beat will be there, then to check this, we be there, then to check this, we will look at the concept of Power of Tu. will look at the concept of Power of Tu. will look at the concept of Power of Tu. what should we see in Power of Tu, like anyone, like Power of Tu, it was in the boundary of $100, okay, so see the one before that, in which there was seven, only van was present, okay, see Zero and the one before that Zero and the one before that Zero and the one before that then there was 1%, so then there was 1%, so here what we have to check is that here what we have to check is that it is only van, we can do this by saying that if it is only van, we can do this by saying that if we we add van in 15 then it will be 15 in decimal. add van in 15 then it will be 15 in decimal. add van in 15 then it will be 15 in decimal. and after that if we take the end of 16 and 15, if zero is taken then we will be able to approve that only one is present in all the lineage, like here we take the end If given then it goes to If given then it goes to If given then it goes to zero, here also we end it, so we have seen it, so now let us see the time complexity of it, time so now let us port it and see, so now let us port it and see, after coding, understand it well. after coding, understand it well. after coding, understand it well. whether only Vansh is present in it whether only Vansh is present in it or not, then almost what will we or not, then almost what will we do? We push do? We push N after shifting right from the van, it N after shifting right from the van, it is fine and after that we just have to return it. is fine and after that we just have to return it. What was the next step, What was the next step, we should check whether you are power off or we should check whether you are power off or not, if it is okay then return it not, if it is okay then return it all once is ours and so if we see here which is ours this is all once and all once plus one if this is If zero comes then it means we have If zero comes then it means we have If zero comes then it means we have alternating beat and if zero does not come alternating beat and if zero does not come then there is no alternating beat. It will return false. then there is no alternating beat. It will return false. Now let us run it and Now let us run it and see. After running, all the tests have been passed Even after doing this, our code has been finally accepted, ok then thank you, see you in the next video [Music] | 2024-03-20 17:15:42 | 693 | Bit Manipulation ||Binary Number with Alternating Bits || Leetcode 693 || C++ || Java |
|
TblhNX9AQ3M | Wedding Welcome To My Channel Today 2070 Problems Constructive Manner Retreat Problems Constructive Manner Retreat From India And Posters Given In Adhir From India And Posters Given In Adhir Veervati History And Subscribe Button More Veervati History And Subscribe Button More Benefits Loot Benefits Loot That Similarly In Post Operative Ward That Similarly In Post Operative Ward Process Factory Process Factory 's Combustion Lights Of Tree 's Combustion Lights Of Tree That And Followed By Root Not Show In Poster That And Followed By Root Not Show In Poster Traversal Traversal Traversal receiver and after the poster of the year poster and ministry of railways etc that divide is in ordinary from into to subscribe will look like this subscribe this Video subscribe this Video subscribe this Video 207 207 Similarly su in the processes of trees will provide you Similarly su in the processes of trees will provide you first will divide factory first will divide factory se gas leakage the poster pair to initially started se gas leakage the poster pair to initially started one intake which is the largest value of largest value of To Three Idiots I Will Reach The Chapter Note To Three Idiots I Will Reach The Chapter Note Subscribe Must Subscribe The Look Into This 20000 Subscribe 20000 Subscribe A For Solving This Will Use This Start The A For Solving This Will Use This Start The Start And Index For The Immortals Start And Index For The Immortals Are And Even In The World Which Will Keep Are And Even In The World Which Will Keep Trek didn't want to process for the Trek didn't want to process for the post Amazon is the root of the water post Amazon is the root of the water subscribe and subscribe the entry loot subscribe and subscribe the entry loot new of a tree node a half bureau ninn postering posts the order turn off index this lineage foreign nominated to right poetry you you you and investment also a brief and dispassionate call receive judge in axis in root index is lineage what do you live say stop this rights act which come under root x plus one correct on the Will be the same The Will be the same The Will be the same The volunteers of left parties Will become start SMS Start editing and destroyed and will come in Noida Route The Index - 1972 Calculator index for the white part among simply Index - 1st in the same and following a sister pimples and poster of fate Tree so how will get this indicates Tree so how will get this indicates Tree so how will get this indicates a first for the first life itself so a first for the first life itself so isi VPN axis hair second and routine and width and that induces will get the number of notes in our that induces will get the number of notes in our life history Danveer Sector-21 from life history Danveer Sector-21 from the power index the power index we will get we will get we will get which here and after doing to subjective which will give the indexes assembly will solve error code for the same approach should be constructed from do subscribe my channel and will not mean that will win from the poster subscribe The Amazing The value of Do you will find a co Do you will find a co Do you will find a co stop this loop and recorded in order to take back after stop this loop and recorded in order to take back after doing all the rights of vs doing all the rights of vs subscribe to that subscribe to that filmi filmi ki accepted software at the same time ki accepted software at the same time complexity software running open complexity software running open request solve every time she these request solve every time she these findings in the case of subscribe and 30 findings in the case of subscribe and 30 Boys Poster 12345 12345 I will withdraw subscribe that Mahesh map and write the indices of between 200 hair for per in ICC Twenty20 200 hair for per in ICC Twenty20 violence in order dot length violence in order dot length that i plus plus that i plus plus that map.com that map.com is an inverter of is an inverter of is an inverter of Software Institute Of Checking For Daru Vijay Best All Check Dam Bay Index Problem Map Map Don't Get We Poster Turn Off Indus Valley Number Oven Thanks And This Algorithm Is Used In It Equal Will be the Will be the work and some descent user time festival videos to off wild space complexity I am safe so second advisors for it is a I am safe so second advisors for it is a defined the global time app you can defined the global time app you can create a local copy and pass uniform create a local copy and pass uniform reaction calls reaction calls reaction calls 100 thank you left me solution satellite button and subscribe my channel thanks for | 2024-03-21 10:24:12 | 106 | construct binary tree from inorder and postorder traversal leetcode | leetcode 106 | binary tree |
|
MjpAAE3-hYg | so hello everyone welcome to this new video and i will be explaining the video and i will be explaining the problem maximum value at a given index problem maximum value at a given index in bounded area in bounded area so this problem is exactly medium one so this problem is exactly medium one and you know this kind of problems uh and you know this kind of problems uh are become i have realized that they are are become i have realized that they are asked regularly these are binary search asked regularly these are binary search problems problems so in this video first i will be so in this video first i will be explaining this problem explaining this problem through an example and then i will code through an example and then i will code it so it so what the problem is basically saying is what the problem is basically saying is that i have been given an that i have been given an array okay and i have been given a array okay and i have been given a particular index particular index and i have been given a particular sum and i have been given a particular sum the sum of the array has to be in the the sum of the array has to be in the limit of limit of this maximum sum and i have to increase this maximum sum and i have to increase maximize that particular index maximize that particular index okay keeping these conditions in mind okay keeping these conditions in mind so these conditions are that the sum of so these conditions are that the sum of adjacent numbers adjacent numbers should be different should be less than should be different should be less than equal to one equal to one and basically the sum of the entire area and basically the sum of the entire area should be less than should be less than the maximum sum so let's understand this the maximum sum so let's understand this problem more clearly from this example problem more clearly from this example so in this example so in this example let's see this this is a let's see this let's see this this is a let's see this example so example so this in this example n is equal to 6 and this in this example n is equal to 6 and index is equal to 1 index is equal to 1 so and the maximum sum is 10 so what i so and the maximum sum is 10 so what i have to do is that i have been given an have to do is that i have been given an array of 6 array of 6 and i have to maximize the index that is and i have to maximize the index that is present at present at 10 uh sorry at 1 and the entire sum 10 uh sorry at 1 and the entire sum of the array should be less than what it of the array should be less than what it should be less than 10 should be less than 10 okay so let's see so what i will do okay so let's see so what i will do that i will just do it by fixing that i will just do it by fixing instead of thinking that what i have to instead of thinking that what i have to do on the left side and do on the left side and do what i have to do on the right side do what i have to do on the right side what i will do is that i will fix this what i will do is that i will fix this number number and then calculate that okay what can be and then calculate that okay what can be my possible left side and right side my possible left side and right side okay okay so for example if i say that okay let's so for example if i say that okay let's fix my number to 10 fix my number to 10 then to minimize the sum of this entire then to minimize the sum of this entire array what i will do and keeping in the array what i will do and keeping in the condition that the difference between condition that the difference between adjacent should be less than equal to adjacent should be less than equal to one one so what i will do is is that i will so what i will do is is that i will write this as 9876 write this as 9876 and in the left side i will go nine so and in the left side i will go nine so the entire sum here is going to be i the entire sum here is going to be i think think somewhere around 30 or 45 30 i guess somewhere around 30 or 45 30 i guess so in this is not satisfying this so in this is not satisfying this condition now what i will do is that condition now what i will do is that i will uh go for say nine in case of i will uh go for say nine in case of nine these things are happening nine these things are happening uh the sum is still going to be uh more uh the sum is still going to be uh more than ten okay than ten okay so now uh and so on uh i will commit so now uh and so on uh i will commit four four uh at four what i do is that okay to uh at four what i do is that okay to keep the conditions valid i will keep the conditions valid i will write this three this two this one and write this three this two this one and after that after that after one i can't go below one because after one i can't go below one because it is given that it is given that all the elements in the array should be all the elements in the array should be greater than 1 greater than 1 so in that case i will write 1 only so so in that case i will write 1 only so here the sum is going to be here the sum is going to be what it is still going to be less than what it is still going to be less than 10 uh greater than 10 it is i think 14 10 uh greater than 10 it is i think 14 but in this case this case 3 2 1 1 so it but in this case this case 3 2 1 1 so it is is what 5 8 7 so in this case the sum is 7 what 5 8 7 so in this case the sum is 7 so this is a valid case so this is a valid case this is a valid case and everything is this is a valid case and everything is being satisfied so being satisfied so my answer will be 3 because so that's my answer will be 3 because so that's the thing the thing so to do this there can be two ways so so to do this there can be two ways so either i can either i can go from 10 all the way down here so this go from 10 all the way down here so this will give me a time limit exceeded will give me a time limit exceeded or another thing is that i can use or another thing is that i can use binary search okay binary search okay so what i will do is that first my so what i will do is that first my maximum sum is 10 maximum sum is 10 and the minimum sum that i can reach and the minimum sum that i can reach here a minimum here a minimum target value i can reach here is one target value i can reach here is one okay so the first one okay so the first one let's say first i will take something as let's say first i will take something as five okay i will explore five five okay i will explore five and see okay the five sum is some and see okay the five sum is some let's say it is one thousand and i will let's say it is one thousand and i will realize realize okay it is one thousand now i have to go okay it is one thousand now i have to go down so then i will go to 2 down so then i will go to 2 at 2 i see that it is its sum is less at 2 i see that it is its sum is less than 10 than 10 so i will go up so you know in this way so i will go up so you know in this way i will arrive at my solution i will arrive at my solution more quickly so this is the idea so now more quickly so this is the idea so now let's let's code it i will it will become more clear code it i will it will become more clear as i code it as i code it so let's begin let's go so let's begin let's go full screen please subscribe to my full screen please subscribe to my channel a lot of my viewers are not channel a lot of my viewers are not subscribed so if you are a regular subscribed so if you are a regular person person here please consider subscribing okay here please consider subscribing okay so first of all for what i will do is so first of all for what i will do is that that i will make a few integers variables in i will make a few integers variables in r is equal to n minus index r is equal to n minus index minus 1 so what r is r is basically just minus 1 so what r is r is basically just let me let me clear this so r is basically the number clear this so r is basically the number of of empty spaces in the right side and i empty spaces in the right side and i will make another variable l that is will make another variable l that is going to be the number of empty going to be the number of empty spaces in the left so in this case it is spaces in the left so in this case it is 4 4 r is 4 so and then i will i'm using long r is 4 so and then i will i'm using long because because there is a integer overflow if i use int there is a integer overflow if i use int okay okay so l is equal to what index index means so l is equal to what index index means it means that uh basically one it means that uh basically one is on the left one only one empty space is on the left one only one empty space is on the left is on the left now i will make uh more variables long now i will make uh more variables long high high high is equal to what max sum maximum high is equal to what max sum maximum and and long low is equal to one so long low is equal to one so these are going to be my initial high these are going to be my initial high and low for the binary search and low for the binary search and i will make another variable called and i will make another variable called long res is equal to zero long res is equal to zero this is going to be my maximized value this is going to be my maximized value okay okay now what i will do is that i will write now what i will do is that i will write a binary search so while low is less a binary search so while low is less than equal to high than equal to high what i will do is that i will what i will do is that i will take long mid is equal to what take long mid is equal to what high minus low high minus low by 2 plus low so by 2 plus low so this is also done to avoid integer this is also done to avoid integer overflow but in overflow but in i have tested it you can also write high i have tested it you can also write high plus low by two plus low by two so and now i will make another variable so and now i will make another variable called long sum called long sum so sum is equal to initially mid so sum is equal to initially mid initially it will be mid initially it will be mid uh you know why because so suppose uh uh you know why because so suppose uh after after doing this i arrive at six so i will doing this i arrive at six so i will have my have my sum some will initially be six then i sum some will initially be six then i will calculate this thing and this thing will calculate this thing and this thing okay so initially the long sum is mid okay so initially the long sum is mid and long ls is equal to 0 i will explain and long ls is equal to 0 i will explain it what this means it what this means long rs is equal to 0 long rs is equal to 0 and long m is equal to and long m is equal to mid minus 1 so just so mid minus 1 so just so l s is basically the sum on l s is basically the sum on left left and left left and r s is sum on right r s is sum on right for that particular so for example in for that particular so for example in this case ls is this case ls is what five plus four nine nine plus three what five plus four nine nine plus three twelve twelve fourteen ls is fourteen and rs is five fourteen ls is fourteen and rs is five and m is m i will use it to and m is m i will use it to calculate this uh sum so m is basically calculate this uh sum so m is basically a five a five and will be five uh as it is clear and will be five uh as it is clear m is mid minus one so i will have to m is mid minus one so i will have to calculate the sum now from calculate the sum now from two to five so that is why uh not six so two to five so that is why uh not six so that is why i have just made it that is why i have just made it m it is just for convenience so m it is just for convenience so now there can be two possibilities now there can be two possibilities so the first possibility is as you can so the first possibility is as you can see uh you will see here see uh you will see here that in this case let's see this case so that in this case let's see this case so in this case this in this case this sum is going from 9 to 6 okay so it is sum is going from 9 to 6 okay so it is fine i can fine i can do there is a formula to calculate sum do there is a formula to calculate sum of n natural numbers i hope you will be of n natural numbers i hope you will be aware of it aware of it n is equal to n plus 1 by 2 so in this n is equal to n plus 1 by 2 so in this case what i can do is that i will case what i can do is that i will calculate the sum of 1 to 9 calculate the sum of 1 to 9 and then i will subtract the sum of 1 to and then i will subtract the sum of 1 to 5 5 to get this particular sum okay i hope to get this particular sum okay i hope it is clear to you it is clear to you uh so it is fine but in this case uh so it is fine but in this case say see this case in this case my 2 1 is say see this case in this case my 2 1 is going to get over here and i will have going to get over here and i will have to add extra ones to to add extra ones to fill this array so this will be a fill this array so this will be a different case this will arrive when different case this will arrive when uh what my m is the number of spaces uh what my m is the number of spaces here is here is uh more than m so m is 2 uh more than m so m is 2 but the number of spaces here are 4 so but the number of spaces here are 4 so in this case i will have to add extra in this case i will have to add extra ones ones so these are some things that i will so these are some things that i will write and i will explain it write and i will explain it so if r is less than equal to so if r is less than equal to m right side then what i will do is that m right side then what i will do is that rs will become what m into rs will become what m into m plus 1 by m plus 1 by 2 subtracted by what 2 subtracted by what m minus r into m minus r into m minus r plus m minus r plus 1 by 2. so 1 by 2. so i hope you are understanding this is i hope you are understanding this is just what just what uh to calculate this sum from uh uh to calculate this sum from uh 9 to 6 what i will do is that i will uh 9 to 6 what i will do is that i will uh just just from i will calculate the entire sum from i will calculate the entire sum from 1 to 9 and subtract the sum from 1 to 9 and subtract the sum from 1 to 5 natural numbers to get this from 1 to 5 natural numbers to get this particular particular range so this is what i am then done range so this is what i am then done else else else for else condition i am going uh else for else condition i am going uh looking for this kind of situation where looking for this kind of situation where i have to fill extra once to complete my i have to fill extra once to complete my array so in this case my rs will be array so in this case my rs will be what m this thing will be same what m this thing will be same control c control v control c control v and i will add some extra ones one and i will add some extra ones one into what how many extra ones i will add into what how many extra ones i will add that will basically be r minus m that will basically be r minus m so you know i strongly suggest you that so you know i strongly suggest you that please pause the video and let this please pause the video and let this thing thing sink in that what this max of match sink in that what this max of match formula means formula means okay then you can move forward so okay then you can move forward so in this way i have calculated the right in this way i have calculated the right side now i will calculate the left side side now i will calculate the left side so so in left side also they are going is in left side also they are going is going to be a similar condition if l is going to be a similar condition if l is less than equal to less than equal to equal to m actually this is all going to equal to m actually this is all going to be same control c control v be same control c control v so instead of l i am rs i am going to so instead of l i am rs i am going to write write l s and instead of m minus r i am going l s and instead of m minus r i am going to write to write m minus l and here also it will be l m minus l and here also it will be l so it is just a replacement so it is just a replacement uh just a second now what i will do is uh just a second now what i will do is that i will calculate my sum that i will calculate my sum so what sum i have arrived so far so the so what sum i have arrived so far so the sum sum will be what some sum plus equals to will be what some sum plus equals to ls plus rs okay now i have ls plus rs okay now i have arrived the sum at this particular say arrived the sum at this particular say at this particular what case i was at i at this particular what case i was at i at this particular case at this particular case what is the time it is 11 minutes okay what is the time it is 11 minutes okay so now what i will do is that so now what i will do is that if if the sum is less than equal to max if if the sum is less than equal to max sum max sum then i will sum max sum then i will simply res is my update my result is simply res is my update my result is equal to equal to mid and i will increase my low is equal mid and i will increase my low is equal to to mid plus 1 and if mid plus 1 and if else else if the sum is exceeding the else else if the sum is exceeding the maximum sum maximum sum that means that i will have to reduce my that means that i will have to reduce my high so my high will become high so my high will become mid minus 1 and that's the problem it is mid minus 1 and that's the problem it is done and in the end i will return res done and in the end i will return res so let's decrease the font so let's decrease the font 12 pixels so i think that is 12 pixels so i think that is done let's run this code to check if done let's run this code to check if there is there is any error it is running fine now let's submit it it is 100 faster in both time and space so it's a pretty good thing so you know if the problem is clear to you please consider subscribing my channel | 2024-03-22 16:02:03 | 1,802 | LeetCode 1802. Maximum Value at a Given Index in a Bounded Array | Weekly Contest 233 🏆 | Explained |
|
ApihGYk4E4k | hello everyone welcome to day 13 the focus liquid challenge and today's focus liquid challenge and today's question is set matrix zeros question is set matrix zeros in this question we are given a matrix in this question we are given a matrix of size m cross n where each element is of size m cross n where each element is kind of an integer and we need to set kind of an integer and we need to set the complete row the complete row and column and column if this if this current element happens to be 0 current element happens to be 0 let's talk about it by an example in let's talk about it by an example in this matrix this element is 0 as soon as this matrix this element is 0 as soon as we find the 0 we need to we find the 0 we need to mark all the elements in that entire row mark all the elements in that entire row and column as 0 and this is what we need and column as 0 and this is what we need to do let's talk about this example as to do let's talk about this example as well well these two are 0s in this matrix that these two are 0s in this matrix that means this complete column this complete means this complete column this complete row and this complete column should be row and this complete column should be marked as zero we need to update the marked as zero we need to update the matrix and return it in the answer matrix and return it in the answer the question says you must do it the question says you must do it in place in place so we will go step by step we will use so we will go step by step we will use some space and then we will try to some space and then we will try to optimize it uh so that we don't have to optimize it uh so that we don't have to use any extra space for it so without use any extra space for it so without much to do let's look at the solution much to do let's look at the solution set matrix 0 lead code 73 set matrix 0 lead code 73 so let's talk about the same example so let's talk about the same example that was specified in the question that was specified in the question the matrix that we have is something the matrix that we have is something like this 0 1 2 0 3 4 5 2 1 3 1 5 like this 0 1 2 0 3 4 5 2 1 3 1 5 and what we can do in the first approach and what we can do in the first approach the naive approach the naive approach uh we can store the indexes of all those uh we can store the indexes of all those rows rows slash columns which needs to be turned slash columns which needs to be turned off or set to zero so you start the off or set to zero so you start the iteration and let me just write the iteration and let me just write the column index and the row index column index and the row index zero one two zero one two and you start you then you start the and you start you then you start the iteration the first element that you see iteration the first element that you see is zero that means you need to is zero that means you need to mark the row starting with the zeroth mark the row starting with the zeroth index the zeroth row to zero and index the zeroth row to zero and zeroth column to zero zeroth column to zero and you continue the process next we and you continue the process next we have one next we have two next again we have one next we have two next again we have a zero that means you need to mark have a zero that means you need to mark the complete column the third column as the complete column the third column as zero so you add it to the column list zero so you add it to the column list and obviously you add again the zero and obviously you add again the zero back so let's add the zero back you can back so let's add the zero back you can create a set for it you can create a create a set for it you can create a list for it set would be optimal then a list for it set would be optimal then a list list then you go under the iteration you have then you go under the iteration you have three four five two one three one five three four five two one three one five let's hypothetically assume instead of let's hypothetically assume instead of this one we had zero then we would have this one we had zero then we would have added the second row and the second added the second row and the second column to our list so 2 gets added to column to our list so 2 gets added to get started get started now what you are going to do you will now what you are going to do you will iterate over these row indexes pull out iterate over these row indexes pull out elements one by one and mark the elements one by one and mark the complete row to zero complete row to zero so uh the first row that get two index so uh the first row that get two index that could pull out is zero so you mark that could pull out is zero so you mark the complete row as zero the complete row as zero then again then again we can create a set for it instead of a we can create a set for it instead of a list so it won't be repeated then we list so it won't be repeated then we have two so this complete row will be have two so this complete row will be marked as zero zero zero is zero zero marked as zero zero zero is zero zero similarly for the column part the zeroth similarly for the column part the zeroth column is three mark zero so this is column is three mark zero so this is gone the third column is to be mark zero gone the third column is to be mark zero this is gone the second column has to be this is gone the second column has to be marked as zero this is gone what is left marked as zero this is gone what is left is only four which is the answer is only four which is the answer assuming we had a zero here not a one assuming we had a zero here not a one i hope you got the context i hope you i hope you got the context i hope you got how it is to be done got how it is to be done and let's talk about the optimized and let's talk about the optimized solution now solution now let's hypothetically assume that this is let's hypothetically assume that this is a matrix that is given to us 1 2 3 4 32 a matrix that is given to us 1 2 3 4 32 1 0 5 7 0 10 14 0 1 8 1 0 5 7 0 10 14 0 1 8 also i forgot to mention the space also i forgot to mention the space complexity here would be equal to order complexity here would be equal to order of of row count plus column count row count plus column count row count row count because at max because at max these these sub arrays these arrays can have sub arrays these arrays can have n number of rows and this array can have n number of rows and this array can have a size of a size of m columns m columns row count plus column count and can we row count plus column count and can we optimize it further the answer is yes optimize it further the answer is yes let's go ahead with the optimization let's go ahead with the optimization instead of using extra space we will do instead of using extra space we will do it in place as soon as we find the 0 it in place as soon as we find the 0 what we are going to do what we are going to do we will mark we will mark the the starting of the row as 0 as well as the starting of the row as 0 as well as the starting of that column as zero starting of that column as zero so so let's assume this is the first zero that let's assume this is the first zero that you encountered by light returning to you encountered by light returning to the matrix and you simply update the the matrix and you simply update the first first element at the at this particular row to element at the at this particular row to zero similarly the first element in this zero similarly the first element in this particular column 2 0. particular column 2 0. now let's continue the process the next now let's continue the process the next leader that we see is in the third row leader that we see is in the third row so you update this to 0 as well as this so you update this to 0 as well as this element to 0 element to 0 next we have is this 0 you update this 0 next we have is this 0 you update this 0 to 0 this element to 0 and this element to 0 this element to 0 and this element to 0 you are basically updating to 0 you are basically updating the first element in that particular row the first element in that particular row to 0 as well as first element in that to 0 as well as first element in that particular column to zero particular column to zero and now the matrix is something like and now the matrix is something like this one zero zero zero this one zero zero zero zero zero zero zero zero zero what you're going to do the first thing that i have done here is to uh define two areas that will store the indexes of those rows that are to be marked that are to be marked zero the indexes of those columns that are doing marked zero i start iterating through the complete matrix one by one and as soon as i find an element that is to be marked that is currently zero i update the row zero array uh to add the i gith row into it similarly i update the column 0 variable to add the jth column in it and then i start iterating uh through the these arrays row 0 and column 0 and for each row index that is retrieved from the row 0 i mark it as 0 make row 0 i have to find another method that accepts two variables the matrix and the row that is to row index that is mark 0 similarly for the column part and once i'm done with this i simply return back the question reduces to defining and writing this these helper methods appropriately so i have the matrix and the row index i start iterating in a column wise fashion j equals to zero j is less than matrix at the zero index dot length the number of columns that i have j plus plus i mark the r index row to zero similarly i have defined a private method make column zero i go uh start i go from i equals to zero i is less than the number of rows that i have and i update matrix of i comma the c index the column index that is we mark zero as zero and simply return back accepted the time complexity of this accepted the time complexity of this approach approach is is order of m into n the space complexity of this solution is again order of m plus n where m n stands m and n stands for number of rows and columns that we have where we are not using any extra space it's a slightly lengthier method but it's very simple so uh i have extract i've checked whether the matrix is not null extract those them and two variables the number of rows and number of columns that i have i'll talk about this later on uh but let's look at the com the actual logic first as soon as i uh find a 0 in the matrix i update the starting element of that row and starting element of that column to zero and i reiterate uh through uh the complete first row and first column and check if my element happens to be the first element happens to be zero i nullify the column as similarly if my first uh element happens to be zero i nullify the complete row this is what i explained in the presentation as well this slide kva to it you need to also check if my first row and first column has already has a zero in it or not if that is the case then we explicitly need to handle it in the end we need to mark the first row as well as the first column as zero explicitly so i've defined two variables here first row has zero first column are zero i start out rating through the matrix only in the first row and if if there is a zero in it i update this variable similarly for the first column has zero and once i have those values i simply nullify the zero way through and the zeroth column to zero using nullify row and nullify column i hope you got the context uh we are doing it in place the time complexity is order of m into n and the space complexity is constant space i hope you enjoyed today's session if you did please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more update from coding decoded see you tomorrow with another fresh question on lead code | 2024-03-20 11:34:20 | 73 | Set Matrix Zeroes | Leetcode 73 | Live coding session | Step by Step 2 approach | 🔥🔥🔥 |
|
xtx342vII5E | welcome to january's lego challenge today's problem is merge two sorted today's problem is merge two sorted lists lists merge two sorted linked lists and return merge two sorted linked lists and return it as a sorted list it as a sorted list the list should be made by splicing the list should be made by splicing together the nodes of the first two together the nodes of the first two lists lists we're given two linked lists here and we're given two linked lists here and they're going to be sorted and we want they're going to be sorted and we want to merge them together to return a to merge them together to return a single sorted linked list now the way single sorted linked list now the way that we solve this is by that we solve this is by having two pointers and basically having two pointers and basically creating a new creating a new linked list by traveling down both of linked list by traveling down both of these two these two lists and whenever we find that one is lists and whenever we find that one is less than the other one less than the other one we add that to the output array and then we add that to the output array and then move move the pointer ahead and then continue that the pointer ahead and then continue that loop loop to compare which one is less than the to compare which one is less than the other once we reach the end of one we other once we reach the end of one we just add the remainder of the just add the remainder of the other list into that output array and other list into that output array and that's it that's it so to do this what i'm going to do is so to do this what i'm going to do is create a dummy node and create a dummy node and the output and we're just going to make the output and we're just going to make this a list node that's empty this a list node that's empty and the reason we need two is this dummy and the reason we need two is this dummy node is going to point to the head node is going to point to the head while the output is going to be like the while the output is going to be like the current node that we're pointed on current node that we're pointed on so while there's both the l1 and l2 so while there's both the l1 and l2 we want to check to see which one is we want to check to see which one is greater right so or which one is greater right so or which one is less rather so if l1 dot value less rather so if l1 dot value is less than l2 that value then we want is less than l2 that value then we want to add this l1 to add this l1 uh to our output so what we'll do is say uh to our output so what we'll do is say okay output.next is equal to okay output.next is equal to l1 and then we move ahead our l1 and then we move ahead our l1 to the next one l1.next l1 to the next one l1.next now otherwise we're going to add l2 to now otherwise we're going to add l2 to the next so open the next so open next equals l2 and then we move ahead next equals l2 and then we move ahead our l2 to the next our l2 to the next and make sure we move ahead our current and make sure we move ahead our current pointer pointer output is now equal to output.next now output is now equal to output.next now once we're out of this loop we just need once we're out of this loop we just need to add the remainder of what remains to add the remainder of what remains to our output so if l1 remains then to our output so if l1 remains then we'll add that we'll add that to output.next up index equals l1 to output.next up index equals l1 otherwise if l2 then output.next equals otherwise if l2 then output.next equals l2 finally we just return the l2 finally we just return the dummy.next which is the head so let's go dummy.next which is the head so let's go ahead and submit that ahead and submit that um see if this works um see if this works looks like it did all right and accepted so this uh is going to be a o of n time complexity and i believe it's the optimal one uh there are other ways you could do it but you know this is kind of the generally accepted way so all right thanks for watching my channel and remember do not trust me | 2024-03-19 17:15:00 | 21 | Leetcode - Merge Two Sorted Lists (Python) |
|
vZuXVliUfeY | Hello friends welcome to my channel let's have a look at another unique let's have a look at another unique binary search trees problem problem 96 binary search trees problem problem 96 in this video we are going to continue in this video we are going to continue the video on problem 95. the video on problem 95. in problem 95 we explained how to build in problem 95 we explained how to build all the unique Banner searches by all the unique Banner searches by recursion so this problem here concerns recursion so this problem here concerns the number of unique banners to trees in the number of unique banners to trees in other words content other words content so first I'll read through the statement so first I'll read through the statement to recall the requirement and then we to recall the requirement and then we analyze the problem and finally we share analyze the problem and finally we share the code the code uh here given that integer M we are uh here given that integer M we are required to return the number of required to return the number of structurally unique bsts which has structurally unique bsts which has exactly nodes of unique values from 1 to exactly nodes of unique values from 1 to m m so here are two examples with the so here are two examples with the corresponding ends and corresponding corresponding ends and corresponding outputs outputs so before we do the analysis let's look so before we do the analysis let's look at the constants so here n is bonded at the constants so here n is bonded below by 1 and upon it above by 19 right below by 1 and upon it above by 19 right so this number in itself is not a large so this number in itself is not a large number so with that said we have a number so with that said we have a feeling about the problem size so now feeling about the problem size so now let's look at the analysis so in this let's look at the analysis so in this problem so if we understand the problem so if we understand the construction of unique Banner searches construction of unique Banner searches actually it's straightforward to do the actually it's straightforward to do the counting I would see actually this two counting I would see actually this two problems are sort of the same just one problems are sort of the same just one cons on the specific trees and the other cons on the specific trees and the other here counts the numbers so here are here counts the numbers so here are several points first if we have no nodes several points first if we have no nodes or just one node so the number is one or just one node so the number is one right there's only one Banner search right there's only one Banner search tree secondly if we have n nodes with tree secondly if we have n nodes with distinct values let's take one two up to distinct values let's take one two up to n for example n for example then we could choose any one of the then we could choose any one of the nodes as root and then let's assume that nodes as root and then let's assume that we choose a number I it could be the we choose a number I it could be the node value as a root so then we need to node value as a root so then we need to use 1 2 up to I minus 1 to build the use 1 2 up to I minus 1 to build the left subtree and we use I plus 1 to n to left subtree and we use I plus 1 to n to build the red sub tree so due to the build the red sub tree so due to the binary search property so when we build binary search property so when we build the search phase so this procedure the search phase so this procedure recursively continue so that's the main recursively continue so that's the main idea now let's look at the numbers idea now let's look at the numbers assume that we have a function f which assume that we have a function f which if we give a number of nodes we're going if we give a number of nodes we're going to compute the number of unique balancer to compute the number of unique balancer trees so here are the actually the trees so here are the actually the recursion relation so FN is nothing but recursion relation so FN is nothing but the summation of the different the summation of the different summation of the product of different summation of the product of different level trees and different respiratory level trees and different respiratory lastly choose we have chosen a node with lastly choose we have chosen a node with value I value I so here so here um there are I minus 1 numbers less than um there are I minus 1 numbers less than I so we have I minus 1 nodes for level I so we have I minus 1 nodes for level super 3 that is F A minus one so this is super 3 that is F A minus one so this is the number of different left slip binary the number of different left slip binary search trees so similarly if we look at search trees so similarly if we look at the red sub tree so there are n minus I the red sub tree so there are n minus I knows so all n i minus I values greater knows so all n i minus I values greater than I so this F in minus I is the than I so this F in minus I is the number of different red sub Banner number of different red sub Banner searches so here I runs from 1 to n so searches so here I runs from 1 to n so this actually is the recursion relation this actually is the recursion relation or a DP updated rule if we want to use or a DP updated rule if we want to use dynamic programming the next line dynamic programming the next line actually is a change of variable so if actually is a change of variable so if we change the summation with respect to we change the summation with respect to I to be with respect to G so we'll let g I to be with respect to G so we'll let g equals I minus 1. so then this summation equals I minus 1. so then this summation is nothing but FG times F and minus 1 is nothing but FG times F and minus 1 minus G so previously I runs from 1 to M minus G so previously I runs from 1 to M now G runs from 0 to n minus 1. so this now G runs from 0 to n minus 1. so this second equality it means to make or second equality it means to make or establish a connection with the constant establish a connection with the constant number CM so if we look at the second number CM so if we look at the second equality this number is nothing but the equality this number is nothing but the constant number cm so therefore to get constant number cm so therefore to get the number of unique balancer cheese the number of unique balancer cheese here we could do either of the two here we could do either of the two following statements first we use DP so following statements first we use DP so this is natural and actually routine if this is natural and actually routine if we do not know the cutting numbers we do not know the cutting numbers secondly so we can use the continent secondly so we can use the continent number recursion formula number recursion formula so the recursion relation for cutting a so the recursion relation for cutting a number let's use C from an N to number let's use C from an N to demonstrate the N some calcium number so demonstrate the N some calcium number so this rating is just for communist of this rating is just for communist of ready right so here and if we initialize ready right so here and if we initialize a start so at zero it's one and one out a start so at zero it's one and one out actually is also one then this is the actually is also one then this is the recursion relation recursion relation so with that side now we can look at the so with that side now we can look at the code actually for the code it's actually code actually for the code it's actually very standard a routine so here first very standard a routine so here first I'm going to write a DP solution I'm going to write a DP solution for the DP solution so I'm going to for the DP solution so I'm going to um because it means count so I'm going um because it means count so I'm going to use cons so 0 times to use cons so 0 times um M plus one so in other words count I um M plus one so in other words count I means that if we have I and distinct means that if we have I and distinct values how many distinct beneficially values how many distinct beneficially right so we're going to return count M right so we're going to return count M right so notice that in this right so notice that in this initialization we used a list of length initialization we used a list of length n n plus one right so in this case the last plus one right so in this case the last element has index in right so const zero element has index in right so const zero should be one right so if we have no should be one right so if we have no nodes so this is what so now we just nodes so this is what so now we just need to use the recursion RDP updated need to use the recursion RDP updated row here row here so now let's do this so now let's do this basically it's a basically it's a um DP update rule or relation um DP update rule or relation so this is a for Loop for I in range so this is a for Loop for I in range um well up to M plus one it means that um well up to M plus one it means that we choose value I as the root value and we choose value I as the root value and then we are going to add the scenes then we are going to add the scenes together for J here range together for J here range 0 to I so let's emphasize zero right so 0 to I so let's emphasize zero right so because left symmetry can be empty tree because left symmetry can be empty tree so here are counts I so here are counts I can incremented by this case right in can incremented by this case right in other words if we have G nodes in the other words if we have G nodes in the left subtree and then we have left subtree and then we have um count um count Pi minus G Pi minus G minus one knows in the rest of the tree minus one knows in the rest of the tree right so this actually this updates um is doing the update according to the so here you can understand that for this so here you can understand that for this all right fixed for fixed I we determine all right fixed for fixed I we determine how many different how many different um um unique balance of cheese if we have in unique balance of cheese if we have in total I know right so what we're going total I know right so what we're going to do to return actually is can't to do to return actually is can't pin rate pin rate so let's directly return this so with that said I guess that's about it for this specific version so let's do a check yeah it passes the first example so now let's look at the generic case it passes the generic case so with that done so let's copy this function signature and then let's use the cotton number so I'm going to call this first version will be one so now let's use a couple in number so I'm going to use a recursion relation in a sense of mathematics so we are going to use this formula right so here let me initialize a result variable so initially what then we are going to iterate intense right so for I in range n right and then the result equals the first result times the factor here the factor so it's 2 times 2 times I plus 1 and the integer division by I Plus 2. so lastly finish this iteration or for Loop so we can return iteration or for Loop so we can return the result stage so actually if we like the result stage so actually if we like actually there is a formula for this actually there is a formula for this content number in terms of factorials content number in terms of factorials like here so you can do this directly so like here so you can do this directly so you can get more information on categy you can get more information on categy number in this Wikipedia page so with number in this Wikipedia page so with that said let's do a check that said let's do a check it passes the first example now let's it passes the first example now let's look at the generic case that's about it for the second solution so I guess that's about it for this specific problem so um here actually the version V1 as more natural so if we do not know the counting number right in mathematics so with that said I guess that's it for | 2024-03-20 13:39:43 | 96 | leetcode 96. Unique Binary Search Trees - DP or Catalan Number |
|
KWhldAv5i6g | Perfect square which is here, we have given, so our people solve it, let's given, so our people solve it, let's see how our people will do this, first of all we read the question problem statement, what do we have, then read the question problem statement, what do we have, then inside the question we have a wait and given, we have to inside the question we have a wait and given, we have to return. return. return. square number tu dat sam tu n ok hai as here I am our people can take it as an example in a way let's suppose for example date is given tu as sam this is an example with this we all can understand the question as Let us understand Let us understand Let us understand what is actually said in the question, okay, what is actually said in the question, okay, inside the question we have basically said that inside the question we have basically said that let's suppose for example, we have the let's suppose for example, we have the value of n given, okay and given is our own, we have the value of n given, okay and given is our own, we have the value of n. value of n. value of n. given 12 then other equals are equal to 12. Here we have basically got 12. Now what we have to do is we will read to find the numbers which we have which are perfect square and whose sum Let's Let's Let's assume for example four plus four four plus four plus four, what will be its value here, what will we get here will be equal to 12, okay can we have any other thing, see here Is it a Is it a Is it a square or not, that van is also there, starting from van, square or not, that van is also there, starting from van, okay 149, all these are okay 149, all these are examples of your perfect square, so examples of your perfect square, so from four we have a perfect square, so from four we have a perfect square, so I will sum it, then we will have the answer which is I will sum it, then we will have the answer which is basically, will anyone else come out? basically, will anyone else come out? We all can do this. For Sam of Han 12, the We all can do this. For Sam of Han 12, the second approach second approach is basically that I select nine once and then is basically that I select nine once and then select Van three times, this also select Van three times, this also we will have basically equal to 12 but the we will have basically equal to 12 but the number of coins here. number of coins here. number of coins here. will we have here? If you see, the number is looking like three. We will do the number of time. They are also picking three times from us. Okay, and from the number of time, I will do the combination of 91 here. So here we will have. Basically there is 4A and what combinations can there be or look at the combination box, okay here the okay here the solution that we can have is what do I do solution that we can have is what do I do 12 times take 1 okay so this is what 12 times take 1 okay so this is what we have basically we have basically we have basically us, which is basically the minimum number of times that we have to perfect, the sum of which will be equal to the given number and end, as if we have given one more example, it is in the test case itself, as if we have So, So, So, what can we pick for 13? Okay, either what can we pick for 13? Okay, either what do I do, I take the phone four times, three times what do I do, I take the phone four times, three times and I take the man once, so here we and I take the man once, so here we basically have four times four, we will basically have four times four, we will have the answer have the answer or what? take one, take one, okay, we have the minimum which will be there, so we will have to return only that, okay, so this is the basically given problem we had, right, now look at one thing, is this the problem which I am reading I am reading I am reading some link from any of them, I am getting it. Okay, some link from any of them, I am getting it. Okay, look here what look here what combinations we have. Look, first of all, what have we all combinations we have. Look, first of all, what have we all done done till 12th, we have given. What till 12th, we have given. What if I basically first collect if I basically first collect if I basically first collect all those numbers which are perfect squares which are less than n like 12. Okay, I will rub all of them once. 10 minutes Here's what you have to do. First of all Here's what you have to do. First of all let's suppose for example, what dreams do we have let's suppose for example, what dreams do we have ? ? ? people think that how can it be possible, there will be 12, then whatever square number we have, which will be a perfect square, we all write those numbers which are less than 12 Okay, like, and the value we have is date, this given date is 12, what do I have to do, I will basically pick any one number as the true date, we will have its value, we will basically get it, so this is the given problem, this is our Looks like it happened somewhere nearby, okay, this is the problem, basically we have one coin change problem, coin change problem number 2 coin change tu hai, two hai apke coin change tu hai, okay so this So, basically, So, basically, So, basically, whatever perfect square we have which is less than n, whatever perfect square we have which is less than n, I will make it, I will find it and I will make it, I will find it and fit it inside the circle, then we will have the question fit it inside the circle, then we will have the question which will be exactly like the coin exchange problem which will be exactly like the coin exchange problem because look, we have because look, we have one four nine. one four nine. one four nine. coins in one way. Okay, we will have coins in one way. If you have problem of coin change then okay, I am going to give you the link. Okay, I will tell you if you do When it comes, you should watch the rest of the video When it comes, you should watch the rest of the video When it comes, you should watch the rest of the video because I am going to complete it, so here we will have because I am going to complete it, so here we will have coins given. I am telling the coin change coins given. I am telling the coin change problem here, problem here, basically the total amount of basically the total amount of value that we have will be given. Okay, now what do value that we have will be given. Okay, now what do you want? you want? you want? true date. Whatever sum we have, we will have it equal to 12. Okay, so this is what we have here, whatever is 9 and 4. Sorry, whatever is here, It will be okay, It will be okay, It will be okay, so let's go to the problem, so friend, so let's go to the problem, so friend, I have understood the perfect square, I have understood the perfect square, we all have to basically pick the numbers from it, of the we all have to basically pick the numbers from it, of the true date, we have selected the minimum true date, we have selected the minimum number of minimum number of number of minimum number of numbers which is this same. numbers which is this same. record, we will focus on the approach. record, we will focus on the approach. What is approach in open hockey? Okay, What is approach in open hockey? Okay, first of all, our people understand, so first of all, our people understand, so what do we have, 149 is given, brother, I give the team to what do we have, 149 is given, brother, I give the team to everyone, what do we do? First of all, we will If we say in the bottom then we will If we say in the bottom then we will If we say in the bottom then we will go from bottom to top, so first of all we go from bottom to top, so first of all we come to nine, I have fixed the index here, come to nine, I have fixed the index here, okay, okay, I have fixed the index here, then only here I will be able to select it, then only here I will be able to select it, okay. okay. okay. that if its value would be bigger if we have it, see like if we had 16 here, 16 would not come. The first thing is fine, then putting a condition on it Whichever number has been allotted by all the people Whichever number has been allotted by all the people Whichever number has been allotted by all the people earlier will not be less than these, nor will it give earlier will not be less than these, nor will it give you a billion, nor will you have a number less than N. Whichever number less than N. Whichever number you have will be a perfect square, like if it was 149, then number you have will be a perfect square, like if it was 149, then all of these will be less than 12th. all of these will be less than 12th. People will create the functions in such a way that they will People will create the functions in such a way that they will give less value than it takes, so in this case we will basically have a choice so in this case we will basically have a choice either you include it or either you include it or you don't include it, okay here you don't include it, okay here we will reduce one variable. we will reduce one variable. we will reduce one variable. it, there will be two choices inside it, either include or not, if I include, what will I do, I will subtract from the value, whatever we have is the value of the index, I have included, so what will happen here, Added it and here we have the value, in this case, okay, I okay, I will show you, okay, before that let us will show you, okay, before that let us look at the code once, as much as I have look at the code once, as much as I have done, this done, this is basically the code for starting. is basically the code for starting. is basically the code for starting. tell you what the people of Apple have done, what all of us have done in the beginning, within that we all have checked whether any number is a perfect Here is the Here is the Here is the function of is not doing anything. function of is not doing anything. In the perfect square function, one will come to us as a number, In the perfect square function, one will come to us as a number, its square root has been done, its square root has been done, okay, as if it has become four, okay, as if it has become four, what will be the square root of four, you will come, okay, so what will be the square root of four, you will come, okay, so you who is here will come to us. you who is here will come to us. you who is here will come to us. we will multiply it later and see if it will be equal, then if it will be equal, then don't be true, wonder false, like in the example, if you have four, then let's see the square of four, like 8 is done, okay, I will convert it to DJ, otherwise it will be return false here, that is, the number which we have is not a perfect square, okay, so this is the whole thing we were getting, then What did all the people do that What did all the people do that What did all the people do that whatever we had in the list became a perfect square, I whatever we had in the list became a perfect square, I basically divided it. basically divided it. Now from here we all see the code, our Now from here we all see the code, our record is only the code, how will our people solve it? record is only the code, how will our people solve it? Okay, remember one thing. Okay, remember one thing. Okay, remember one thing. we have the value of index and you know value which is changing, okay let's start with nine, first of all I will create the tech one inside which I will include the numbers okay initially I will maximum of the interior. maximum of the interior. maximum of the interior. but I will tell but I will tell you why I have not put the maximum of the interior. Okay, first of all, you why I have not put the maximum of the interior. Okay, first of all, what is the condition that whatever value we have, what is the condition that whatever value we have, like 12, if its like 12, if its value is basically big then only value is basically big then only I will be able to include it. I will be able to include it. I will be able to include it. our people will do news after DP. our people will do news after DP. Okay, so this was the thing, now let's Okay, so this was the thing, now let's all do this, so value the value all do this, so value the value of the bull, if we have a good idea of their value, then basically we will have the choice. then basically we will have the choice. then basically we will have the choice. include this one or not, okay take care, either I will include it or not, if I will include it, then we did a step, okay if I include this one, I am including this one inside this one, I will include it inside this one, so here The value of the pass index will not increase The value of the pass index will not increase The value of the pass index will not increase because I can select its previous value also, because I can select its previous value also, like in the example, it is like in the example, it is 12, so people are also using us by 12, so people are also using us by selecting four thrice. Okay, so selecting four thrice. Okay, so if I select it once, then if I select it once, then if I select it once, then second time I can select it, okay, first of all, we have one, I am selecting its value, okay, here we have the index and here we have the date, this is the value, I will give whatever I will give whatever I will give whatever value of index we have, we will write it, we will not select it, meaning what we see that something is happening by selecting on four see that something is happening by selecting on four and here the value will be basically because we have not done anything here, What do people want? What do people want? What do people want? Both of them want a minimum. We have the condition that I have given. Whose will we have? They will select from us and they will not select the number. It's Or Or Or why didn't you take zero? See, first of all why didn't you take zero? See, first of all I tell you because we find the I tell you because we find the minimum value, minimum value, hence questions. Friend, for your 1000 i.e. questions. Friend, for your 1000 i.e. 10000, you will take some more value. 10000, you will take some more value. what will happen? what will happen? minimum value, then the same number is minimum value, then the same number is returned. There is no value more than this. Okay, so for this one, I have made it constunt, after seeing it, there is If it comes then If it comes then If it comes then I have selected the same. I have selected the same. Ok, it was about tech. Now let's talk about not tech. Reduce it because we are in water. Projector needs minimum. Out of both, I have made two calls. Out of needs minimum. Out of both, I have made two calls. Out of both, I both, I need minimum out of tech. need minimum out of tech. need minimum out of tech. notes, what will we do, like I have what will we do, like I have subtracted nine from 12, okay, so only one call will be made here because we all have put a condition here, right here we have, like what will I Here A will go to us, we will have three Here A will go to us, we will have three Here A will go to us, we will have three A will go to us, A will go to us, will we keep it fixed, will I be able to select will we keep it fixed, will I be able to select it back, we will not be able to do this because this it back, we will not be able to do this because this condition has failed, then we will not condition has failed, then we will not take only our people, in this case we will take only our people, in this case we will have, will we have people directly select have, will we have people directly select four from us? four from us? four from us? then the value of three is bigger than four. Okay, so in this case too, what will we all do? We will go ahead by one more. Okay, The The The base case condition that I base case condition that I want to tell in the last season is the date want to tell in the last season is the date that we have made, whatever is the last index that that we have made, whatever is the last index that we have, the van inside it we have, the van inside it will always be fixed. Okay, so the will always be fixed. Okay, so the last is whatever you have, you can make it last is whatever you have, you can make it from any number. from any number. from any number. you will have certain things included, okay, if you divide anything by van, the number will be the same, so if I basically remove this here, So it won't make that much difference, okay, So it won't make that much difference, okay, So it won't make that much difference, okay, but it looks good, okay, so but it looks good, okay, so let's run it and see Its a request, let me Its a request, let me tell you one more thing, what will be the time frame that we have, see what will be the time frame that we have, see what I can do here. what I can do here. what I can do here. time complex? It is time complex? It is a simple thing, I have a given, let's assume that a simple thing, I have a given, let's assume that what is inside it, I have given what is inside it, I have given elements A, so inside that we will have elements A, so inside that we will have options that I can select or options that I can select or options that I can select or n't select then I will have so many options from the element, they will be N on 2 rest, the option is fine but its the time which we are black city, those 2 races are more than you par N, the reason is know what There will be a change van, There will be a change van, There will be a change van, what was there inside that you will select what was there inside that you will select and by selecting you will reach further, it and by selecting you will reach further, it is okay as if the number is given like this then is okay as if the number is given like this then here you will select but even here you will select but even after not selecting here, you still have the option, after not selecting here, you still have the option, do you? do you? do you? become two, I can select two any number of times, so 2 * K is the number of times you will select it and the value of K is not fixed, you Its time is also Its time is also Its time is also exponential, so then friend, this is a exponential, so then friend, this is a bad thing, you will have to miss it, if your bad thing, you will have to miss it, if your people are okay, then your people people are okay, then your people will put DP, here, your people will put DP for you, will put DP, here, your people will put DP for you, okay then we will do memorization, what will we do first, we will make DPR. what will we do first, we will make DPR. what will we do first, we will make DPR. okay second thing here I will do, you are DP so what will we do here is memorization so first of all we all will fill -1 inside all What will I do, I will call the DP, What will I do, I will call the DP, What will I do, I will call the DP, okay and here the DP went, we had Van Four Nine at that time. Okay, 100, now what do I do here? Science, later you guys will tell me the tabulation, so I reduce it, make some changes inside the court, here, I index it as van, van tu three, The game that follows is basically one and only The game that follows is basically one and only The game that follows is basically one and only three, but here I three, but here I will do one thing due to which it will seem as if it is will do one thing due to which it will seem as if it is going on as it is, okay, so let's see going on as it is, okay, so let's see how our people will write it, right here, call in advance. call in advance. call in advance. if the value of the index here is basically one, then what will I do in this case [Music] I will make the and and here we will do the index wherever it is. index wherever it is. index wherever it is. rest of the things are going to come from what we have, okay here you have to put that DP widgetized DP off if you want to reduce it, okay keep doing it. size of the perfect square has been made, now what do we reduce here, which is the code for memorization, we all will do the same code for memorization. Sorry, I have written only one condition here, It is okay to write it here, It is okay to write it here, It is okay to write it here, without that, here we start from zero, zero one three, this is basically the index that we have, whatever we have, people had created from the you know natural numbers, this is what we have, basically the But But But I have definitely forgotten to write the condition, but I have definitely forgotten to write the condition, but you have to remember that if I have the you have to remember that if I have the value of the index here, then if the value of the index here, then if the value of the index here comes to us as zero, value of the index here comes to us as zero, then what will I do in this case, then what will I do in this case, here we will return What will happen because if you have zero in your index then it means that we have zero index. Okay, let me tell you that it is given that we have the value of N which will be more than Van, If If If one WAN number is created then one N one WAN one WAN number is created then one N one WAN number will come to you every time, number will come to you every time, so write the condition we have or not, it does so write the condition we have or not, it does n't matter, it's okay, but it doesn't matter, there n't matter, it's okay, but it doesn't matter, there is a concept of one thing, so then is a concept of one thing, so then we will try to understand it a little. we will try to understand it a little. we will try to understand it a little. okay, so wherever the value of the index here, we will get zero, there, I will make 10 rest tu power four. What is the meaning of 10 raw power four, What does no zero mean, What does no zero mean, What does no zero mean, you have it, it is given, I am you have it, it is given, I am carrying one index here, carrying one index here, okay, now here it is a simple thing, you have okay, now here it is a simple thing, you have zero index, meaning we you, we have zero index, meaning we you, we have not even a single you no number has come out. not even a single you no number has come out. That's right, even one of us has turned out to be a That's right, even one of us has turned out to be a perfect square. It's okay, so the van will perfect square. It's okay, so the van will always come to us, so always come to us, so write it or not, there is no problem, but to write it or not, there is no problem, but to understand, we are doing this on this understand, we are doing this on this in a group of four. in a group of four. in a group of four. all this, basically the team will have done it, okay nine, what will happen if we have the value of the index in one place, then if the value of the index comes to me in one place, then I will return it or what can you do Pay Pay Pay return value or the meaning of return is that you will get only one, that is, you will get any number divided by one, that you will get only one, that is, you will get any number divided by one, that is the same number, fill the same number, fill zero, one, that is the same number, fill the same number, fill zero, one, three, it is right, so three, it is right, so basically you fill the numbers in such a place. basically you fill the numbers in such a place. Okay, now what do we have with our people, now here we all will have to take the complete conventional method which we have all these methods. Okay, here what will you have to do, let me complete it. Okay, by First let's do the code, First let's do the code, First let's do the code, whatever we have is the establishment code, we have value, it will go up to then what do you have to do, here you don't have to do anything, then what do you have to do, here you don't have to do anything, you have to you have to pick up whatever we had, so pick up whatever we had, so this. this. Well, the concept will be the same, Well, the concept will be the same, okay, you can do it. So, if you have the okay, you can do it. So, if you have the value of the index, then value of the index, then what will you have to do. What will be the value of the DPO of the what will you have to do. What will be the value of the DPO of the index? index? You will have to enter one more condition. You will have to enter one more condition. You will have to enter one more condition. index and will be solved then ok good ok do return [music] put equal tu sign because it will work for zero so that After this, I will explain to you the code once, in less page, in less page, it was give the statement, okay, now here we have the first time which comes out, you have to If it is then here you will have a If it is then here you will have a If it is then here you will have a take whose value is take whose value is 4 groups. Okay and along with that you will have 4 groups. Okay and along with that you will have a nonte. Right now look here you will have to see the minimum value, I have forgotten to tell you here, you have to do it, the According to the calculation, the same will come but also see one thing According to the calculation, the same will come but also see one thing According to the calculation, the same will come but also see one thing that if you have zero values that if you have zero values then you will not use it for anyone else, then you will not use it for anyone else, here you will get only zero here you will get only zero coins, there is no need to do it, so coins, there is no need to do it, so here we have here we have here we have fill its value which is zero, now let's talk about this thing by name, take here till here, van tu will be three, so I will be able to do it with only 11 coins, Because all these Because all these Because all these problems are divided into four, so what will we do here, one coin will be selected, right four will come, you have got one point and together, what will come out here Music] Music] Music] If we have here the value means four If we have here the value means four minus zero, okay, now we have to compare that value between the minimum, we have to find the four between van and four, that is, the date which was above it is It It It will come, it's okay whether you include it or not, that's the will come, it's okay whether you include it or not, that's the same thing because you have same thing because you have included it after yourself in the index, so whether included it after yourself in the index, so whether you include it or not, it doesn't matter, even you include it or not, it doesn't matter, even if you don't include it, it won't make that much difference, right. right. what will we do here, if then you will date as a friend, you will get the answer, you will have the answer, which is the actual answer, okay, I told you, friend, whether to include it or not is up to you, okay? I see here, even if I n't include it, it will still be submitted to us. I was linking the problem with coin change, linking the problem with coin change, that's why I was doing that, that is why I that's why I was doing that, that is why I said what is already written. said what is already written. said what is already written. being accepted, please submit and show it, it will okay, so the video is very long, I am okay, so the video is very long, I am sorry for that, I hope you have sorry for that, I hope you have understood something from this video, the understood something from this video, the problem is okay, then do problem is okay, then do like it. | 2024-03-22 14:02:41 | 279 | Perfect Squares || Leetcode-279 |
|
q4Vr307dOzs | hi guys welcome to algorithms made easy my name is khushpu and in this video my name is khushpu and in this video we'll see the question best time to buy we'll see the question best time to buy and sell stock part three and sell stock part three you are given an array prices where you are given an array prices where prices of i is the price prices of i is the price of the given stock on ith day of the given stock on ith day we need to find the maximum profit that we need to find the maximum profit that we can achieve we can achieve given that you may complete at most two given that you may complete at most two transactions transactions you may not engage in multiple you may not engage in multiple transactions simultaneously that is transactions simultaneously that is you must sell the stock before you buy you must sell the stock before you buy again again let's see the example number one wherein let's see the example number one wherein we are given the prices and the we are given the prices and the explanation states that buy on day four explanation states that buy on day four at price zero and sell on day six at at price zero and sell on day six at price 3 which is this transaction price 3 which is this transaction and and then buy on day 7 at price 1 and sell on then buy on day 7 at price 1 and sell on day 8 at price 4. so this is this day 8 at price 4. so this is this transaction if you do a total you get 3 transaction if you do a total you get 3 plus 3 which is 6 that is the output so plus 3 which is 6 that is the output so in example one we did two transactions in example one we did two transactions let's see the example number two in the let's see the example number two in the example number two the array is given in example number two the array is given in an increasing order so we can just buy an increasing order so we can just buy this stock at one rupee and sell it at this stock at one rupee and sell it at five five which gives us the highest profit which which gives us the highest profit which is of four rupee is of four rupee the example number three has a the example number three has a decreasing array which means that no decreasing array which means that no transaction will give us a profit so we transaction will give us a profit so we are not going to buy or sell the stock are not going to buy or sell the stock and our profit remains zero so now with and our profit remains zero so now with the examples it is clear that we can the examples it is clear that we can have either zero one or at most two have either zero one or at most two transactions to find the maximum profit transactions to find the maximum profit that we can achieve that we can achieve so let's go ahead and see how we can so let's go ahead and see how we can solve this question solve this question when there was a single transaction when there was a single transaction allowed which was in the part 1 of the allowed which was in the part 1 of the question question what we did was we found out the minimum what we did was we found out the minimum and stored it and stored it and then at each step we used to find and then at each step we used to find the maximum profit that we could achieve the maximum profit that we could achieve by considering the minimum that was the by considering the minimum that was the buying point and maximizing the profit buying point and maximizing the profit by finding the maximum value at which we by finding the maximum value at which we can sell the stock with this approach can sell the stock with this approach our output would have considered this our output would have considered this particular transaction particular transaction now now when we say that we can make at most two when we say that we can make at most two transactions it means we can either have transactions it means we can either have zero one or two transactions so looking zero one or two transactions so looking at this graph at this graph we can make one transaction for this we can make one transaction for this particular range and the second particular range and the second transaction transaction in this particular days this will in this particular days this will maximize our profit and that's what we maximize our profit and that's what we want to achieve in this question want to achieve in this question if we see here we have two transactions if we see here we have two transactions transaction one and transaction two transaction one and transaction two which is dividing our sequence into two which is dividing our sequence into two parts parts and these transactions are and these transactions are the transaction that are giving maximum the transaction that are giving maximum output in these two different parts output in these two different parts so we can consider these parts as left so we can consider these parts as left and right so for a given point if i am and right so for a given point if i am considering or if i am dividing my considering or if i am dividing my sequence on day three then i need to sequence on day three then i need to find out the maximum profit i can find out the maximum profit i can achieve from day zero to day three achieve from day zero to day three and the maximum profit that i can and the maximum profit that i can achieve from day 3 to d6 achieve from day 3 to d6 combining these two combining these two will give me the answer for this will give me the answer for this particular question wherein i am making particular question wherein i am making at most two transactions at most two transactions for that what we are going to use is for that what we are going to use is bi-directional dynamic programming as bi-directional dynamic programming as the name suggests it is going to have the name suggests it is going to have iterations in two directions one being iterations in two directions one being from left to right and the other being from left to right and the other being from right to left and since it is dp we from right to left and since it is dp we are going to store intermediate results are going to store intermediate results of the maximum profit we can achieve of the maximum profit we can achieve till that particular date till that particular date so let's take this example which is the so let's take this example which is the prices array prices array and we will take a left array which is and we will take a left array which is our intermediate result to store the our intermediate result to store the profit that we are achieving when we are profit that we are achieving when we are iterating from left to right iterating from left to right over here we are also going to have a over here we are also going to have a variable which will store the minimum variable which will store the minimum price that is the minimum buying price price that is the minimum buying price initially at zeroth index the profit initially at zeroth index the profit will be zero because the most you can do will be zero because the most you can do is buy it three rupees and sell at three is buy it three rupees and sell at three rupees and our minimum gets updated to rupees and our minimum gets updated to three moving ahead when we come to this three moving ahead when we come to this particular index now we are going to see particular index now we are going to see if my minimum is changing or not if my if my minimum is changing or not if my minimum changes i'll update that minimum minimum changes i'll update that minimum buying price in my min variable buying price in my min variable and and i can find out the profit that is the i can find out the profit that is the maximum profit till the current index maximum profit till the current index so so that maximum profit can either be the that maximum profit can either be the profit that i have already observed profit that i have already observed previously previously or the profit that i will make or the profit that i will make by selling the stock on the current by selling the stock on the current price which will give me the profit of price which will give me the profit of prices of i minus min prices of i minus min which is the buying price currently for which is the buying price currently for this particular index since this this particular index since this particular price is equivalent to the particular price is equivalent to the minimum price this is going to be 0 minimum price this is going to be 0 because it will be maximum of either 0 because it will be maximum of either 0 or or 3 minus 3 0 which gives us 0 moving 3 minus 3 0 which gives us 0 moving ahead ahead now i have a higher price my previous now i have a higher price my previous profit was 0 profit was 0 and my current profit now becomes and my current profit now becomes 5 minus 3 which is 2. 5 minus 3 which is 2. if i see the maximum profit it will be if i see the maximum profit it will be either the max of 0 either the max of 0 or 2 which gives us or 2 which gives us 2. 2. similarly i'll go ahead and check for similarly i'll go ahead and check for this particular index this particular index now since my buy price is 0 which is now since my buy price is 0 which is lesser than the previous buy price which lesser than the previous buy price which was three was three i'll update the minimum variable that is i'll update the minimum variable that is i can buy lowest at zero rupees i can buy lowest at zero rupees considering this the profit becomes zero considering this the profit becomes zero for the current transaction for the current transaction and the profit that i have already seen and the profit that i have already seen previously was 2 so i just take the same previously was 2 so i just take the same value and put it in the current index value and put it in the current index for profit if you do continue this till for profit if you do continue this till the end of the array the end of the array you will get the profit that you can you will get the profit that you can achieve by traveling from left to right achieve by traveling from left to right on each and every day now we have the on each and every day now we have the left array we need to find out the same left array we need to find out the same thing while starting from thing while starting from right to left so we'll take a right right to left so we'll take a right array and we'll start from the end of array and we'll start from the end of the array since we are starting from the the array since we are starting from the end of the array we will now have the end of the array we will now have the selling price that is going to be the selling price that is going to be the maximum price at which i can sell the maximum price at which i can sell the stock stock which is currently 4 that is value in my which is currently 4 that is value in my prices array prices array and now as i move ahead i need to find and now as i move ahead i need to find the maximum profit that i can achieve by the maximum profit that i can achieve by saying that this is the maximum value at saying that this is the maximum value at which i could have sold the stock and which i could have sold the stock and the current prices of i being the buying the current prices of i being the buying price price so so when we go over here when we go over here my sell price is 4 my buy price is 1 and my sell price is 4 my buy price is 1 and my profit would become either the my profit would become either the maximum profit i have seen previously or maximum profit i have seen previously or the profit from the current transaction the profit from the current transaction that is from buying at this particular that is from buying at this particular price which will give me 4 minus 1 that price which will give me 4 minus 1 that is 3 as the profit moving ahead if my is 3 as the profit moving ahead if my buy price now becomes 3 my profit is buy price now becomes 3 my profit is reduced to 1 which i don't want to take reduced to 1 which i don't want to take because i already made a profit of three because i already made a profit of three rupees from the previous transaction so rupees from the previous transaction so the maximum profit was already three so the maximum profit was already three so i just added three over here in this i just added three over here in this particular index similarly when you do particular index similarly when you do this for all the other indexes you will this for all the other indexes you will see the right array filled in this see the right array filled in this particular way now let's see what all particular way now let's see what all these components define if i take this these components define if i take this particular index this 2 is telling me particular index this 2 is telling me that the maximum profit that i can that the maximum profit that i can achieve till this point when i am achieve till this point when i am starting from day 0 is 2 rupees or 2 starting from day 0 is 2 rupees or 2 units while this 4 corresponding to the units while this 4 corresponding to the same index in right array will say that same index in right array will say that the maximum profit i can achieve in the the maximum profit i can achieve in the future starting from this point till the future starting from this point till the end is 4. so at this particular point if end is 4. so at this particular point if i see i see the maximum profit the maximum profit in this area and the maximum profit in in this area and the maximum profit in this area is nothing but this two and this area is nothing but this two and four so four so from the two transactions i can maximize from the two transactions i can maximize the profit up to six rupees which is the the profit up to six rupees which is the maximum that we can achieve so this is maximum that we can achieve so this is one of the way of solving this question one of the way of solving this question now i would like you guys to pause the now i would like you guys to pause the video video and try coding this approach by yourself and try coding this approach by yourself if you get stuck refer to the coding if you get stuck refer to the coding part that i'll be showing now so let's part that i'll be showing now so let's go ahead and code this approach out and go ahead and code this approach out and then we'll see another interesting then we'll see another interesting approach to solve this question let us approach to solve this question let us take a few variables take a few variables that we will keep handy and will also have a base condition that is if n is 0 return 0 and now let's write down the bi-directional dp logic over here first one is from left to right and second would be from right to left traversal let's write the left to right one first initially we'll need a variable min which will hold the minimum buying price and that price is going to be nothing but the price on day zero after that we will start looping and we'll start our loop from index one in this loop the first step is going to be update by price second is calculate current profit third is fill the left array so let's start with step one if the current price is lower we update if the current price is lower we update the min the profit will be selling price minus buying price sell prices the price for current index and buy prices min so over here the profit at current index would become the maximum profit that i can obtain till now so that can be either the previous profit or the current profit the same thing we need to do for right as well but for right we'll take a max which is equal to the selling price and that would be initially equal to the value at last index of the prices array and we'll take a for loop starting from second last index over here again we are going to have three steps the first is second is second is calculate current profit calculate current profit and third is and third is update the right iron update the right iron so let's start with the first step if so let's start with the first step if prices of i prices of i is greater than max is greater than max update max update max now now current profit current profit is nothing but is nothing but the sell price which is max minus buy the sell price which is max minus buy price price which is prices of i which is prices of i and third is and third is the array the array which will be which will be maximizing either the profit that we maximizing either the profit that we have seen earlier that is have seen earlier that is right of i plus 1 right of i plus 1 or the or the current profit current profit now that we are done with this we need now that we are done with this we need to iterate over to iterate over both these arrays and find out the both these arrays and find out the maximum profit from two transactions for that let's take a variable max profit which is initially zero and max profit will become the maximum of either the max profit or leftify plus right of i that's it return max profit and we are done let's hope we haven't made any mistakes let's run it again it's giving a perfect answer let's submit this and it got submitted the time complexity for this approach would be o of 3n which is equivalent to often because we are having three for loops 1 2 and 3. the space complexity is going to be o of 2n or which is equivalent to o of n for these two arrays so that's about this approach now how can you find this in only one pass so let's see that approach so in this approach we are going to see the one pass simulation we can see that this particular question can have four different actions buy off transaction one sell of transaction one buy of transaction two and sell off transaction two let's keep this points handy that is buy sell and profit by selling profit and let's take an example suppose i am giving two coins to buy one stock which is the buy of transaction 1 at cost c1 now when i'm selling the stock i am getting an additional three coins so these three coins are nothing but profit and my sell price becomes c1 plus p1 now let's see the transaction 2. when i'm doing the second transaction for say some amount x the amount that i am actually paying from my own pocket is one coin over here for buying it at cost four why only one coin because these three coins were from the previous profit i used the same profit and gave one more extra coin to buy the share so this effective price for me that i had to pay from my own pocket was nothing but the cost of the second transaction minus the profit that i got from the previous transaction so this was x minus p1 now when i sell the share i am getting some more profit right and then the entire profit of this transaction if you see is nothing but this transaction that is the sell price minus the effective cost of buying this particular share which was nothing but x minus p1 so my entire profit after both the transaction becomes y minus x minus p1 so now at every given point in time we are going to maintain four variables which is the buy price of first transaction which would be the minimum buy price the profit from the first transaction the buy price or the effective buy price for the second transaction which is nothing but the number of coins that i have spent from my pocket to buy that share not including the profit from previous transaction and lastly we'll have the profit which is nothing but this that is the profit from both the transactions together so now my buy price for first transaction is always going to be the minimum price at which i can buy a stock so for that we can have a formula which is nothing but either the previous buy price that is already there with me or the current price on which i am there second thing the profit this profit is the maximum of either the profit that i have seen earlier or the current profit which is nothing but the sell price minus buy price considering that i am selling the stock at current price third thing is the buy price for second transaction which is nothing but my effective buy price or this x minus p1 so that is going to be equal to the minimum of either the buy price that i have seen earlier or the current one which is nothing but price of i minus this profit of transaction 1 that is x minus p1 this is the formula that we have written over here the last thing is profit 2 which is the profit from both the transactions this is going to be the maximum of the profit that we have seen earlier or the profit when we are doing the current transaction so the current transaction profit will be nothing but the sell price at the current price minus the buy price which was my effective buy price for the second transaction that is y minus x minus 1 so y is my sell price x minus p 1 was this that we calculated already so that is by price 2. so now we know from where we are getting this formula let's see one example with this approach so let us take this particular array and this is the table that we have initially the buy prices would be maxed out and the profits would be 0. now starting from index 0 my buy price 1 is minimum of either my buy price or the price of i initially it was max so minimum of both this is 3 profit over here is 0 because if i do the cell transaction at this current price it will be three minus three which is zero by price for second transaction now becomes three again because it is either max or three minus zero and profit of 2 is also 0 with this particular formula because we have either maximum that is 0 or 3 minus 3 that is prices of minus by price of second transaction now let's take the previous values handy with us going to the next iteration or next index now the buy price of the first transaction stays same because we have again the price of 3 which is still the same as the previous one profit is still zero because we bought it three maximum what we can do is selling at this particular price which is three so it becomes zero by four second is also three and profit for 2 is 0. now let's come to this wherein the current price is 5. now we can see from here that we have a profit my buy price is still going to be 3 which is the minimum that i have seen till now profit becomes 2 which is 5 minus 3 by price of 2 is the buy price that i have seen or the effective buy price that i will see the previous buy price was three units and the current effective buy price can be prices of i minus the profit that i have seen from transaction one which also gives us three so this remains unchanged profit of 2 now becomes 2 which is 5-3 moving on to the next index this now becomes my minimum buy price for the first transaction because it is the lowest we have observed my profit becomes 2 which is the previous max profit because if i sell at 0 and i bought at 0 that would give me 0 as profit maximum of 2 and 0 is 2. interesting part over here is the buy price for the second transaction which is the effective buy price what happens over here is that previous buy price for second transaction was three and for the current transaction since the stock is at cost of 0 units and i already have a profit of 2 units so what i am spending is minus 2 rupees because i have extra 2 rupees with me or extra 2 units with me as a profit from the previous transaction now the profit 2 becomes maximum of this 2 or maximum of the profit that i have after buying at this particular buy price which is 2 itself continuing with the same now this by price 2 has changed to minus 2 rest everything is same since we have the cost as 0 unit over here our table is going to stay the same and not change this time let's move ahead when we come to this three our buy price one is still zero maximum profit will now be buying at zero selling at three which is 3 units now i had 2 rupees profit from earlier i need to buy this particular share at 3 rupees so what i am spending now is 1 rupee for my site in this particular transaction so the minimum buy price will be either the previous by price or the current one which still stays minus 2 profit now becomes maximum of either 2 or this 3 minus of minus 2 which now gives me a profit of 5 because this by price that i had earlier was minus 2 current sale price is 3 i had a profit of 2 i am now making a profit of 3 from this transaction and total profit becomes 3 plus 2 which is 5 which is the profit from 2 transactions let's move ahead over here our minimum buy price remains the same and all these tables remain the same when we come to 4 the minimum price over here does not change the profit of buying year and selling here in this transaction becomes 4 my defective buy price 2 is still minus 2 and my profit now becomes maximum of either the previous transaction or the profit from current transaction that is 4 minus of minus 2 which is 6. so what this particular transaction means is that i did a transaction that is buying at this three or this three whichever you want to consider and selling it at five which gave me a profit of two and the second transaction was buying at zero and selling at full which is this profit adding this to we get 6 which is the total profit that we can get so that was the dry run of this particular approach wherein we have the formulas with us and the profit 2 gives us the entire profit from at most two transactions so that's all for this approach i want you guys to try to code this particular approach by yourself before going into the coding part with me so now let's go and code this particular approach out first and the foremost thing that we need to do is take all the four variables so we'll take c1 c2 p1 and p2 c1 c2 will be dot maxwell and p1 p2 will initially be now we'll iterate over the array now we'll iterate over the array now what we are going to do is now what we are going to do is just update all these four variables and just update all these four variables and finally finally return p2 return p2 which is going to hold the cumulative which is going to hold the cumulative profit for two transactions profit for two transactions now now let's see what c1 has let's see what c1 has c1 is the minimum price at which we can c1 is the minimum price at which we can buy so it takes math dot minimum of buy so it takes math dot minimum of either the price that we have seen or either the price that we have seen or the current price the current price what about profit what about profit profit is going to be the maximum profit profit is going to be the maximum profit that i have already seen that i have already seen or the profit from the current or the profit from the current transaction now the current transaction transaction now the current transaction is selling at is selling at this price and buying at this price and buying at c1 what about c2 c2 is the c1 what about c2 c2 is the effective buying price effective buying price which is also going to be the minimum which is also going to be the minimum effective buying price effective buying price effective buying price effective buying price was was calculated using a formula if you calculated using a formula if you remember which was nothing but paying remember which was nothing but paying with the profit we have got from the with the profit we have got from the first transaction so that is nothing but first transaction so that is nothing but cost of current share minus cost of current share minus the profit that i have made from the profit that i have made from previous transaction this is the previous transaction this is the effective buy price effective buy price p2 now becomes the p2 now becomes the maximum profit that we have seen in both maximum profit that we have seen in both the transactions so that is nothing but the transactions so that is nothing but either p2 either p2 or or sell price minus by price sell price minus by price that's it let's try to run this code that's it let's try to run this code and it runs perfectly let's submit it and it runs perfectly let's submit it and it got submitted and it got submitted the time the time complexity over here is o of n complexity over here is o of n that is same the only thing is that it that is same the only thing is that it is a one pass solution is a one pass solution the space complexity if you see over the space complexity if you see over here is o of one because we are only here is o of one because we are only taking four variables taking four variables that's it that's it so that's it for this question guys i so that's it for this question guys i hope you like the solutions please like hope you like the solutions please like share and subscribe to our channel and share and subscribe to our channel and drop your thoughts in the comments and drop your thoughts in the comments and i'll see you in the next one [Music] | 2024-03-21 11:18:06 | 123 | Best Time to Buy and Sell Stock III | Live Coding with Explanation | Leetcode - 123 |
|
6HQzBdROi-I | hello everyone welcome to my your programming Club welcome to my your programming Club today we will be solving another daily today we will be solving another daily code Challenge and the challenge name is code Challenge and the challenge name is minimum speed to arrive on time minimum speed to arrive on time so the channel statement is like this so the channel statement is like this you are given a floating Point number or you are given a floating Point number or representing the amount of time you have representing the amount of time you have to to reach the office to commute to the reach the office to commute to the office you must take entrance in a office you must take entrance in a sequential order sequential order uh so till now what's the problem uh so till now what's the problem statement is saying is let's say t number of hours to reach and then we and there are n number of trains to we and there are n number of trains to reach the office reach the office you must take these entrains in a you must take these entrains in a sequential order it means that if you decide to First Take the let's say first train you will go in the like this this is the first second and third and fourth Trend you uh basically they are whatever these you uh basically they are whatever these you have to take you have to take this is compulsive to take each strain this is compulsive to take each strain but you cannot take trends like this you but you cannot take trends like this you first you take the first string and then first you take the first string and then you take the third one and then you take you take the third one and then you take the let's say fifth one uh it's not the the let's say fifth one uh it's not the sequential order uh so this is the wrong sequential order uh so this is the wrong order of taking the trains you should order of taking the trains you should take in this order only one two three take in this order only one two three four and five I hope till now it's clear four and five I hope till now it's clear and you are also given an integer array and you are also given an integer array distance of length n distance of length n Athan and Athan and the element each element in the distance the element each element in the distance array represents the array represents the distance in kilometers that a particular distance in kilometers that a particular train ride will take train ride will take so so what what is further given is is further given is a train can only depart at an integer R a train can only depart at an integer R so you may need to wait between each so you may need to wait between each train right what it's saying is train right what it's saying is let's say first train taking the first train at a particular speed to Q uh 0.3333 hours okay and now when you will take the second trade let me quickly change the color you will take the second train if they if there is a other train to be taken at all you have to take the ceiling of 0.33333 and what is a ceiling feeling of a number is the least integer which is greater than or equal to the given number so what it's saying is what is the list integer which is greater than or equal to this 0.333 it's one so you you can only take the second ring at one hour at one hour note before that because you cannot take note before that because you cannot take the secondary net the secondary net V3 0.33 hours V3 0.33 hours just after you have finished traveling just after you have finished traveling from uh from training one from uh from training one so I hope it's clear so I hope it's clear now let's move back to the prolong now let's move back to the prolong statement statement for example if the first train takes 1.5 for example if the first train takes 1.5 hours you must wait for the additional hours you must wait for the additional 0.5 hours before you can depart on the 0.5 hours before you can depart on the second Android it's pretty much the same second Android it's pretty much the same thing which I have told you thing which I have told you and what you have to return is you have and what you have to return is you have to return the minimum possible positive to return the minimum possible positive integer speed uh what is integer integer period so that you reach TRS TRS or given us so if you let's move to the constraints part uh n is and here is the length of the distance array which represents the distance for each strain right and Order of n is of 10 raised to power 5 and the distance is in the distance array are reported 10 raised to power 5. and the number of hours that you will be given to reach the office also tests are generated test cases are then tests are generated test cases are then it is such that it is such that the minimum speed uh that will be possible or the answer so it will be our maximum minimum speed so it will be our maximum minimum speed possible possible so if let's say you are traveling with so if let's say you are traveling with the maximum speed or a maximum minimum the maximum speed or a maximum minimum speed possible for speed possible for including all test cases let's say this including all test cases let's say this is the maximum speed you are traveling in each stream let's say then or if this is the maximum speed then you want to know what is the minimum speed then you can say that from 0 to 10 raised to power 7 there are that many options for Speed options for Speed of train or whether this much speed would be sufficient or not that that is another issue uh we have to check for that so these many options are available for value of speed uh since we have to find the common speed for each strain so this is when your options are available and let what's the size of the distance array how many trains we we are will be given uh it will be order of 10 raised to power 5 let uh 10 raised to the power 7 into 10 raise to power 5 it's 10 is to power 12. and it's clearly greater than 10 raised to power it allowed in once again so it will clearly give this Brute Force approach of checking for every possible speed Brute Force for checking for every option uh for checking for every option uh available for Speed will give us tle available for Speed will give us tle so what we need to do we have to so what we need to do we have to optimize this Brute Force approach and for those of you who do not know how the berries berries according to according to input size right now what you can understand is uh right now what you can understand is uh this is the article that will those are this is the article that will those are using I will be providing to you using I will be providing to you and since n is greater than of order 10 and since n is greater than of order 10 raised to power 3 and it's between 10 raised to power 3 and it's between 10 raise to power over 6 so n log n of n of raise to power over 6 so n log n of n of 1 or Logan time complexities will be 1 or Logan time complexities will be fine for the solution fine for the solution so so what you will do in order to make your what you will do in order to make your solution uh uh time complexity according equal to one of these uh so basically you for each distance or train ride for each strain right you have to check the time taken that we cannot reduce but we can reduce the option that we will select for Speed what we will be reducing options that check for speed initially you were having 0 to 10 raise available for Speed available for Speed values values available available for speed of for speed of trends trends and you input force approach you are and you input force approach you are checking for each of these values but checking for each of these values but now what we will be doing is If You now what we will be doing is If You observe these values are in a sorted observe these values are in a sorted fashion fashion so after 0 will come one two three and so after 0 will come one two three and so on till 10 raised to power 7 so these so on till 10 raised to power 7 so these are in sorted order so what we can do are in sorted order so what we can do for the for the next next choice of speed choice of speed [Music] and since and since by research works for in log of end time by research works for in log of end time complexity and here is 10 is 2.7 so order of logo 10 raised to power 7 and into 10 raised to power What will what is the input size of the distance array it's of the order 10 raised to power five it's it will be clearly less than so our solution will be accepted so I will be applying binary search for the next choice of speed first of all you have to understand on for working which thing we are applying binary search for we are applying binary code search for the next choice uh now let's move to the coding part uh now let's move to the coding part there you will be unders you will be there you will be unders you will be able to understand the logic and the able to understand the logic and the implementation in a more clearer way implementation in a more clearer way let me quickly zoom out yeah this is the implementation and what we have done is we have created a helper function find minimum speed binary search what we have done is what we have done is let's say minimum speed let's say minimum speed and also and also it is also told that in the program it is also told that in the program statement that if you are unable to reach office in the given time return minus 1 to indicate that it is impossible to reach so initially we are assuming that is impossible to reach the office so the minimum speed we are taking as minus 1 and the minimum possible value of the speed we are taking as 0 and since it's given that answer will not exceed 10 raised to power 7 so I have taken 10 raised to power 7 plus 1 you can also take 10 raised to 0.7 that would also be fine I just for safety I have taken plus one actually there's uh up to you basically it's the same order of 10 days to power seven so here I have applied a standard binary search but here is that a trickier part in the binary search what we are checking is uh this is the mid will be the mid is uh choice or uh choice or speeds speeds value value so so uh what we are checking is in is enough uh what we are checking is in is enough function function uh if the uh if the current current choice or speed choice or speed is sufficient to make us reach the office in given time Givens which is which is or or this value this value so in this function we are checking that so in this function we are checking that this and it if it's the sufficient this and it if it's the sufficient enough speed currently this will be the enough speed currently this will be the minimum minimum speed speed and up and what we'll do is we will decrease from one previous value to Mid and right from one previous value to Mid and right will be shift shifted at the max will be shift shifted at the max limit of the search space will be limit of the search space will be shifted to one previous two current shifted to one previous two current speed which is mid and if that's not the speed which is mid and if that's not the case the current speed is not enough we case the current speed is not enough we will simply will simply uh shift or minimum value of search uh shift or minimum value of search space to 1 greater than the space to 1 greater than the current speed which is mid current speed which is mid so so uh this is a standard binary search uh this is a standard binary search approach approach and at last we will be returning our and at last we will be returning our minimum speed depending upon whether minimum speed depending upon whether whether the minimum speed value was whether the minimum speed value was uptrended or not uh it will return the uptrended or not uh it will return the answer and let's have a look at the answer and let's have a look at the isana function which is checking if the isana function which is checking if the current choice of speed is sufficient to current choice of speed is sufficient to make us reach the office in a given time make us reach the office in a given time limit limit so what we have done is uh what will be the current time taken if the speed is this so it will be the distance that is to be covered in the trend writer index indx and so this will be the time it will take to cut do a particular train ride and if we are we are another then what we'll do we'll take the then what we'll do we'll take the feeling of the feeling of the current current time taken to use this current train time taken to use this current train and we'll add the current time taken to and we'll add the current time taken to the total time taken and at last we will the total time taken and at last we will return whether the total time taken is return whether the total time taken is in the limit of the given time limit in the limit of the given time limit which was r which was r and yeah that's pretty much it for the and yeah that's pretty much it for the solution part of this problem solution part of this problem now the code will be available in C plus now the code will be available in C plus plus and Java both so thank you for plus and Java both so thank you for watching watching thank you | 2024-03-25 11:26:56 | 1,870 | 1870. Minimum Speed to Arrive on Time | Daily Leetcode Challenge | July | C++ | Java |
|
Szekde9mljQ | hello friends today list of tallest billboard problem you are installing a billboard problem you are installing a billboard and you want billboard and you want to have the lag largest height to have the lag largest height the billboard will have two steel spots the billboard will have two steel spots one on each side one on each side each steel spout must be an equal height each steel spout must be an equal height so simply put that is we are given an so simply put that is we are given an integer rate integer rate we want to separate into two buckets we want to separate into two buckets each brackets bracket is a sum each brackets bracket is a sum equal to the other one but you should equal to the other one but you should notice that notice that we do not need to use up older we do not need to use up older rows so in this example we can separate rows so in this example we can separate into into one two three because they sum up equal one two three because they sum up equal to 6 to 6 and the other bucket you know only have and the other bucket you know only have one road which had the length of 6 so one road which had the length of 6 so we meet the requirement we return 6. we meet the requirement we return 6. in this example we can separate it into in this example we can separate it into two markets uh two three two markets uh two three five they sum up to ten five they sum up to ten and they are the bargains they have four and they are the bargains they have four six they also sum up to six they also sum up to ten and the 10 is the highest ten and the 10 is the highest we can get but you notice that we can get but you notice that we do not use this one it's also okay we do not use this one it's also okay in this example we cannot make it in this example we cannot make it because we only have because we only have one two and we cannot separate into one two and we cannot separate into two markets which have the same height two markets which have the same height so how to do it for each road we we so how to do it for each road we we actually have three actually have three options one is usage and the food is in options one is usage and the food is in the the left bracket the second one is we use it left bracket the second one is we use it and put and put it into the right bucket the third one it into the right bucket the third one is that we do not use it is that we do not use it so i think the idea is straightforward so i think the idea is straightforward that that we just try every possibilities and to get the global max height maximum height but further search better problem we actually uh the hardest part is that we must know how to prove prune prove it pruning well we must know how to do pruning because for example if the left plus right the sun of the left and the right and plus uncheck the uh roads is less than twice of the maximum height we do not need to check anymore because even roads we cannot uh we cannot roads we cannot uh we cannot be uh higher than this already get be uh higher than this already get the maximum height actually we can put a the maximum height actually we can put a u chord side here because if even if the u chord side here because if even if the equal equal we do not need to check anymore we do not need to check anymore um the other way to um the other way to pro to do the pruning is that if the pro to do the pruning is that if the left height left height their absolute value is greater than the their absolute value is greater than the unchecked unchecked sum we do not need to check anymore sum we do not need to check anymore because because even if we put all the unchecked even if we put all the unchecked height to one of these brackets we height to one of these brackets we cannot make these two cannot make these two brackets equal so no need to check brackets equal so no need to check anymore anymore so we can apply these two plugin so we can apply these two plugin techniques so now let's write the code the idea is simple we need to maintain a max global variable we call it max and then we get the we do the or this part we get the an equal to row star length and we needed to get the sum of all these rows so iterate this road in the roads so some plus this road then we do the help function which is actually uh that first search and finally we re return this max so let's see how to implement this well actually we can uh well actually we can uh because it is not sorted we can search because it is not sorted we can search from left to right or from right to left from left to right or from right to left but but i think but but i think the uh the the uh the samples i mean the test cases samples i mean the test cases are strange if i we search from left to are strange if i we search from left to right we will go right we will go turn limit exceeded but if we search turn limit exceeded but if we search from right to left from right to left we are quite fast so whatever we just we are quite fast so whatever we just search for right left let's see the search for right left let's see the parameters we need parameters we need first of course is the red roads first of course is the red roads and we also need the index which and we also need the index which indicate where indicate where are we in the road array are we in the road array the sum of the left bracket the sum of the sum of the left bracket the sum of the right bracket the right bracket in the remain one which is unchecked in the remain one which is unchecked part part so the best case once the index is less so the best case once the index is less than zero we know we must return than zero we know we must return but in what case should we add but in what case should we add the result which is the the result which is the if the left bracket have this if the left bracket have this same height as the right bracket and of same height as the right bracket and of course course they are higher than the max we should they are higher than the max we should update the max update the max to the their height to the their height so now let's do some so now let's do some pruning let's do some pruning pruning let's do some pruning oh why oh oh why oh do some pruning that do some pruning that if the left plus right if the left plus right plus on the remain unchecked plus on the remain unchecked which is less than less or equal than 2 which is less than less or equal than 2 times max we just written and times max we just written and the other part is that we can never make the other part is that we can never make them equal them equal so left minus right so left minus right is greater than remain we just return is greater than remain we just return other parts we just do three check other parts we just do three check because one is another index because one is another index minus one one is put to the current road minus one one is put to the current road to the left market to the left market right keep the right as it is and remain right keep the right as it is and remain minus minus the roads index the other option is put the road to the right market so left unchanged the right plus rows index the remain minus rows index the third is do not use it so index minus one left right and the remain minus rows index okay so let's fill this part there will be rows zero uh zero zero also index is not there index is the roads the length minus one in the row zero zero and the remain is sum okay thank you for watching see you okay thank you for watching see you next time sorry i think it should be next time sorry i think it should be like a like a full uh meaning seconds full uh meaning seconds or something see you next time | 2024-03-25 12:16:06 | 956 | [Check DP Solution Link Below] LeetCode 956. Tallest Billboard Explanation and Solution |
|
vVvq9YoNheM | Hello Hello friends in this section we are going to discuss about another light co problem light co problem product of acceptance of deposits of luxury all will do we product of acceptance of deposits of luxury all will do we call call the product of all elements acid pimple or the product of all elements acid pimple or pimple 3000 will do protector of all pimple 3000 will do protector of all elements subscribe The Channel do all elements subscribe The Channel do all Elements Element Product 5130 Elements Element Product 5130 subscribe and subscribe the Channel subscribe and subscribe the Channel That Apple Problem Statement That Apple Problem Statement Piece Expected to Solve Problem in Order of Piece Expected to Solve Problem in Order of Time Complexity and Without Using Division Time Complexity and Without Using Division Operation All Services Solvent in The Operation All Services Solvent in The Hague Specific Artist Click Half Hour Subscription Will Understand Porn Class Class Class Elements In Next Withdrawal Withdrawal Product With Current Element In 98100 But One Which Assures Will Start At Whose Heart Is Indicative One Adhikari Product Product Element At Index Product Product Element At Index Product Left Side Element Which Product Product Left Side Element Which Product Right Side Element Right Side Element Right Side Element That Boat Lets Have A Product Top 2054 Multiply Between Answers Which Include Element At Index Product Amazon More Products Right Side Element Ultimately Final Product Subscribe That Something Matching Only Noobs Ramdev Opposite Glue Android Product Introduction Element Appointed Final Result Lets Understand This Approach Is Element Is Element Is Element Product Product Left Right Will Use This Product Product Left Right Will Use This Is Element Right Side Product Product From Is Element Right Side Product Product From Right To Left Final Product Subscribe Default Product Product All Elements To Its Previous In Series Index Calculated By Product Product Previous Index Element Multiplied By Previous Product Subscribe Subscribe Subscribe Now to Subscribe Subscribe Products Now to Subscribe Subscribe Products From Right to Left Thursday Nilayam From Right to Left Thursday Nilayam Default Product Default Product I am One Hair Not Wait and Active for a I am One Hair Not Wait and Active for a Previous Index Element Hair One is Previous Index Element Hair One is Pay Click Hair Products for Multiple Top Pay Click Hair Products for Multiple Top 49th Urs Element Subscribe Product 49th Urs Element Subscribe Product Multiple of 100 to the President Android Products Android Products Android Products Final Product Multiply Multiply Multiply That 2286 Multiplicative Reason Divine Final Put It Is The Time This They Didn't Want End Complexity Video Channel Subscribe Left The Channel subscribe this The Channel subscribe this Video plz subscribe Channel Products Which Video plz subscribe Channel Products Which Element In Directions Internet Subscribe Element In Directions Internet Subscribe Product Id Product Id That They'll Take Care Rather Holder Left That They'll Take Care Rather Holder Left Side Product The Side Product The States Initial Satire Intekaam Team Via States Initial Satire Intekaam Team Via Job Element In Areas Default Subscribe Job Element In Areas Default Subscribe 280 Right Side Flu Productive 280 Right Side Flu Productive One Officer Will Update Products Current One Officer Will Update Products Current Element 151 Update Lu Lu Element 151 Update Lu Lu That In Extraction v8 Inductive Will Right That In Extraction v8 Inductive Will Right Side Side Side half glue current element to subscribe our that internet station website indicative right side product fluid two for multiply bittu quite update person update loop current elementary level plug bittu ne Thursday 12561 multiply quality update Subscribe to Video Channel to Novel Calculate Right Side Product A Prostrate Before the Will Cause You Lose A Bevy of and Look Hello Viewers on the Internet From Right to Left and Calculating Right Product Jhal Jhal Flash Lights Declare Attempt Rob Nichol Flash Lights Declare Attempt Rob Nichol Left Side Product In A Position To Set Left Side Product In A Position To Set Default Value Will Give Oo Default Value Will Give Oo Na That Let Complete Final Result Update Jhal To Finally Returned Result Finally Returned Result Disruption With Coding Letter Code Have Already Disruption With Coding Letter Code Have Already Written Friends Sometime We Make A Written Friends Sometime We Make A Call To Products Call To Products Call To Products Kapil Now Input Electronics Result Who Is The Art Which Aspect And Thanks Watching Hope You Like This Video Please Do You Like The Video And To Subscribe My | 2024-03-22 11:33:32 | 238 | Product of Array Except Self - LeetCode 238 - Solution Explained |
|
QzAqTq9MaVk | 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 calculate money in Elite code bank and calculate money in Elite code bank and in this problem someone wants to save in this problem someone wants to save money for his first car he puts money in money for his first car he puts money in a Le code Bank every day he puts $1 a Le code Bank every day he puts $1 Monday and then every day he will put a Monday and then every day he will put a $1 more and then on every subsequent $1 more and then on every subsequent Monday he will put in more than the Monday he will put in more than the previous Monday $1 more given and return previous Monday $1 more given and return the total amount of money he'll have an the total amount of money he'll have an El code bank so here we have four days El code bank so here we have four days so you'll just put in 1 2 3 4 10 days so you'll just put in 1 2 3 4 10 days the first week every day will increase the first week every day will increase and then on the next Monday it's going and then on the next Monday it's going to go back to one more than the previous to go back to one more than the previous Monday and then for a bunch of days kind Monday and then for a bunch of days kind of the same thing so every day increase of the same thing so every day increase by one then on the start of the week you by one then on the start of the week you drop down to one more than the previous drop down to one more than the previous Monday then you increase every day and Monday then you increase every day and then the same thing you have one more then the same thing you have one more than the previous Monday so you could than the previous Monday so you could pretty easily make a simulation of this pretty easily make a simulation of this where you just Loop end times and you where you just Loop end times and you figure out like okay for every day let's figure out like okay for every day let's just add one and then on every single just add one and then on every single Monday let's subtract some number and Monday let's subtract some number and then you can get a total so that's one then you can get a total so that's one way to do it um we're actually going to way to do it um we're actually going to talk about the 01 solution cuz it's a talk about the 01 solution cuz it's a little bit more interesting and uh yeah little bit more interesting and uh yeah it's a little harder to do so we'll get it's a little harder to do so we'll get into into that so there's a few things to that we that so there's a few things to that we need to get the of one need to get the of one solution and the first solution and the first thing is number of thing is number of weeks that pass right like full weeks weeks that pass right like full weeks so the number of full weeks that pass so so the number of full weeks that pass so like for let's um look at like maybe like for let's um look at like maybe this third example so the number of full this third example so the number of full weeks that pass if n equals weeks that pass if n equals 20 is just going to be two 20 is just going to be two right then the second thing we need is right then the second thing we need is number of days left and so for the number of days left we need to figure out basically like how many days do we have leftovers like the remainder after we did some full weeks so in this case we have two full weeks so we have 6 days left and then from there the next thing we need to do is we need to figure out like how do we quickly calculate like we know how many weeks passed is there a way we could just plug this into some math equation and get a result and so notice for our actual if you look at these sequences so like let's look at let's look at the weeks right so for week zero the sequence is 1 2 3 4 5 6 7 for week one it's 2 three 4 5 6 7 8 and then for week two it is 3 4 five 6 7 8 9 so notice for one thing these are arithmetic sequences right they start at some number and then they always increase by constant amount so let's take a look at the totals here so actually for this total this total is 13 18 22 + 6 so 28 this total is the same as the previous total but since every number is one Higher it's going to be 28 + 7 so 35 and this is going to be 42 so basically we can write this down for like for a week so like week zero week one week two week three are actually total for an entire week is going to be like 28 35 42 49 and so on so if we have the number of weeks that we actually fully completed like let's say we completed two weeks in this case we did we can just figure out exactly like what the total is for the two weeks right because we know week one is going to take 28 week two is going to take 35 if we had some arbitrary week um we can just do that number right we can just do 28 plus seven times like the number of weeks and we can figure out like how weeks and we can figure out like how many weeks the last week took so if two many weeks the last week took so if two weeks passed then week two week two at weeks passed then week two week two at this index one one is just going to be this index one one is just going to be um SE 28 + 7 * 1 so we can figure out um SE 28 + 7 * 1 so we can figure out like how long did the last week take so like how long did the last week take so in this case the last week was week one in this case the last week was week one right if it's if the weeks are zero right if it's if the weeks are zero index let's just say um then week one index let's just say um then week one you know Z week week zero took 28 Week 1 you know Z week week zero took 28 Week 1 took 35 so we can figure that out so for took 35 so we can figure that out so for example if 10 weeks passed then we would example if 10 weeks passed then we would just calculate how long did week nine just calculate how long did week nine take that's zero indexed so here the take that's zero indexed so here the first week all always takes 28 or this first week all always takes 28 or this zero index week we can also write it zero index week we can also write it like this to make it a little bit less like this to make it a little bit less confusing and then we can just change confusing and then we can just change our formula a little bit slightly right our formula a little bit slightly right so it be like week one week two week so it be like week one week two week three week four something like this so three week four something like this so we could say Okay week two would take we could say Okay week two would take seven * week what whatever week you're seven * week what whatever week you're on you can just do this if you want it on you can just do this if you want it to be one index so this would also work to be one index so this would also work right so if we're on week two um it it's right so if we're on week two um it it's going to we're going to get 35 week going to we're going to get 35 week minus one so that's totally fine as minus one so that's totally fine as well okay and so now that we know that well okay and so now that we know that what we really need is how to get a what we really need is how to get a total like let's say we let's say we did total like let's say we let's say we did some number of weeks what we really need some number of weeks what we really need is What's the total that we actually got is What's the total that we actually got right because this is per week but right because this is per week but really what we want is we want a total really what we want is we want a total so because this is an arithmetic so because this is an arithmetic sequence is actually pretty sequence is actually pretty straightforward and let's just like have straightforward and let's just like have some easier numbers just to see how we some easier numbers just to see how we could easily do it let's say our could easily do it let's say our sequence instead was like 2 4 6 sequence instead was like 2 4 6 81 and we're trying to 81 and we're trying to get the a get the a average right the idea is because this average right the idea is because this is an arithmetic sequence it increases is an arithmetic sequence it increases by the same amount all we want to do is by the same amount all we want to do is just get an average and then multiply just get an average and then multiply that by the length of the sequence so that by the length of the sequence so here it's kind of pretty straightforward here it's kind of pretty straightforward to get the average the average would be to get the average the average would be the six so we can just say okay well if the six so we can just say okay well if the average is six then we'll multiply the average is six then we'll multiply that by the length of the sequence which that by the length of the sequence which is five so the sum of this sequence is five so the sum of this sequence should just be 30 and if we look at it should just be 30 and if we look at it so it's 18 so it's 18 2430 and that's how you get the um the 2430 and that's how you get the um the total of an arithmetic sequence quickly total of an arithmetic sequence quickly is is it's just going to be first Value is is it's just going to be first Value Plus last value over two to get the Plus last value over two to get the average so we can call this also average so we can call this also average over two times length of the average over two times length of the sequence will be the sum so we're not sequence will be the sum so we're not actually going to build the sequence actually going to build the sequence we're just going to figure it out and we're just going to figure it out and then get the sum so in this case let's then get the sum so in this case let's plug in our numbers so um what's the plug in our numbers so um what's the average the first number in the sequence average the first number in the sequence is going to be is going to be 28 and the second number of the sequence 28 and the second number of the sequence if two week pass is going to be if two week pass is going to be 28 plus 7 * weeks - one so the so the 28 plus 7 * weeks - one so the so the last week that happened was week two so last week that happened was week two so this would be 2 - 1 so the last is going this would be 2 - 1 so the last is going to be 35 so we just take the average of to be 35 so we just take the average of 28 and 35 and then we divide by two so 28 and 35 and then we divide by two so we do 28 + we do 28 + 35 divide by two and then we multiply 35 divide by two and then we multiply that by the length of the sequence the that by the length of the sequence the sequence is two weeks so we just sequence is two weeks so we just multiply by two and then um the twos multiply by two and then um the twos cancel out so we just get this as our cancel out so we just get this as our total so in this case it's it's going to total so in this case it's it's going to be 63 yeah okay and so that is our total for two weeks right so total for the two weeks but now the thing is we also have days left over like in this case we have days left over right we have six days left over and so now we can kind of do the same thing for an arithmetic sequence basically exactly the same thing so if we have six days left over how do we know what the what the numbers are for these six days well we can just figure out what week we're on right so so this is the last week here so it should be 3 4 5 6 7 8 so if we know we are on week three for these last six days and we know every week we add one so because we're on week three we we'd have added one twice right because our numbers are like 1 2 3 4 5 six seven then week two we add one it's 2 3 4 5 6 7 8 uh like up here and then so on so when we're on week three if this was one indexed if this was week one week 2 week three then basically the number we add is just going to be number to add is just weeks or the week we're on minus one right so in this case because we're on week three for these last six days for every single number we will add two so the number for the first day of the days we have left is going to be three and then it's going to be like four five six and so on right so the number for the first day is going to be three and if we have six days left we can just calculate like what's going to be the last day so if you think about it it's going to be like 3 four five 6 7 8 so the number for the last day is just the number for the first day so we can write that down as well number for last day equals number for first day plus the number of days minus one right so that's just like pretty straightforward so the number of days here is six so the number for the last day would be eight that's just like a basic you know if your array increases by one like what's the index like six indices ahead and so on right it's going to be it's going to be whatever the first one was plus the length minus one and so now that we have the first and last day we can do this like range again right where we can take the average and then we can just multiply by the length so let's get an average here and then multiply by the number of days so in this case we have six days so then what it's going to be is it's going to be 11 * 3 which is 33 and if we write out our days again so it's going to be like 3 4 5 6 7 8 we do a total we have 15 21 26 + 7 which is 33 so basically you do this arithmetic sequence sum for the days and the weeks and then you're able to get both of them in 01 because you know exactly like for the last week you know exactly where the first day starts depending on the week because every week you add one and then also for your sums every week for the total week you just add seven so that's kind of how you do it it's a pretty straightforward problem once you know that and this is kind of useful to know how to get the sum of an arithmetic sequence because now you you if you if you recognize you get something like this you never actually have to build it all you have to do is just get an average and just multiply by the length of it okay and now we can code it up so I think uh solution's closer to a medium problem um you know if you were asked to do the sov one so I I think the the simulation is like pretty straightforward so no real point in going over that one okay so we're going to calculate our weeks so we'll say full weeks equals n IDE by 7 then we have our days left over as like the remainder which is n mod 7 so let's say we have uh like n is 20 here we would have two full weeks and then then we would get 20 mod 7 which would be 6 days now we're just going to do this range sum thing for the weeks and then we'll do the range sum for the uh days and then we can just add those together so you say total full weeks equals full weeks times so a lot of these things are going to add together so basically uh the first day is going to be 28 and the last day will be 28 or sorry not the first day uh the first week will be the sum will be 28 and then the last the last last week it'll be 28 plus 7 times some number so this is really going to be 56 plus and then you add seven full weeks minus one times for the last week so get that divide by two so this part gives you the average this this is the length of your act thing okay so the second part is going to be pretty similar where we'll do this for the days left so we'll say total days left equals days left left is going to be the length of this uh arithmetic sequence and then it's going to be kind of similar where the number we start with for both of them will be full weeks so it's going to be two times because the number we start with for both of them will be two or full weeks plus one so for example um if if our full weeks that we went through was two that means this first number of the days should just be three right so it should be like 3 4 5 6 7even 8 so whatever full week who went through Plus One will give us the starting number for both of them and then for the last day we also need to add what we need to add right so the last day is going to be days uh left minus one greater than the first day right so if you do this the first day will be 2 + 1 which is correct and then the last day will be 2 + 1 plus this days left so that'll be 6 minus one 8 so essentially uh this part is going 8 so essentially uh this part is going to be in both of them and then this part to be in both of them and then this part is going to be in the second one so 2+ 1 is going to be in the second one so 2+ 1 2+ one and then this is in the second 2+ one and then this is in the second one so you just combine terms here okay one so you just combine terms here okay and then we also need to get the average and then we also need to get the average here so we got the average multiply by here so we got the average multiply by the length of the sequence and finally the length of the sequence and finally we just return both of these added we just return both of these added together so and there we go and so you could also do this um you could for for your days left you could just do that in a loop because you only have like six days or something so you're still quite saving on constraints here right because if this is a th you could calculate your days left in a loop but basically you can do both of these in in an arithmetic sum so this would be like a true o of one I guess solution and yeah I think this is like significantly faster than um the other ones and I'm sure I guess we H don't need to do that actually so yeah um so we can write down time here uh and it's just going to be a one and space one and also another thing I noticed I don't know if you guys noticed I think they added a new feature Le code I don't know when so you can actually like click on Solutions now and it will literally tell you like here's what the solution that got this was so kind of yeah okay so finally enough here they yeah okay so finally enough here they actually didn't do the arithmetic sum actually didn't do the arithmetic sum and it's actually faster than yeah this and it's actually faster than yeah this is why the Le code Solutions don't make is why the Le code Solutions don't make sense because here they didn't do the sense because here they didn't do the arithmetic sum they actually Loop arithmetic sum they actually Loop through the number of weeks and this through the number of weeks and this ends up being faster so for these small ends up being faster so for these small run times this stuff isn't super run times this stuff isn't super accurate which is kind of hilarious like accurate which is kind of hilarious like a slower runtime solution actually a slower runtime solution actually uh actually is or sorry a bigger time uh actually is or sorry a bigger time complexity actually runs faster so complexity actually runs faster so that's why I said when you get these that's why I said when you get these Solutions like don't really worry about Solutions like don't really worry about what numbers you get worry more about what numbers you get worry more about like theoretical time complexity because like theoretical time complexity because I had plenty of solutions that I wrote I had plenty of solutions that I wrote that are like that I wrote in oen but that are like that I wrote in oen but then like my n log n answer was like then like my n log n answer was like significantly faster somehow so oh yeah significantly faster somehow so oh yeah so that's going to be all for this one so that's going to be all for this one so if you liked it please like the video so if you liked it please like the video and subscribe to your channel and uh and subscribe to your channel and uh I'll see you in the next one thanks for I'll see you in the next one thanks for watching | 2024-03-20 15:21:54 | 1,716 | Calculate Money in LeetCode Bank - LeetCode 1716 - Python |
|
yBXTAfNuOQg | in this video we have to uh generate uh all the possible parentheses valid all the possible parentheses valid parenthesis with a given length so let's parenthesis with a given length so let's understand the problem understand the problem so here we are given some input in so here we are given some input in n is 3 in this case so in in this case n is 3 in this case so in in this case we have to generate all the valid we have to generate all the valid parenthesis which can be formed using parenthesis which can be formed using three open three open and three closing parenthesis and three closing parenthesis so a parenthesis is considered valid if so a parenthesis is considered valid if there is an opening parenthesis followed there is an opening parenthesis followed by by closing parenthesis closing parenthesis or the other way around is not valid for or the other way around is not valid for example if you have this it's not valid example if you have this it's not valid but this one is valid although the count but this one is valid although the count is same we can also have nested is same we can also have nested parenthesis for example in this case parenthesis for example in this case this is the innermost parenthesis this is the innermost parenthesis this is one pair this is one pair and it is nested within this outer and it is nested within this outer parenthesis and so on we can have other parenthesis and so on we can have other combinations for example with three all combinations for example with three all of these are the possible combinations of these are the possible combinations so one two three four five so we have to so one two three four five so we have to return return all those five values all those five values so see uh this is a valid parenthesis so see uh this is a valid parenthesis open open close close then open open open open close close then open open close so so if you look at this inner close so so if you look at this inner parenthesis parenthesis it's valid and then we have another it's valid and then we have another valid parenthesis pair of parenthesis valid parenthesis pair of parenthesis and then these two are enclosed within and then these two are enclosed within this outer parenthesis and you can this outer parenthesis and you can verify it's true for all there is no verify it's true for all there is no other possible ah arrangement of this other possible ah arrangement of this open and closed parenthesis so that they open and closed parenthesis so that they remain valid so we have to figure a way remain valid so we have to figure a way of returning this of returning this so if there is a n is three then we have so if there is a n is three then we have total six parenthesis three open and total six parenthesis three open and three close three close so let's see how we will attack this so let's see how we will attack this problem first let's try with this problem first let's try with this example of three example of three so initially our solution space is empty so initially our solution space is empty so there is no nothing in the result let so there is no nothing in the result let us say this bracket is the list denoting us say this bracket is the list denoting the result the result so initially it is empty so initially it is empty next uh one thing you can notice is that next uh one thing you can notice is that a closing parenthesis cannot come before a closing parenthesis cannot come before opening parenthesis or let's say we have opening parenthesis or let's say we have one opening parenthesis and then one one opening parenthesis and then one closing parenthesis now the count of closing parenthesis now the count of both open open is one both open open is one closes one closes one again if we place a closing parenthesis again if we place a closing parenthesis then closing parenthesis becomes more then closing parenthesis becomes more than open parenthesis till this point if than open parenthesis till this point if we are going from left to right we are going from left to right so at any point of time we have to keep so at any point of time we have to keep in mind that number of open parentheses in mind that number of open parentheses should be more than or equal to number should be more than or equal to number of closing parenthesis otherwise it will of closing parenthesis otherwise it will be invalid so this is one check and the be invalid so this is one check and the other condition is that maximum number other condition is that maximum number of of open and close parenthesis should be 3 open and close parenthesis should be 3 in fact in fact it should be exactly 3 but at any given it should be exactly 3 but at any given point of time it should not point of time it should not go more than three go more than three so keeping those two points in mind one so keeping those two points in mind one is that is that open should always be more than equal to open should always be more than equal to close close number of close parenthesis number of close parenthesis and and open should be at any point of time we have not yet reached the complete solution but we are adding parenthesis one by one so at any point of time it should be less than or equal to n in our case it's 3 so we are taking the example of three so here initially our solution is empty we are not reached at any solution so we are allowed to add only open parenthesis since here open is 0 close is 0. so we if we add close that violates this condition so we will only add one open parenthesis so this is the string that is formed so or we can get rid of this square bracket or we can get rid of this square bracket so this is the current string now we so this is the current string now we have open equal to have open equal to one one so open is now 1 close is zero so we can so open is now 1 close is zero so we can add both add both so we can add so we can add one closing parenthesis one closing parenthesis one opening parenthesis that's fine we one opening parenthesis that's fine we can add open because open is still less can add open because open is still less than three or we can also add close parenthesis since it does not violate both of these conditions so this is another possibility from this value from here we can reach these two now if you look here at this part open is 2 close is 0 and in this case open is one closes one so here there are two open so we can add so here there are two open so we can add one more open so that is another one more open so that is another possibility now open S3 closes zero so here there is another possibility that we can add one because open is 2 close is 0 so we can because open is 2 close is 0 so we can add one close add one close now here again uh we cannot add any now here again uh we cannot add any further open because open has reached 3 further open because open has reached 3 and 3 is the limit and 3 is the limit for n equal to 3 so we can only add for n equal to 3 so we can only add one closed parenthesis so let's draw it below and here again open is 3 so we cannot and here again open is 3 so we cannot add any further open and close is one so add any further open and close is one so we can add more close we can add more close parenthesis parenthesis now it's 3 2 so we can add one close now it's 3 2 so we can add one close parenthesis now there are three open parenthesis now there are three open three Clues we have reached a solution three Clues we have reached a solution so this is one of the solutions so this is one of the solutions now let's get back to here open is 2 now let's get back to here open is 2 closes one closes one so we have two possibilities so we have two possibilities we can we can add add after this point we can add even open after this point we can add even open because open is not yet 3 or we can add one close because close is less than open now from here we have three open parentheses so we cannot add any further open parenthesis so only thing we can add to this substring is this close parenthesis and same thing three open two close we can one close and now we have three open one close and now we have three open three close parenthesis so this is the three close parenthesis so this is the solution solution and let's come back to here we have two and let's come back to here we have two open two close so at this point of time open two close so at this point of time we cannot add one closing parenthesis we cannot add one closing parenthesis because that will exceed the number of because that will exceed the number of open parenthesis so we can just add open parenthesis so we can just add this open open close close open this is this open open close close open this is the only possibility and here there are the only possibility and here there are three open two close so only three open two close so only possibilities possibilities one close parenthesis so this is another one close parenthesis so this is another solution so this we have listed all the solution so this we have listed all the possibilities now let's get back to this possibilities now let's get back to this here only thing we can do is add open parenthesis because there is one one each so close can never be more than open and here we have two possibilities so we can have open close open so we can so we can have open close open so we can add open add open and we can also add close now here 3 open so only one possibility close here also three open two close so close here also three open two close so only possibilities close so this is another solution and now here two two each so we cannot add any further close so because close will exceed the number of open so only possibilities open now we have three open to close so we cannot add open since it will cross the maximum limit of three so we can so this is another solution and we have so this is another solution and we have listed down all the possibilities so we listed down all the possibilities so we have these five possible have these five possible these five possible valid parenthesis these five possible valid parenthesis and you can see that the expected value and you can see that the expected value was this same list of five five strings was this same list of five five strings having these parentheses having these parentheses so this is how it works now how we will so this is how it works now how we will convert it to code convert it to code so we start with empty string so so we start with empty string so initially this is empty there is nothing initially this is empty there is nothing here so it is a empty string here so it is a empty string then then uh at all point of time we will check so uh at all point of time we will check so we have this function we have this function let's say list parenthesis let's call let's say list parenthesis let's call this function p this function p so we start with so we start with empty string and then we check uh we keep track of open and close so open is zero close is 0 initially open is less than n so n is the maximum open is less than n so n is the maximum length length then we call this function again then we call this function again by by adding adding this open parenthesis this open parenthesis open equal to 1 close equal to 0 n equal open equal to 1 close equal to 0 n equal to 3. and if close is less than open then only we can add this close to whatever string so let's take a generic string Str or or current string then current Plus open we will add if open is less than n and this will remain same and this will remain same and if close is less than open we we can and if close is less than open we we can call it again with current Plus call it again with current Plus disclose disclose and then open close plus one and three and then open close plus one and three so let's see so here it will the string so let's see so here it will the string is empty when we call is empty when we call it with this we can add this open it with this we can add this open bracket bracket because open is less than 3. because open is less than 3. so it will further call again check that so it will further call again check that open is less than three so it will again open is less than three so it will again call this part call this part again it will call this part again it will call this part now this condition is no more true now this condition is no more true so we made three p calls each time so we made three p calls each time adding one one of these open braces so adding one one of these open braces so we have three nested calls you can see we have three nested calls you can see here here this function was called with this function was called with adding this then again it called this adding this then again it called this this now this first condition is false this now this first condition is false so it will go here close is less than so it will go here close is less than open so at this point of time close is less than open and we cannot add any Open Bracket so we will add this so another call is made another call is made and what is the termination condition so we have to add a termination condition here that if current string so current is the variable here which denotes the running or the current string is equal to 2 times n n was 3 so if it's is equal to 2 times n n was 3 so if it's 6 3 open 3 close then we 6 3 open 3 close then we add this value to the result add this value to the result add current to add current to result Vector so we have to return result Vector so we have to return the all such string so whatever is the the all such string so whatever is the current result at that value there current result at that value there so now get back so here the length so now get back so here the length became 6 and we added it to the result became 6 and we added it to the result so these are the series of calls made so these are the series of calls made here you can see here here you can see here in yellow in yellow so this call returns here there was no so this call returns here there was no other call here so it returns here other call here so it returns here back here back here so this function had back here back here so this function had called triggered this call called triggered this call now now ah ah it will come to this part it will come to this part so this so this option was called the other call can be option was called the other call can be made is adding this closing parenthesis made is adding this closing parenthesis here here so this is the closing parenthesis so this is the closing parenthesis so the left side denote when we added so the left side denote when we added this open parenthesis now again it it this open parenthesis now again it it calls it first tries to add open so it calls it first tries to add open so it can add open parenthesis so it adds now can add open parenthesis so it adds now it calls again with this this again the it calls again with this this again the length is 6 so it will terminate back length is 6 so it will terminate back here back here and this will be added to here back here and this will be added to result result back here and now it will it can it has back here and now it will it can it has already tried with the open uh already tried with the open uh parenthesis so it will add this parenthesis so it will add this closing parenthesis and there is only closing parenthesis and there is only one possibility one possibility and this one possibility one possibility and this will be added to solution since the will be added to solution since the length is 6 so it will return to calling length is 6 so it will return to calling function back back and now this call function back back and now this call terminates and comes back here this call terminates and comes back here this call also terminates comes back here also terminates comes back here and and it tries a bit so it has added this open it tries a bit so it has added this open parenthesis after it so now the other parenthesis after it so now the other possibility is with close parenthesis possibility is with close parenthesis and here just one call is made and here just one call is made here again two calls so you got the idea here again two calls so you got the idea why this should work why this should work so now let's try it in our code so we will have we have to return a and this is result and then let's write a recursive make sure to pass by reference and then the count of open parenthesis count of close parenthesis the maximum length so we have to add the termination so we have to add the termination condition if condition if current dot length current dot length equal to 2 times n equal to 2 times n then then we have to add this to the result we have to add this to the result whatever is the current string whatever is the current string so result Dot current if this is not the case then we current if this is not the case then we have to go down further have to go down further so if so if open is less than n open is less than n then we call this function then we call this function recursively by adding One open recursively by adding One open parenthesis to the current string result or open is one more close remains same n remains same and current becomes current plus this open similarly if similarly if close is less than close is less than open then we will call with and this these recursive calls will and this these recursive calls will terminate once it has six parentheses terminate once it has six parentheses and at any point of time while adding and at any point of time while adding these opening and closing parenthesis we these opening and closing parenthesis we are making sure that those are valid so are making sure that those are valid so once the length becomes equal to 2 times once the length becomes equal to 2 times n or in our example 6. then we know that n or in our example 6. then we know that it's a valid uh combination of it's a valid uh combination of parenthesis parenthesis and here in the main function we will and here in the main function we will call this call this generate parenthesis and we will pass generate parenthesis and we will pass the result the result open should be initially zero open should be initially zero close is also zero close is also zero and the string is empty current is empty and the string is empty current is empty and finally we and finally we return the result so in this case the answer is correct let's submit if all the test cases pass so all the test cases are passing so all the test cases are passing so I hope you understood this this so I hope you understood this this problem looked uh problem looked uh daunting in the beginning but it's just daunting in the beginning but it's just a few lines of code and it gives you a a few lines of code and it gives you a good practice of backtracking so you can good practice of backtracking so you can see here see here we are backtracking we are trying first we are backtracking we are trying first with opening uh adding open parenthesis with opening uh adding open parenthesis and once we reach a solution we go back and once we reach a solution we go back and then try with close parenthesis and and then try with close parenthesis and again continue again continue so it these kind of problems you need to so it these kind of problems you need to will give you a good practice of will give you a good practice of recursion and backtracking | 2024-03-19 17:17:44 | 22 | Generate Parentheses | Leetcode 22 | Recursion |
|
GZU0losKg60 | hello and welcome to today's daily lead code challenge let's begin question code challenge let's begin question 735 asteroid Collision in this question 735 asteroid Collision in this question we are given an array of asteroids of we are given an array of asteroids of integers representing asteroids in a row integers representing asteroids in a row for each asteroid the absolute value for each asteroid the absolute value represents its size and the sign represents its size and the sign represents its direction positive represents its direction positive meaning right negative meaning left each meaning right negative meaning left each asteroid moves at the same speed asteroid moves at the same speed find out find out the state of the asteroids after all the state of the asteroids after all collisions if two asteroids meet the collisions if two asteroids meet the smaller one will explode if both are the smaller one will explode if both are the same size both will explode two same size both will explode two asteroids moving in the same direction asteroids moving in the same direction will never meet will never meet okay let's rephrase this in my own words okay let's rephrase this in my own words we're given a asteroid belt and this we're given a asteroid belt and this asteroid belt there are some that are asteroid belt there are some that are moving to the right some that are moving moving to the right some that are moving to the right to the left some are to the right to the left some are different sizes some are the same we are different sizes some are the same we are a tasked to figure out which ones of the a tasked to figure out which ones of the asteroids are left in the asteroid belt asteroids are left in the asteroid belt after all collisions after all possible after all collisions after all possible collisions have occurred a collision is collisions have occurred a collision is going to occur when going to occur when um two asteroids are moving towards each um two asteroids are moving towards each other other um and um and a collision will eliminate asteroids if a collision will eliminate asteroids if well an elimination is going to occur well an elimination is going to occur but a bigger asteroid will eliminate a but a bigger asteroid will eliminate a smaller one two asteroids of the same smaller one two asteroids of the same size will eliminate each other size will eliminate each other okay and so we're tasked to figure out okay and so we're tasked to figure out which asteroids are left after all which asteroids are left after all collisions have occurred collisions have occurred so so um let's start with some examples we're um let's start with some examples we're given an array of five ten negative five given an array of five ten negative five so these two are moving to the right so these two are moving to the right this is moving to the left it's clear this is moving to the left it's clear that this number 10 moving to the right that this number 10 moving to the right will eliminate the negative five and will eliminate the negative five and we're going to be left with 5 10 since we're going to be left with 5 10 since those are all of the same size those are all of the same size that seems to be the output in this case that seems to be the output in this case they eliminate each other because this they eliminate each other because this one's moving to the right this one's one's moving to the right this one's moving to the left moving to the left and they will cancel out in this case we and they will cancel out in this case we first see that the negative 5 eliminates first see that the negative 5 eliminates the two but then the 10 eliminates the the two but then the 10 eliminates the negative 5. okay negative 5. okay so I guess what to notice here is that so I guess what to notice here is that um I guess what we can notice here is that um um we can compare which asteroids eliminate we can compare which asteroids eliminate which other ones in any order because which other ones in any order because um given let's say that we're that we um given let's say that we're that we have this here have this here um we can know for certain that these two ones will meet eventually and these two two ones will meet eventually so we don't have to look at either one of these in a particular order we can actually just be looking at them one by one we can first look at if these two are are safe then see how adding a third one will affect our sort of safe asteroid belt and then if this gets eliminated or eliminates some in the safe belt we then look at the next one and so on and so on so this kind of gives us a hint into what the approach is going to be um so the hint here is that since they're all moving at the same time it doesn't matter which asteroid collisions we look at first the collisions are going to occur regardless and they're only dictated by the position and the direction in which the asteroids are moving so with that let's have a safe belt and this is going to be essentially a stack and then over the um so this is going to be a stack and then we're just going to iterate over the asteroids that are given to us and see how those asteroids affect our safe belt so for asteroid is in asteroids we're going to do some logic and then we're going to return the safe belt belt okay so how do our asteroids um act in the in the asteroid belt well there is I see a couple of three different scenarios uh scenario one um new asteroid I'm going to call this new asteroid new asteroid El Lima mates sum in the safe belt uh two new asteroid is a limit Ed um and then three which three is a bit sticky I think because it is essentially both of these and it can happen at any time but the third one and I'll figure out where to put this next is uh new s um asteroid eliminates some and then is eliminated and then is eliminated so given that we have these three so given that we have these three scenarios essentially let's figure out scenarios essentially let's figure out um how to treat them um how to treat them well well um um how to treat them how to treat them I know that I know that I know what conditions would make a I know what conditions would make a I know what conditions would make an I know what conditions would make an asteroid be eliminated asteroid be eliminated so so why not why not um why not just start with that how how do how do I treat this hmm I have a new asteroid and my new asteroid will somehow affect the safe belt the belt of asteroids that I have already considered to be safe um what are the different scenarios well I could say that if if an asteroid if the new asteroid is moving to the right then I can essentially just add it without even doing anything is that right so I guess there is a fourth one nothing gets uh nothing gets uh and let's start with this fourth one and let's start with this fourth one actually at the top um let's say that if new asteroid greater than zero save belt append new asteroid pretty simple that seems about right so now what if that seems about right so now what if the asteroid is not moving to the right the asteroid is not moving to the right and what if it is moving to the left and what if it is moving to the left if it is moving to the left then there's if it is moving to the left then there's a condition upon a condition upon there's a condition one where the there's a condition one where the asteroid eliminates some asteroid eliminates some asteroids in the safe belt or asteroids in the safe belt or potentially just gets added to the potentially just gets added to the asteroid belt so asteroid belt so um and but all of these fall under these um and but all of these fall under these three scenarios so three scenarios so if it's already moving to the to the if it's already moving to the to the left then it's going to be one of these left then it's going to be one of these um um let's see under which condition would let's see under which condition would this and this be met and I'm getting a this and this be met and I'm getting a feel that these will be feel that these will be somehow related so if somehow related so if um um save belt save belt negative one is greater than negative one is greater than zero no zero no if it is moving to the right so yes if if it is moving to the right so yes if it is greater than zero it is greater than zero and let's see safe and let's see safe belt belt um negative one um negative one is is smaller than absolute value of new smaller than absolute value of new asteroid asteroid I'm trying to get the situation where I'm trying to get the situation where I'm actually removing or popping I'm actually removing or popping um um asteroids from the safe belt well this asteroids from the safe belt well this would lead me to pop all of the would lead me to pop all of the asteroids that are in the safe belt so asteroids that are in the safe belt so one more time given that we're already one more time given that we're already at this if statement we are our new our at this if statement we are our new our new asteroid is moving to the left and new asteroid is moving to the left and if asteroid belt it still exists and if asteroid belt it still exists and there and the second in the last there and the second in the last asteroid belt is moving to the right asteroid belt is moving to the right which would mean that they're colliding which would mean that they're colliding and the safe belt asteroid is the last and the safe belt asteroid is the last asteroid in the safe belt is smaller asteroid in the safe belt is smaller than the absolute value okay let me see than the absolute value okay let me see this absolute value of the new asteroid then I'm going to be popping this asteroid and This falls under the category of new asteroid uh new asteroid eliminates some in the safe belt and let's see since once it has eliminated all of them um I think it's safe to add the asteroid right uh could I now just say um I need to make sure um I need to make sure that I need to make sure that the that I need to make sure that the asteroid here asteroid here isn't of the same size because if it is isn't of the same size because if it is of the same so if of the same so if um um I actually need to look at oh but how would I okay so if safe belt so if if there is a safe belt and the last asteroid belt and the safe belt the last asteroid belt and the safe belt is if the last asteroid and the safe build if the last asteroid and the safe build is equal to no is equal to no is is if it's larger then if it's larger then let's say equal to new belt then nothing happens both get destroyed both get destroyed if um if however if however um um if how about this how about this first okay I'm going to I'm going to remove this for now I need to see if um I need to see if the safe belt is actually empty if that's the reason why we've stopped this oh and this should be a while while safe belt and belt negative one is greater than zero so there is an asteroid moving to the right and the safe belt last asteroid is smaller than the new I'm going to be destroying them so now what is what is what does it mean that we've passed this while loop either that there's no more either no more safe belt or I've met and S terroid that's greater I've met a safe asteroid that's GR ater or equal to new asteroid okay and we have to take care of all of these scenarios so if the how how how do we do that uh just one at a time would probably be the best solution unless there's some pattern in between them unless unless one of them can go first and the other one can go next okay so how do I do that okay so how do I do that if not safe belt if not safe belt then could I just then could I just save save belt belt append append new asteroid new asteroid right right uh what about uh what about if if not safe belt okay now if safe belt not safe belt okay now if safe belt meaning that there is a uh meaning that meaning that there is a uh meaning that there is something in a safe belt but there is something in a safe belt but they are of the same size no if they are they are of the same size no if they are of the L if if they are of the same size or greater so if they're of the same size then would I if L if safe belt safe belt is greater or equal to is greater or equal to um no let's let's say greater than uh new asteroid if it's greater than new asteroid then if it's greater than new asteroid then how do I then what do I do then I just simply continue I don't do anything the new the safe belt continues to exist and the new asteroid is removed so the only thing I need to care about is if it is the same if it's the same then I say safe belt pop um save that belt pop and is that it I think that's it so if it's the same belt then I don't do anything and I um and I remove yeah I think I think this is this is it yeah I think I think this is this is it um let's try to run this um let's try to run this and and go through the logic one more time go through the logic one more time um um so again the what what I'm trying to do so again the what what I'm trying to do is is essentially safe belt is a stack and I essentially safe belt is a stack and I am trying to write out all of the am trying to write out all of the situations that would situations that would all of the conditions that would or I'm all of the conditions that would or I'm trying to meet all the conditions uh trying to meet all the conditions uh there are three different cases the there are three different cases the cases are the asteroids are just moving cases are the asteroids are just moving in opposite directions or sorry the bet in opposite directions or sorry the bet the better way is the asteroid the new the better way is the asteroid the new asteroid is moving to the right in which asteroid is moving to the right in which case case nothing gets done about it it just it nothing gets done about it it just it just keeps moving just keeps moving the other situation is it's moving to the other situation is it's moving to the left but the left but um um but so but it and and if it's moving to but so but it and and if it's moving to the left there are there are a number of the left there are there are a number of things that can happen either things that can happen either um either we have to remove some um either we have to remove some asteroids from the safe belt and that asteroids from the safe belt and that would be only if the last asteroid and would be only if the last asteroid and the safe belt is moving to the right and the safe belt is moving to the right and is smaller uh than the new asteroid so is smaller uh than the new asteroid so if that happens then we keep on popping if that happens then we keep on popping elements from the safe belt until that elements from the safe belt until that condition no longer meets uh that condition no longer meets uh that condition can break on two different condition can break on two different scenarios one the safe belt is exhausted scenarios one the safe belt is exhausted and if it is exhausted then the new and if it is exhausted then the new asteroid beats everyone and it is now asteroid beats everyone and it is now the start of the new and is now the end the start of the new and is now the end of the safe belt in which case we simply of the safe belt in which case we simply appended and appended and um and move on the other situation is um and move on the other situation is um um the asteroid those the last asteroid is the asteroid those the last asteroid is actually uh bigger than actually uh bigger than or equal to the new asteroid now if it or equal to the new asteroid now if it is bigger than the new asteroid then we is bigger than the new asteroid then we don't really do anything we just don't don't really do anything we just don't we just remove the new asteroid from we just remove the new asteroid from from the condition from the condition otherwise if it's equal to then we pop otherwise if it's equal to then we pop the safe the safe okay so now there's a situation where we okay so now there's a situation where we could actually be popping from the safe could actually be popping from the safe belt for a while because belt for a while because um um yeah so how do I take that into account yeah so how do I take that into account how can we be popping for a while so how can we be popping for a while so um yeah let's let's let's continue let's um yeah let's let's let's continue let's submit this and see where submit this and see where it goes wrong and I yeah it clearly does it goes wrong and I yeah it clearly does go wrong somewhere but go wrong somewhere but uh okay these two are moving to the uh okay these two are moving to the right okay so what goes wrong here because somehow this asteroid gets removed from the stack how does it now how does it get removed okay so let's let's let's start okay so let's let's let's start debugging debugging um started debugging how do we go about this uh well probably I just want to print the um save belt for each one of these iterations and at least see where it would be getting um um so what is the case where so what is the case where so why does one never appear here why does negative one never appear so then at which point would I add it so then at which point would I add it what I only add it if well a save belt if not save belt and then yeah so I'm not looking into the situation where I simply um I simply add the asteroid since it's going to the left with this if if my asteroid if my new asteroid is moving to the left the belt is not destroyed and um it's not equal then couldn't I just say safe belt append new asteroid oh else and now the other ones are failing but and now the other ones are failing but this one is causing so this one is causing so um how do I how do I split up this logic into more blocks hmm um what okay I'm overlooking the situation where the new asteroid is moving to the left if it's moving to the left it's definitely going here and since it's going in here and this scenario then um this is not going to get executed could I just this is not going to get executed so if not if not safe belt or save if not safe belt or save belt belt negative one negative one is smaller well it is going to be is smaller well it is going to be smaller than zero smaller than zero right right smaller than zero append and let go yeah because I can't have that else there there we go okay so I I had that else there and that would meant that things that don't meet the condition in the case where a new asteroid is just not taken acknowled is not acknowledged it was being added so let's let's let's submit here and see if this actually okay time limit exceeded how how can oh because I still have the print oh because I still have the print statement Okay so statement Okay so okay let's submit one more time and I'm okay let's submit one more time and I'm pretty sure this is going to work pretty sure this is going to work um um all right all right who who so that was a bit of a hard one I would so that was a bit of a hard one I would say say um hard not because the um hard not because the not because the implementation is hard not because the implementation is hard but because it's hard to keep track of but because it's hard to keep track of all of the different conditions that are all of the different conditions that are happening one by one so happening one by one so um let me just go through this one more um let me just go through this one more time quickly uh this is I I don't even time quickly uh this is I I don't even know what this is heavy on this is heavy know what this is heavy on this is heavy on just keeping track of different on just keeping track of different conditions that are happening but we conditions that are happening but we have an asteroid belt and we have to have an asteroid belt and we have to meet uh a bunch of different conditions meet uh a bunch of different conditions there's uh two asteroids that could or there's uh two asteroids that could or could not Collide if they're not could not Collide if they're not colliding colliding um um it means that three things are happening it means that three things are happening either the going in opposite directions either the going in opposite directions either they're both going to the left or either they're both going to the left or they're both going to the right they're both going to the right um um that's already that's already three conditions to take three conditions to take no I a lot I lost track they could be no I a lot I lost track they could be colliding one colliding one yeah that is four conditions either yeah that is four conditions either they're not colliding which is those they're not colliding which is those three or they are colliding if they are three or they are colliding if they are colliding then we have to consider which colliding then we have to consider which one will survive or if either Will one will survive or if either Will Survive and that's another three Survive and that's another three conditions uh left one survives right conditions uh left one survives right one survives both survive and then we one survives both survive and then we have to see and then we have to repeat have to see and then we have to repeat that logic so that logic so uh yeah this is a bit of a harder one I uh yeah this is a bit of a harder one I actually don't appreciate these as much actually don't appreciate these as much but but um this is a pretty clean solution still um this is a pretty clean solution still and very little code and very little code uh I would probably imagine that uh I would probably imagine that pretty much the rest are going in the pretty much the rest are going in the same same pattern pattern um um yeah yeah they both are they're all yeah yeah they both are they're all using a stack they're all have a for using a stack they're all have a for Loop and they all have some conditions Loop and they all have some conditions so this one is a bit different but so this one is a bit different but still the same still the same yeah yeah Yep they're all they're all approaching Yep they're all they're all approaching this the same way as stack and an this the same way as stack and an iteration over all of the asteroids so iteration over all of the asteroids so in that case in that case um um I would just see if this one makes sense I would just see if this one makes sense to you and uh feel free to use this all to you and uh feel free to use this all right well thanks for watching and we'll right well thanks for watching and we'll see you later bye | 2024-03-21 11:56:04 | 735 | Asteroid Collision | # 735 Leetcode | Python3 |
|
CdaIX7fDHAI | hey hey everybody this is larry this is the 11th of september so that you'll the 11th of september so that you'll have on the september league daily have on the september league daily challenge challenge hit the like button to subscribe and hit the like button to subscribe and join me on discord let me know what you join me on discord let me know what you think about today's problem basic think about today's problem basic calculator um you know i'm from new york calculator um you know i'm from new york i grew up in new york my high school was i grew up in new york my high school was actually um a couple of blocks away from actually um a couple of blocks away from um um from uh from uh the old world trade center so yeah i the old world trade center so yeah i hope everyone hope everyone you know i don't know what to say about you know i don't know what to say about these things but yeah i just hope these things but yeah i just hope everyone kind of keep it in mind and everyone kind of keep it in mind and and i don't know maybe just sitting in and i don't know maybe just sitting in some of us it's kind of tough to figure some of us it's kind of tough to figure out what is up but it is 20 years so 20 out what is up but it is 20 years so 20 years is a long time years is a long time um anyway you're not here for that i um anyway you're not here for that i suppose but you know but i am from new suppose but you know but i am from new york and york and it's in the handle so you know gotta it's in the handle so you know gotta it is what it is right um anyway today's it is what it is right um anyway today's problem is basic calculator um so okay problem is basic calculator um so okay return to resolve the evaluation you're return to resolve the evaluation you're not able to use any url okay okay so not able to use any url okay okay so this is kind of um a silly problem that basically you know i mean it's just what implemented right except for that it it could be messy and you know it's a very implementation heavy one uh the one that makes it slightly easier is that it only has plus and minus um so yeah so i don't think there's that much to explain um there are a couple of ways you can do it you could do it with stack you could do recursive descent uh and stuff like that recursive descent uh and stuff like that if you like um and if you want to learn if you like um and if you want to learn more you know google them but this is more you know google them but this is you know passing has been a thing that's you know passing has been a thing that's been been you know um from the beginning of you know um from the beginning of computers computers ever since you have computers you want ever since you have computers you want to pause and people build you know to pause and people build you know languages and languages and and stuff like that and there's a lot of and stuff like that and there's a lot of fun things you can do with it so fun things you can do with it so you know so and you know so and i don't know if this is still in style i don't know if this is still in style anymore but when i was younger anymore but when i was younger definitely um definitely um these kind of problems were on more these kind of problems were on more interviews because they were considered interviews because they were considered practical because you know these are practical because you know these are things that you do in real life things that you do in real life yeah maybe at the time anyway in theory yeah maybe at the time anyway in theory because nowadays you could just you know because nowadays you could just you know their functions and their libraries and their functions and their libraries and their language libraries and stuff like their language libraries and stuff like that and the libraries on that libraries that and the libraries on that libraries that kind of help you do these things that kind of help you do these things anyway but um anyway but um but yeah but yeah uh without further ado i do uh without further ado i do let's uh you know take advantage of this let's uh you know take advantage of this this subset because we don't have to this subset because we don't have to worry about we don't have to worry about um we don't have to worry about the order of operation because we only have plus and minuses uh i could be used as the unit has to be um what does that um what does that mean or like i know what this part means mean or like i know what this part means but i don't know what by inside but i don't know what by inside parentheses do they have an example i feel like i'm gonna by getting a wa by getting a wa getting a wrong answer together getting a wrong answer together because like okay i mean i guess we because like okay i mean i guess we could just try it out right like what could just try it out right like what does that mean damn it's like 91.1 is does that mean damn it's like 91.1 is that just zero that just zero that does make things a little bit that does make things a little bit trickier trickier if that's writing but uh okay well but yeah i don't really think they have damage to teach it is just a practice type thing what does the inside parenthesis mean that's really con oh i just don't know what that means there'll be no two consecutive operators i guess that makes sense if this is not a thing but is that a thing then okay so this isn't a thing but the other and you can imagine you have someone and you can imagine you have someone like someone like this maybe right but yeah i mean to be frank this is just going to be really annoying i don't think oh i guess this isn't still invalid try to remove it first but yeah it is probably just you know if you spend enough time on this you can get it but it's it is just annoying um because now now there is some complexion with just being a possible negative um so yeah okay first of all maybe we'll replace how does replace work or maybe it's just start like like that right so we remove all the we remove all the spaces because they we remove all the spaces because they don't do anything other than making us don't do anything other than making us confused confused so so yeah okay that it works so i make sure yeah okay that it works so i make sure because i'm really bad at python because i'm really bad at python apparently apparently so yeah okay so yeah okay then now we just pause one character at then now we just pause one character at a time and in this case now you know i've been grunting and kind of trying to figure out how to do it but i mean i know how to do it it's just this is one of those problems where it doesn't matter you know i mean you could do things slightly cleaner if you have experience but it is just going to be putting in the work so let's get started then uh let's just use a stack and then okay what do we do okay if c is equal to 2 then we push something up then we put the current number on the stack so let's just say um yeah let's just say um yeah let's just say how do i do this i don't even remember how do i do this i don't even remember this anymore but if it's fine yeah i this anymore but if it's fine yeah i just say current is zero if this is this just say current is zero if this is this then we just then we just push this on the stack um else if c is equal to do then we push it off the stack then and then either we and then either we but but let's write out the cases but even if we let's write out the cases but even if we don't write out the code yet um don't write out the code yet um either stack either stack is empty is empty and i guess we're done well well in this case then we can actually in this case then we can actually um yeah okay then we can now start let's actually uh let's just uh append this maybe this is less confusing um yeah while um yeah while length of well i mean okay i guess this length of well i mean okay i guess this should always be true now now while should always be true now now while the last element is not the last element is not to do what do we do well we pop it to do what do we do well we pop it like mary poppins like mary poppins um whoops this is the beginning of this like i mean that means that okay so we take so this is the last number and then the last operation is you go to the next pop is this right let me think about there's is this right let me think about there's so many cases to think about when i so many cases to think about when i think about this oh yeah so if the top think about this oh yeah so if the top is not right then it must be a number is not right then it must be a number but but can you have something that just um can you have something that just um can you have something that's just can you have something that's just um um like this is that a valid input i guess so okay okay if length of stack is greater than zero then that means that we have an operator and um um okay i guess we have to check um okay i guess we have to check now if stack now if stack the top of the stack is the top of the stack is equal to the thing then we just equal to the thing then we just um we're just able to um we're just able to pop this and then we pop this and then we push x back on push x back on so basically we reduce um this thing so basically we reduce um this thing so this is the case of so this is the case of in this case it's just something like in this case it's just something like this this and then we do this to five right and then we do this to five right that's basically what we're doing here and then we continue otherwise what happens otherwise what happens otherwise otherwise we have an operator we have an operator so we have op is to go to stack.pop i so we have op is to go to stack.pop i suspect i'm going to get a live wrong suspect i'm going to get a live wrong answer for this so so don't i mean you answer for this so so don't i mean you can learn from me making mistakes i can learn from me making mistakes i think that's gonna be the thing uh and i think that's gonna be the thing uh and i think it's a little bit late because i think it's a little bit late because i forgot to say it this time but i am forgot to say it this time but i am usually solving these lives so usually solving these lives so feel free to watch it you know in a feel free to watch it you know in a yeah faster speed or whatever i'm going yeah faster speed or whatever i'm going to see see how larry messes up to see see how larry messes up um yeah and why is he going to stack um yeah and why is he going to stack that pop and then now if um um [Music] [Music] yeah yeah i guess the hard part is that i guess the hard part is that you can you can you know i'm the hard part is that you have to do the the operations left to right right so and that's not quite the way that i'm doing it so it's a little bit awkward i think there's probably a quite more i think there's probably a quite more clever way to do it but i'm clever way to do it but i'm i'm like i'm just going to do something i'm like i'm just going to do something a little bit dumber um okay a little bit dumber um okay so okay so then now so okay so then now while stack of negative one is not equal while stack of negative one is not equal to do don't try this at home i would not recommend this just to be professional parsing code but yeah so then here um um to do is you go to this dot dot append stack that pop so then now we append stack that pop so then now we keep on adding these things and then now keep on adding these things and then now we look at from the bottom up we look at from the bottom up okay file to do length of to do is okay file to do length of to do is greater than zero greater than zero um um okay or if this is okay and then at the way and we pop off the top of the doo doo for the future and now for to do now we can go from right to left to do it okay so while this is at least three and it should be at least three so that should be okay dude pop so this is x x is the first number up is equal to the second operation um and then what do we do uh yeah and then we hmm uh we push this back on x plus y else um x minus y i think that's it i mean this isn't quite right but i've i mean this isn't quite right but i've but it is i'm just gonna try to see how but it is i'm just gonna try to see how it goes oh the next it goes oh the next i don't handle this case okay oh yeah that way and we um we should have length of you know would assert that oh and also you might have oh and also you might have multiple numbers this is so annoying multiple numbers this is so annoying so annoying because you got like for so annoying because you got like for some something like this and i don't handle this either because and i don't handle this either because that's not an operator that's not an operator but okay let's print out the stack at least this should work though i mean it may not work correctly but it should do something oh i i don't append any other things oh i i don't append any other things that's right otherwise we appen that's right otherwise we appen see though see though again this is working process so again this is working process so uh my apologies yeah oh i have to convert them to ends but that's okay so this looks okay this does not look okay because of this uh negative one and but anyway okay so let's just say and else else if c is in is numeric then we have if c is in is numeric then we have panned in version of it otherwise we panned in version of it otherwise we just this is an operator and we just just this is an operator and we just append c still not super good because of that negative thing but i don't know this is for the next one so i don't know this is for the next one so okay okay wait wait is that right is that right oh well because we oh well because we we have to do this thing at the right we have to do this thing at the right end again okay let's just have a helper function this hmm okay and then now because of that we can [Music] we can evaluate this but from left to right so that means that we actually want this to go backwards because in in here the way that we did is we actually we we kind of we we kind of look at it backwards i don't know this look at it backwards i don't know this is way messy i'm not going to lie evaluate so now i don't have a spell anymore so now i don't have a spell anymore because i feel like i saw it like five because i feel like i saw it like five times kind of thing times kind of thing okay i think now we're good except for this unit well and and this number we have to pause as well but uh okay but that looks you know in theory this looks good so so this is hopeful for me um and of course if you you know you should consider the tdd type thing and you would have uh more test cases that kind of address these things but of course uh you know this thing fails and then tells me like one time hours right so um but conceptually conceptually uh you know we will kind of see what what pass and what fails and i'll be okay but yeah um i think the first thing we need to do um are these this actually maybe could be right four of these nope i don't get this one right so this is six and this is four so why is this four it may be that i just don't have that's not right right oh how do i return this i i should this okay it's just that i returned the wrong okay it's just that i returned the wrong thing because i i thing because i i changed the code without thinking about changed the code without thinking about it okay so this is mostly right again we it okay so this is mostly right again we don't we know that this is wrong this is don't we know that this is wrong this is expected wrong in this is one expected expected wrong in this is one expected way because way because um um because we didn't implement multi digit because we didn't implement multi digit things here we can kind of um things here we can kind of um yeah how do we want to do it yeah how do we want to do it yikes so okay so it can be a leading zero let's think about all the possibilities that that has to do with here right so the cur the current parsing is think is this thing and that means that we don't okay so if it's numeric then we times it by 10 and then we add end of and then for and then for for everything else and then what can follow this right it can follow it as an operator so here we we append uh current and then set current back to zero and then uh add the operator that's following and then the other thing that could follow it is this thing so let's also put that there yeah because the thing that is before yeah because the thing that is before this has the close friends has to be a this has the close friends has to be a number right so we can do that um let's number right so we can do that um let's see if that gives us see if that gives us the right answer for this nope i mean i think we're in the right direction but i might be missing hmm i don't know what i don't know what this should be but i guess we set it to this should be but i guess we set it to zero anyway but this is an awkward part of the stack so it's a little bit weird let's put out the stack is ready to get it as well where's my other print statement right okay so empty and then this and then okay so empty and then this and then this and then we get this all right let's get c so we could see okay we process one we just processed okay we process one we just processed correctly if this files it correctly correctly if this files it correctly this it keeps going this it keeps going and then oh and then it's the end of the string okay so down here if current um how do i huh i just have a flag ongoing as you go to force here it sets ongoing as you go to true force and force force and force and then now and then now if it's ongoing then stack data pen if it's ongoing then stack data pen current current and then hopefully this should be good and then hopefully this should be good for the last dump that's basically why for the last dump that's basically why we're doing it we're doing it nope uh five one i mean nope uh five one i mean i mean this d should be backwards so i mean this d should be backwards so that should be okay that's six okay five that should be okay that's six okay five okay now i think we're this there's an extra zero here so this is six and this is four but why oh oh i guess we should only yeah we should only do this if we haven't already passed it because i don't even add one there but but we don't handle we don't handle um um i mean i don't know if this is good but i mean i don't know if this is good but it is a better than what we had before it is a better than what we had before let's actually add a couple more let's actually add a couple more of multiple digit ones uh this is just me banging on the keyboard i don't but if this is right i'm i'll be really but if this is right i'm i'll be really happy okay so this is right so i'm happy okay so this is right so i'm actually very happy right now actually very happy right now um um and if and i don't really have a good and if and i don't really have a good explanation if you have trouble catching explanation if you have trouble catching uh following along not because i'm uh following along not because i'm pretending i'm arrogant and smart or pretending i'm arrogant and smart or whatever but because this is the whatever but because this is the opposite this is terrible this is me opposite this is terrible this is me just literally thinking about and having just literally thinking about and having an if statement for every possible case an if statement for every possible case so this is terrible uh i don't think so this is terrible uh i don't think there's anything underlying behind it there's anything underlying behind it it's just about like i said earlier it's just about like i said earlier right it's about grinding and kind of right it's about grinding and kind of pushing through and getting it and pushing through and getting it and that's it i'm still not done i okay so i that's it i'm still not done i okay so i have all this but i don't have to one have all this but i don't have to one that is um let's just say that is um let's just say negative one plus five right we don't negative one plus five right we don't have that we don't have five plus have that we don't have five plus um negative one um negative one plus plus uh uh ten but what i was thinking was uh uh ten but what i was thinking was actually we should also handle some actually we should also handle some zeros just in case i have some weird zeros just in case i have some weird zero logic um zero logic um yeah yeah okay i suspect that this should give me okay i suspect that this should give me an exception about passing one time an exception about passing one time things yep things yep because because right now we count this as an operator right now we count this as an operator but but hmm okay i think we can actually hmm okay i think we can actually this one can only be part of they're saying that it has to be in the beginning because you cannot add negative thingies right let me let me remove this for now just to make sure that everything oh i guess this one as well just make sure that everything still pauses i want to make sure to check the zero cases first as well okay so that looks good so far and then the other thing i wanted to make sure was that like something like this does that count okay so so this is a valid input but that's why that's what i was checking because you cannot do something like but this is a valid input right because but this is a valid input right because now it should give me an invalid now it should give me an invalid expression okay expression okay okay okay and then now these should be other ones and then now these should be other ones that are good um that are good um i think this is also good the negative i think this is also good the negative one plus five one plus five um okay yeah so in that case that means um okay yeah so in that case that means that the negative appearance will only that the negative appearance will only be in the first item so we can actually be in the first item so we can actually hard code this maybe we'll see if this hard code this maybe we'll see if this is right but um yeah if length of total is right but um yeah if length of total is is greater than zero and the first element greater than zero and the first element now that's actually the last element now that's actually the last element because we're doing it backwards is because we're doing it backwards is equal to negative equal to negative then we then we we pop we pop we pop the negative and then we pop the pre the top number and then we just append okay let's give it a spin okay so this looks good i think but if you ask me about my confidence would i stick anything in it i wouldn't even i wouldn't put my money in it i wouldn't even put you know a sandwich on it uh so that but but that said i am lazy though so let's give it a submit and see what what because there are billion test edge cases so i suspect that something will fail but of course after i said all that it did get accepted on the first try so i'm really happy uh okay so the the running time is going to be linear because well i i i didn't mention this but n is 10 3 times 10 to the fifth so if it's not linear it's going to be too slow anyway um and i know that n log n would be fast enough for 3 times 10 to the fifth but but you would have to have a weird operate um you have to do something weird to get unlocked in this case um but in any case we basically for each character we only push and pop off the stack once and then we also push and pop off this to-do thing uh once right so we push and pop off here once and we push and pop off the stacked ones so in that case everything is going to get pushed and popped once so this is constant per character or per per chunk per token um so yeah so this is human linear time in terms of space of course we use linear space we have two stacks and it can get pretty full like a full house party kind of thing so yeah linear time linear space that's all i have it's a little bit long um and like i said i just did everything by if statements i um my my strategy was to just break it down case by case and kind of try to make progress slowly but incrementally and hopefully this is good for you anyway uh stay good stay healthy to good mental health i'll see you later uh and yeah | 2024-03-22 10:57:52 | 224 | 224. Basic Calculator - Day 11/30 Leetcode September Challenge |
|
GDYaGaomLqE | you are initially standing at index zero in one move you can jump at most k steps in one move you can jump at most k steps in one movie jump to those k steps in one movie jump to those k steps without going outside the boundaries without going outside the boundaries obviously and the index i to any index obviously and the index i to any index in the range of i plus 1 minimum of in the range of i plus 1 minimum of n minus 1 till i plus k so you want to n minus 1 till i plus k so you want to reach the last index of the array reach the last index of the array which is n minus 1 so your score is the which is n minus 1 so your score is the sum of all numbers of j for each index j sum of all numbers of j for each index j you visited in the array you visited in the array so we will try to go from good force of so we will try to go from good force of course course to the optimal to the optimal [Music] [Music] so for each index if we want to consider so for each index if we want to consider if we visit this index then we can go if we visit this index then we can go either one either one either one job or two jump either one job or two jump for getting the optimum answer here they for getting the optimum answer here they have done one jump then it is one minus have done one jump then it is one minus one zero then from here they have taken one zero then from here they have taken two jumps then the total sum will be two jumps then the total sum will be total score will be four and from here total score will be four and from here they have taken two jumps the total they have taken two jumps the total score will be seven so four plus three score will be seven so four plus three seven so seven is the optimal answer seven so seven is the optimal answer that you can get maximum max mean so we that you can get maximum max mean so we have to maximize it have to maximize it so we have for each index for so we have for each index for considering in each index i can take k considering in each index i can take k steps i can take from plus one plus two steps i can take from plus one plus two from the for this index i can take plus from the for this index i can take plus one plus two so i can i have many one plus two so i can i have many possibilities so i have choices possibilities so i have choices obviously if we have any choices then we obviously if we have any choices then we can go for a recursive problem because can go for a recursive problem because the solution the solution so i will write the so i will write the recursive function passing the recursive function passing the parameters parameters nums nums k k and 0 and 0 0 is the index i so now i will [Music] [Music] so so if i has reached my if i has reached my end of the edit number size end of the edit number size [Music] [Music] then then i can say return i can say return 0 0 or else i should i will declare a value or else i should i will declare a value which is which is uh minimum in women uh minimum in women since i have to get the maximum score i since i have to get the maximum score i will say it has messed up will say it has messed up my score and i can for each and every index i can go at most k steps so i will have a variable steps that starts from 1 still steps less than or equal to k steps plus [Music] next step i plus steps if my next if my next step is greater than or if my next step is greater than or equal to my number then i can just break this income this would be a more case where i can handle or else i can find the current score considering uh i'm taking this skip steps out so i can uh include this index the included indexes numbers of steps plus solve of nums [Music] k and next step and i will update my max score raspberry so max 4 is nothing but max of max score comma that's good so i'm finally i will return max code so this will be my recursive approach i uh uh max of mexico max of mexico [Music] [Music] uh oh this is numb some steps it's numbs up next [Music] overflow um next step if my next step is like the steps now next time is greater than my number size then i am making the slope i'm calculating the current score numbers of my next step last solve of numbers k and next step and i'm going to do that index and i will be taking the all the k steps if i am going to reach mems dot size minus one then i will just computer that i don't want to take computer that i don't want to take subscribe i want to reach the end of the subscribe i want to reach the end of the exo exo here i have two for each for every here i have two for each for every result i'm going to include my first result i'm going to include my first element uh because as you can see that element uh because as you can see that when i call this recursive function it when i call this recursive function it goes to this call and then i will goes to this call and then i will declare a max variable then i will declare a max variable then i will not include this first element and not include this first element and rather i will implode the rather i will implode the next element the steps count as 1 so 0 next element the steps count as 1 so 0 plus 1 so i plus 1 which is 0 plus 1 1 plus 1 so i plus 1 which is 0 plus 1 1 and i'm going to add the num sum and i'm going to add the num sum 1 only i will not be adding numbers of 1 only i will not be adding numbers of zero itself so uh what i can say is zero itself so uh what i can say is numbers of zero can be added here numbers of zero can be added here always i'm going to add so the score which is at the first index and then i'm going to call this recursive function so hope this makes clear here we are we are seeing every possible cases but this will not get accepted as the constraints constraints is uh in terms of length is important and cased in perfect now it grows exponentially the time composition will be exponential in nature so we can try to memorize it for memoization we want to see what are the changing parameters the changing parameters is only the yield i i is the ie varies 0 to n so i will declare on the array current dp of size now size unable to initialize with minus one in amazon dp and i will pass dp here as in amazon dp and i will pass dp here as well well [Music] if my dp of i is not equal to minus 1 then i will just [Music] here here this recursive call will go for order of n so the time complexity [Music] time complexity k steps so r of n into k as you can see k steps so r of n into k as you can see the n grows still at in power and k is the n grows still at in power and k is also 10 power okay so it will be 10 also 10 power okay so it will be 10 power 10 so 10 power 10 is a n square power 10 so 10 power 10 is a n square solution so this will give our tle obviously the space complexity is our rock and we are using an extra uh we are using an extra space of automation and then auxiliary stack space two we are going to use text so the of our recursive solution so we so we get time limit excited for this so so we get time limit excited for this so how can we optimize this further so let how can we optimize this further so let us analyze what we are doing us analyze what we are doing in reverse matter let us take this in reverse matter let us take this example one minus one minus two then example one minus one minus two then four minus four minus seven and three seven and three so obviously so obviously from back we will be taking this three from back we will be taking this three then the three steps then the three steps now then now then three steps we can we have taken three steps we can we have taken and uh in minus seven what is the best and uh in minus seven what is the best steps we can take minus seven plus three steps we can take minus seven plus three which is minus four which is minus four then from minus four uh then from minus four uh from this four what are the three step from this four what are the three step what are the next step i can take either what are the next step i can take either this minus seven or this three this minus seven or this three so i will take four minus four zero or i so i will take four minus four zero or i will be taking four plus three seven so will be taking four plus three seven so i will be taking four plus three seven next i will be taking a uh minus two either i can take this seven or i can take this minus four so which is best i will be taking minus two plus minus four which is minus six minus six or is best or seven minus two five five is best so i will be taking five next uh minus one i will be taking either five minus one which is four or seven minus one which is six i will taking seven minus one which is six so i will be taking some minus one which is six i can move only k steps which is two steps so uh what i'm doing can i you can observe uh that i hope it makes sense then in one i will be taking either so one plus six so one plus six which is seven or one plus five which is which is seven or one plus five which is six so i will be taking the six so i will be taking the maximum which is one plus maximum which is one plus six which is seven so i'm six which is seven so i'm i'm filling this dp array in the reverse i'm filling this dp array in the reverse fashion fashion uh so by uh so by for each uh for each uh iteration i go i will be going i for iteration i go i will be going i for each i index i will be going to each i index i will be going to uh every uh every every k steps forward and i will be every k steps forward and i will be checking which is best checking which is best so so obviously for each and every step i am obviously for each and every step i am getting the maximum element of that getting the maximum element of that i will do a dry run once again so that i will do a dry run once again so that it will be more clear for you it will be more clear for you i will be coming from reverse and taking i will be coming from reverse and taking this current and i will be taking this this current and i will be taking this current elementary current elementary so i have pulled it so i have pulled it so in minus seven so in minus seven uh uh from minus seven what is the maximum from minus seven what is the maximum element on its right element on its right it is obviously three so i will be it is obviously three so i will be taking y minus seven plus three which is taking y minus seven plus three which is minus four minus four then uh from this current index what is then uh from this current index what is the the greatest element of greatest element of these two elements these two elements it is obviously three four plus three it is obviously three four plus three seven seven uh i should not see all the uh i should not see all the elements that are in right yeah we are elements that are in right yeah we are having only k steps so we have to having only k steps so we have to take care of those k distance also so 4 take care of those k distance also so 4 plus 3 7 plus 3 7 in this minus 2 what will be the best in this minus 2 what will be the best option that i am going to choose i option that i am going to choose i cannot choose i i cannot have a choice cannot choose i i cannot have a choice of choosing every the elements in the of choosing every the elements in the right i'll be having a choice for only 7 right i'll be having a choice for only 7 and minus 4. and minus 4. so so in minus 2 what will be the best in minus 2 what will be the best possible element that i can choose is possible element that i can choose is obviously this seven seven minus two obviously this seven seven minus two which is five which is five so i will say it as five so i will say it as five in in this index minor in this element minus this index minor in this element minus one water in this course with the score one water in this course with the score or what is the best element that i will or what is the best element that i will be going to choose i will be choosing be going to choose i will be choosing 7 so 7 minus 1 which is 6 7 so 7 minus 1 which is 6 so i am just want a greater element so i am just want a greater element always i just want a greater element if always i just want a greater element if i i if i'm if i'm if i have some way to if i have some way to have a greater element seven five have a greater element seven five uh such a way or three minus four such a uh such a way or three minus four such a way what you can understand in this i am way what you can understand in this i am having a monotonically decreasing decreasing elements of k elements elements monotonically decreasing k elements if for each particular for each index if i can maintain a monotonically decreasing k element then i can say uh for to calculate the current index i consider the dp of i is the current index to calculate the current index db of i i will say uh the some data structure uh considered for the monotonically decreasing k elements i am having some data structure ds data structure dot friend top but the element which is a different plus my number of i so this is uh this makes sense right it makes sense dbfi is nothing but data structure that uh databases of print element which is going to give me the greatest element of k distance and then i will obviously and then i will obviously uh obviously insert this dpf i uh obviously insert this dpf i do that monodragonically decreasing do that monodragonically decreasing their k elements so how their k elements so how so to maintain uh monotonically so to maintain uh monotonically decreasing k elements we'll be using a decreasing k elements we'll be using a dq which can be inserted or a friend dq which can be inserted or a friend insert front and back insert front and back so so by this i can maintain the to maintain by this i can maintain the to maintain to maintain the to maintain the order order so that i can reduce this k loop so that i can reduce this k loop instead of uh going for a n square instead of uh going for a n square solution we can reduce the scale loop solution we can reduce the scale loop and we can do it in linear method so for and we can do it in linear method so for this particular index one i want a this particular index one i want a greater element of 6 and 5 if i have a greater element of 6 and 5 if i have a data structure if i have a dq where i data structure if i have a dq where i have maintaining the 6 and 5 have maintaining the 6 and 5 i can take 1 plus 6 which is 7 sound i can take 1 plus 6 which is 7 sound will be the answer will be the answer and i will move consider in the data and i will move consider in the data structure dq i have structure dq i have six and five now i have calculated the six and five now i have calculated the dp of is dp of is db of is one plus six which is seven so db of is one plus six which is seven so now i have to insert seven now i have to insert seven here how we can insert i am going to here how we can insert i am going to insert insert uh seven uh if uh insert seven if this uh elements are smaller then i will be inserting the seven at the back so i will be popping this five and then i will be popping the six and then i will be inserting the seven domain eq right this is what i'm going to do now we will write the code so that it will be more now we will try to import this approach first of all we are going to have we i will have a db of i will have a db of dp of size yen itself of n minus 1 dp of n minus 1 is nothing but numbers of n minus 1 then from last before and x 4 and i equal to n minus 2 i greater than or equal to zero i minus i will be having a dq which is the data i will be having a dq which is the data structure eq structure eq i will name it as dq itself i will name it as dq itself so this is going to so this is going to maintain monotonically decreasing elements this is going to maintain my monological decreasing elements so from the last before index i'm going to traverse it and i'm going to calculate dp of i is nothing but dq uh dq dot friend plus my numbers of i correct yeah it makes sense so then i will be pushing this dpf i into my dq if my dq is not empty if my dq is not empty if my dq is not empty and if my dq dot dq dot bank is less than my pop the elements i can obviously pop pop the elements i can obviously pop those elements yeah i don't want those those elements yeah i don't want those elements they are smaller smaller than elements they are smaller smaller than the elements which are in the back so i the elements which are in the back so i will uh just will uh just pop those in sleepy. pop those in sleepy. dq dot com back dq dot com back after popping back i have to insert this after popping back i have to insert this dpr file insert this current element dpr file insert this current element into my pack so dx do not push into my pack so dx do not push [Music] [Music] back of back of dp dp [Music] [Music] and finally what we are going to and finally what we are going to return we are going to return db of zero return we are going to return db of zero as you can see in my dpf 0 the value is as you can see in my dpf 0 the value is stored 7 so this is what we are going to stored 7 so this is what we are going to do but do but is that all the cases are handled no is that all the cases are handled no uh for each and every index i we are uh for each and every index i we are going to going to calculate the next care we are going to calculate the next care we are going to maintain the next k elements but how we maintain the next k elements but how we can see that this can see that this current index if my current index current index if my current index current value is the current value is exceeding that k distance if this alignment is uh calculated and if this element if the queue has this element in the friend then this 6 scan can't be calculated with minus 4 because it is k distance more than that so we have to keep some index to that data structure so that we can maintain them we can eliminate those uh those elements so how we can do this we elements into our elements into our dq we will insert the index into rdq uh so we will insert the index dq dot push back of n minus one push back of n minus one so instead of dq dot friend it will be and we have to check and we have to check we have to check we have to check if my dq if my dq is my dq dot friend minus the current index i is greater than k then i will be deleting that element i don't want that so i will deleting the dq dot print element index so hope that makes clear we are eliminating this uh k distance elements that's it we are nothing uh doing more complicated we'll use the example test cases and run the code [Music] we get uh wrong answer let us see sorry sorry sorry here they use my dq dot friend sorry here they use my dq dot friend minus i is greater than yeah okay i am minus i is greater than yeah okay i am going to say that i am eliminating that going to say that i am eliminating that element so dq element so dq friend so i should do the dq dot pop friend so i should do the dq dot pop file so i have eliminated that index file so i have eliminated that index element element i have admitted [Music] [Music] of i and then while the of i and then while the dq is not empty dq is not empty so so this is wrongly checked if my if there is at least one element size then install on black is less than my dp of i then i will popping back and then i will be pushing back next [Music] [Music] [Music] sorry before we answer the dpr friendly sorry before we answer the dpr friendly via friend will giving me the value but via friend will giving me the value but this is not the numbers of dq dot print this is not the numbers of dq dot print it is dp of it is dp of dq dot friend right now dq dot friend right now i think it will be the current answer we i think it will be the current answer we have made some silly mistake have made some silly mistake um um it is dpp of it is dpp of [Music] it got accepted so here the time it got accepted so here the time complexity will be order of n complexity will be order of n and this y is not going to cost me r of and this y is not going to cost me r of k so it will be this k so it will be this it is uh just in our linear solution it it is uh just in our linear solution it is so hope you like this video so let us is so hope you like this video so let us see tomorrow's video see tomorrow's video tomorrow's great coach daily challenge | 2024-03-20 14:31:29 | 1,696 | 1696. Jump Game VI | LeetCode Daily Challenge |
|
v-MK7BjGxwM | hey what's up guys this is chung here so today uh lead called number 778 so today uh lead called number 778 swim in rising water okay so you're swim in rising water okay so you're you're given like an unbiased grade you're given like an unbiased grade right so each each element right so each each element or each position represents or each position represents the elevation of that point and now the the elevation of that point and now the rain water starts rain water starts to fall now the rain starts to fall to fall now the rain starts to fall and that's why i know the water will and that's why i know the water will will keep will keep uh keep rising right so at time uh keep rising right so at time t i time t the depths of the water t i time t the depths of the water everywhere is t okay and you can swim everywhere is t okay and you can swim from a from a square to another neighbors square to another neighbors neighbor four adjacent squares if and neighbor four adjacent squares if and only if the elevation of the waters only if the elevation of the waters sorry if if both the division of the sorry if if both the division of the squares squares individually are at most at most t right and then you can swim in different in infinite distance in zero time and of course you must stay within the boundaries of the grid so our task is to find out the minimum time right so that we can swim from the top left corner to the bottom right corner so yeah so for example we have a like so yeah so for example we have a like two by two two by two uh grid here you know so each of the cell has it has their own their own height right so the answer is three because you know so see at that beginning the zero the top left corner has like zero height which means we can swim uh here but we cannot swim to any neighbors right because we have two zero one three right so in order for us to swim from zero to two we need to wait for for two for time for two times right from zero to one we need to wait for one times right and then either from two to three work from one to three we also need to wait some time right for example from two to three we need to wait for another time here we need to wait for another two time that's why the answer is three because we need at least three time to swim from the source to start to the end right and yeah so that's it right i mean the uh the the range is at fif uh is 50 by 50. right so obviously this one is a con it's a kind of like the uh a graph problem or like a search problem right uh so i was at the beginning you know every time we see this kind of uh what is that uh the list where the minimum values we're looking for in the in the graph problem uh i actually actually at the beginning i was thinking about can we use a bfs search right but the bfs search um it seems like this this graph this graph problem is not like a bfs bfs problem because it has like as you guys can see it has a weight right it has a weight on each on each ad so from here to here it's not it's not free we have to wait some time so that's why you know this one is not like traditional bfs and then we can we can definitely use uh uh dextra right to solve this problem and yeah and we'll we'll be uh doing the doctor today and and there's also like another solution for this one it's a binary search right because every so binary search can also help us find the either the least or the max values and so for binary search you know the key point for binary search that we have to find the trend basically we have there there's like uh monotonic trend right while the value is either increasing or or decreasing so for this problem you know basically when the time is increasing along the way right there will be a along the way right there will be a there will be a time there will be a time right we can reach from lap from right we can reach from lap from the start to the end right because you the start to the end right because you know know because we know by by the time the water because we know by by the time the water had uh had uh the water is deep enough to cover the water is deep enough to cover all the other square that obviously we all the other square that obviously we can swim can swim we can swim from from one place from we can swim from from one place from from the top left corner from the top left corner to the bottom right corner right so to the bottom right corner right so then we can simply search we can do a then we can simply search we can do a binary search binary search of of the t here right binary search the t here so and we have hyper functions basically given like sorry that's my that's my theory so given like a fixed t here we know in this grid we have some we have some grids uh so we have some squares that are currently connected to each other which means we can swim across them right and then we can just have a helper function with a given t and can we swim from the top left corner to the bottom right so that's that's right so that's that's that's that one actually there's a third that's that one actually there's a third one there's a third solution for this one there's a third solution for this which is the uh which which is the uh which is the uh which which is the uh the union find um so how does this union find works actually it's a similar i think it's a similar idea as the binary search basically you know we have kind of a grid here let's say we have five five okay uh maybe i should just write four okay uh maybe i should just write four by four by four okay anyway i'm almost done here and each basically each cell has its own height right so what is the unifying can how the unifying union fund can help us basically if you know the uh there's a algorithm called uh minimum spin spinning tree right so basically here we are we're actually building like a minimum spinning tree uh to connect uh the source by connecting some of the path by some by connecting some of the path by some by connecting some of the by connecting some of the after the square right after the square right and we need to find the the we need to and we need to find the the we need to find the smallest find the smallest smallest time so what is the smallest smallest time so what is the smallest time right so the smallest time is the time right so the smallest time is the time that you know time that you know uh if we basically if we sort if we sort uh if we basically if we sort if we sort all this kind of all this kind of uh element from smallest to the biggest uh element from smallest to the biggest and if we process them one by one and if we process them one by one right from the smallest to the biggest right from the smallest to the biggest and by the time and by the time we process you know let's say we have we process you know let's say we have some uh this is zero let's say this is some uh this is zero let's say this is like um five like um five or something like like that right and or something like like that right and then right right in the middle let's see then right right in the middle let's see there there's like this one there there's like this one let's see the value is seven let's see the value is seven so basically what so this what how this so basically what so this what how this algorithm works is that you know we uh algorithm works is that you know we uh we're using a union find and then we we're using a union find and then we sort each each square sort each each square by by the height from the smallest to by by the height from the smallest to the biggest the biggest and every time when we have like uh the and every time when we have like uh the current current the current uh square we try to do a the current uh square we try to do a union find union find with all its neighbors okay and after that we can check if the zero if the the source and target has has the same root if if that's the case and then we know this value is the minimum time we're looking for right so this is like how how the minimum spinning tree right basically by the time by the time we have uh connected zero and five then the the the minimum spinning tree is it's it's completed and since we are and since we are like processing from this from the smallest from smallest uh time here then we are sure you know the current time or the current cut this current value here is the minimum time we need to build this right um right um yeah because yeah i think that's yeah because yeah i think that's that's the basic idea here right so and that's the basic idea here right so and of course you know when we try to of course you know when we try to uh do a union with all the four uh do a union with all the four neighbors we simply cannot neighbors we simply cannot union all the four neighbors because we union all the four neighbors because we have to have like you know have to have like you know uh a visit a scene set uh a visit a scene set a scene set here uh where when we do the a scene set here uh where when we do the union find union find for with all the neighbors we only only for with all the neighbors we only only a union a union do the union with the with a with a do the union with the with a with a square we have already the same view square we have already the same view before right that's i think it's obvious because you know let's say this one is 7 right so since we're processing from the smallest to the biggest let's say the neighbors has like three uh four and six this one is let's say it's ten okay so by the time by the time we're processing this this this cell here square here obviously all the others these three neighbors right three six four have already been uh visited before same before that's that's why we can uh do the union with them right but with 10 since 10 has not been seen before we cannot do it do a union is here because obviously you know if we do a union with 10 it means that okay actually because 10 has like a bigger value here you know if if if union 10 if 10 has uh if if 10 has uh if if 10 has like a connection with five here right like a connection with five here right it's the is the end here and then then it's the is the end here and then then we're getting the we're getting the wrong the wrong value here it shouldn't wrong the wrong value here it shouldn't be seven it should be changed that right that's why you know uh obviously you know we only want to uh know the the nature of the union fine is like we only union with the value we have already a union b before in this case right yeah so yeah basically if we were if we were union of a number that we have not been seen before it means that you know the time will be increasing right which it will not be the same in this case uh cool yeah i think that's all the explanation for all three uh i think solutions you know i think we can start coding then right um so where where should we start um let me think uh how about binary search i think binary search is the most uh straightforward one uh the binary search right so we have uh we have n going to be the length of grade right now we have left equal to zero and the right equals to n times two right so the upper bound is this one because because it says all the values is a permutation from n to n squared minus one that's why the right boundary is this one right and then the binary search right at the template uh so wow this one is smaller than r right we have middle l plus m1 right minus elapsed divided by two and then [Music] and then we're going to have like a hover function so i'm going to cut can from with the middle level water right from with the middle level water right if it can if it can see okay so now we're looking we're see okay so now we're looking we're looking for the smallest the minimum looking for the smallest the minimum value right value right that's why you know we have to do uh r that's why you know we have to do uh r is going to be the middle is going to be the middle and then the left house will be the and then the left house will be the uh left will be middle plot plus one uh left will be middle plot plus one right so this is a kind of template you right so this is a kind of template you know because you know know because you know uh see if we're looking for the minimum uh see if we're looking for the minimum you know we will you know we will be doing this middle equals to r to the be doing this middle equals to r to the right right and the left equals to this one if we're and the left equals to this one if we're doing the maximum doing the maximum right if you are doing the maximum and basically this is as if like this you can try to picture a picture of this scenario here if we're if we're looking for the minimum at the maximum and if this can reach so this harbor functions always return to it which means that you know now they will always return to it if this harbor functions return true it means that because the current value i mean works right so means it might be the answer so for the minimum for uh to look for the minimum values let's say with the middle is right here right that's why it means that you know the middle could be the answer but since we're looking for the minimum but since we're looking for the minimum one right so which means we one right so which means we we need to look for this side we need to look for this side right that's why you know we set this right that's why you know we set this right into the middle right so similarly if we're looking for the maximum for the maximum all right so again right for the maximum if this one a half function uh return true it means that this one could be a one of the values right but for this one since we're looking for the maximum that's why we need to look uh to the right side right also including this one right that's why you know uh when we're looking for the maximum when this when this thing happens we have to do a left equals to middle right and then this one is going to be r dot middle minus one because because for the maximum we're right so that's that's how you remember right so that's that's how you remember this template and oh and this template and oh and when you do a left equals to middle you when you do a left equals to middle you have to do this one password right have to do this one password right i think i've already talked about that i think i've already talked about that several times several times okay so that's a little bit about the body of the binary search okay template and then uh what else and then we just return the left in the end right so now let's implement that hyper functions can reach right range of middle so this hardware functions here is simply like like a dfs search where like you can use stack or anything you prefer to start search from the beginning from top left corner and see if we can reach the end right with this current middle basically with some constraints uh so first you know i'm going to have like this uh do a quick check if this thing if this starting point uh is greater than the middle right then we simply return false it means that we can we'll never be able to move to anywhere from the top left corner that's why we need to return false here otherwise have a stack equals to this and then scene dot add and then scene dot add right and then zero zero and right and then zero zero and then directions tedious coding here and then do a while loop here you know current i current j equals to stack that current i current j equals to stack that pop pop right so here i'm using a stack to do right so here i'm using a stack to do the dfi search the dfi search so if the ci equals to n minus 1 so if the ci equals to n minus 1 this cj equals to n minus 1 then we this cj equals to n minus 1 then we return true right we know we find it return true right we know we find it to find the path it's it can reach to find the path it's it can reach basically basically or we do it uh or we do it uh search from four directions okay so new search from four directions okay so new i is going to be ci plus d0 i is going to be ci plus d0 right and then new j goes to c right and then new j goes to c c j plus d one and then if c j plus d one and then if this thing is in the range of n this thing is in the range of n same thing uh for the same thing uh for the new j in the n and new i new j in the n and new i new j not in scene okay new j not in scene okay and the great right so the last one is and the great right so the last one is it's it's the constraints we bring we bring in the constraints we bring we bring in with the middle with the current level with the middle with the current level of the water right of the water right basically neighbor can only be visited basically neighbor can only be visited if if the water if the water is higher than the water if the water is higher than the than the height the than the height then activation of this square right then activation of this square right than the middle okay then we do a stack than the middle okay then we do a stack dot append a new i dot append a new i new j right oh we need another new j right oh we need another pair of parentheses here and then c pair of parentheses here and then c dot add ui dot new j dot add ui dot new j okay and then in the end return false okay and then in the end return false right uh right uh yeah that's it so let's run the code yeah that's it so let's run the code here here okay accept it nice all right cool so it okay accept it nice all right cool so it works works um yeah so that's the that's a binary um yeah so that's the that's a binary search right i mean search right i mean time complexity so obviously here we time complexity so obviously here we have have uh the range is like like this so we uh the range is like like this so we have a have a log in log n square right so that's the log in log n square right so that's the uh the binary search uh the binary search and for the helper functions here it's and for the helper functions here it's just uh just uh just while loop so the worst case just while loop so the worst case scenarios we have to search the entire scenarios we have to search the entire graph right that's why we have an n graph right that's why we have an n square log n square right so that's the binary search time complexity and so next uh let me think yeah dark stroke right so let's do dextro i think we have we have already uh i think we have we have already uh basically analyze a bit about dextro basically analyze a bit about dextro basically the actual basically the actual the way the reason we can use dioxide is the way the reason we can use dioxide is because from one node to another because from one node to another so from one square to another there's a so from one square to another there's a cost in this in this case it's a time we cost in this in this case it's a time we have the weight have the weight right in case in case this one right in case in case this one is is it's uh it's lower than this one is is it's uh it's lower than this one right i mean this is 10 let's say this right i mean this is 10 let's say this is five is five if you want to travel you want to swing if you want to travel you want to swing from this one to here we have to wait from this one to here we have to wait for five for five times right but if this one is 10 10 times right but if this one is 10 10 5 then this one is zero right then it's 5 then this one is zero right then it's free okay cool so now we have a graph with the uh with the weighted edge right and we want to find the minimum cost from top left corner to the bottom right corner right so that's a perfect candidate for the dextro okay cool so for a digestion uh let me think uh we need uh distance right i mean i think it's not decent it's like so we need a basically a two dimensional so we need a basically a two dimensional array array to help us to store to help us to store the minimum cost the minimum cost right the minimum cost the minimum cost right from between each between from between each between any two nodes here okay any two nodes here okay and at the beginning we have a cost at and at the beginning we have a cost at zero zero zero zero right so what is this one so so keep in right so what is this one so so keep in mind this one is it's not zero mind this one is it's not zero it's what it's a grid of zero zero it's what it's a grid of zero zero right remember so the the first one right remember so the the first one does not necessarily to be zero out uh does not necessarily to be zero out uh every time if the zero zero let's say if every time if the zero zero let's say if there's ten here there's ten here ten uh two ten uh two five and one right so for example this five and one right so for example this one here so what is the answer for this it's ten right because we're standing at the top left corners but we cannot move anywhere until until the time ten is equal to 10 right and by the time it is equal to 10 we can simply move to anywhere right including this one that's why at that's why the cost zero zero is the is the value of the grid zero zero okay and then the prior queue right for the darkest row and we have the grid of zero dot zero and then the the the coordinates right along along with it now we also need the scene set right and then the wow well priority queue thing right then the dot ci current right and then we do us scene dot at uh ci dot cj right so we only add add to the scene after we pop out pop-up from the product queue because we there could be multiple items for the same for the same uh coordinates in this particular and we only add it whenever it's his turn to be processed which which means it's he which means he has this one has the smallest cost right for the darkest row and then for d oh and we need to define this but luckily we can copy and paste we don't have to type in this and i guess we also need this n here okay so for d uh actually i'm going to copy this this part you know because they're pretty much the same so we have a d here and this part is that's uh this is this one and we're going to remove this part right so now here inside so part of the dark stroke problem of the template we have a new cost the new class will be with the grade from the new place new i minus new this new one subtract the uh the grid of this one dot c c j right so it seems like this one but you know there's this one is not correct first first this one this one could be smaller than this one right so the new cost could be negative that's why first thing we need to add is the maximum between zero right so in this case we are sure that uh we'll always get a zero for negative values and there's a second there's a second thing second issue here because uh oh for example right so we have i have already give you the example here so let's say we have 10 we have one and then let's say we have five two and five okay so for example in this case right if you're only trying to do the new cost with this formula okay so at the beginning we have 10 the cost is 10 right so from 10 to 1 this is zero right and we're fine but from one to five we have five here we have four right so are we saying that you know from here to here you know if we if we follow this one you know the cost from from here to here will be four will be it's instead of instead of 10 because it's instead of instead of 10 because the the the real answer is 10 instead of 14. the real answer is 10 instead of 14. that's why we cannot simply just do uh that's why we cannot simply just do uh this one with uh with this with the this one with uh with this with the previous one instead previous one instead we should also do a comparison we should also do a comparison with this one for this one with the with this one for this one with the current of the cost current of the cost so we're getting the maximum between two so we're getting the maximum between two of them and that's how we can get the correct basically the previous previous cost all right all right cool so now we have a new cost and then we can do uh the the dikes part right and then if this thing is smaller than that this the cost of new i and we do a heap push right and we do a heap push right probably that we have a new cost probably that we have a new cost plus cost and then ui new j plus cost and then ui new j okay and then don't forget to update okay and then don't forget to update this cost this cost nu i u j nu i u j equals to this equals to this right so that's it and that's the right so that's it and that's the the hold actual and in the end just the hold actual and in the end just return the uh return the uh distance of minus one and minus one distance of minus one and minus one right so that's the uh right so that's the uh that's the value right that's the that's the answer that's the answer we're looking for from the starting point to this last to this last one cool so run the code hip excuse me oh sorry excuse me oh sorry yeah i was using distance at the yeah i was using distance at the beginning then i change it that's why i beginning then i change it that's why i mistyped that okay accept it mistyped that okay accept it and then cool so this one dax and then cool so this one dax also works right and for the time also works right and for the time complexity for the texture complexity for the texture and it's i think and it's i think it's v plus e log v right so that's the it's v plus e log v right so that's the uh uh that's time complexity for dextro and as when we when we convert it into this this problem so the vertices and edges right so we have vertices vertices are like n squared right plus how about address add is also n square okay and then we have a log of n square right so this one is gone right actually as you guys can see this one is the same as the binary search by the time complexity that okay so that's so that's the direction for you guys and the last one uh what is that uh oh the union find right so let's do the unified with the with the minimum speed uh spinning tree which is also called uh cool crew score algorithm right okay so the last one is the union find okay so the last one is the union find uh uh for the union find so to for the union find so to do the union find we have to do the union find we have to create the parents right so the parents create the parents right so the parents list first so because at the beginning list first so because at the beginning everything everything is its own parents so it's going to be is its own parents so it's going to be the range of the range of and square right and then for the yeah for the union fine let's define the union find function here so the first one is find of x right so we do a terms of x right so we do a terms that x equals to that x equals to defined our parents of x defined our parents of x okay and then we return the uh okay and then we return the uh the parents of x that's defined the parents of x that's defined and then the union right so this one is and then the union right so this one is like a find with the path compression i like a find with the path compression i have already talked about this part a have already talked about this part a lot of times lot of times many times i'm not going to repeat that many times i'm not going to repeat that here here today so for a union we have r1 is going today so for a union we have r1 is going to be defined of to be defined of x right and r2 because the find of x right and r2 because the find of y okay so if r1 y okay so if r1 is not equal to r2 we do appearance is not equal to r2 we do appearance of r2 equals to r1 so again here i'm of r2 equals to r1 so again here i'm i'm skipping that that right i'm skipping that that right the the rating part right so the the rating part right so because actually to make this finite because actually to make this finite union a real one time complexity union a real one time complexity uh ideally here when we do the units we uh ideally here when we do the units we should also should also compare the uh the weight compare the uh the weight for each of the spinning tree right and for each of the spinning tree right and we'll only we'll only uh append a uh append a sorry not the spinning tree though sorry sorry not the spinning tree though sorry the the the the tree for for each of the reach the the tree for for each of the reach of the root group of the root group so we only will only be appending so we only will only be appending assigning the the root who has the assigning the the root who has the smaller smaller weight to the root to the root who has a weight to the root to the root who has a larger weight larger weight that's the way we can make this like that's the way we can make this like a tree structure balanced right but here a tree structure balanced right but here i'm just i'm just simplifying that union version a little simplifying that union version a little bit bit okay yeah basically every time okay yeah basically every time we if we really want to do that we if we really want to do that basically we have a like i think there's basically we have a like i think there's a a score or something scroll something at score or something scroll something at the beginning we have everything it's the beginning we have everything it's going to be zero right and then going to be zero right and then uh this is uh uh this is uh and this one i think that's the how we and this one i think that's the how we do it right do it right so basically if this one doesn't equal so basically if this one doesn't equal this uh this uh uh basically the if the score uh basically the if the score of r1 is is greater than the scores of r1 is is greater than the scores of r2 right and then we do uh we do this of r2 right and then we do uh we do this we do appearance of this one we do appearance of this one okay else okay else right oh and when we do this we also right oh and when we do this we also need to update the scores of r1 right so need to update the scores of r1 right so this this scores of r1 gonna be the increase uh scores of r1 gonna be the increase uh going to be the sum of this going to be the sum of this right else we do it in in the reverse right else we do it in in the reverse way right so now we're way right so now we're assigning the presence of r1 to r2 and assigning the presence of r1 to r2 and now the square of r2 will be increased now the square of r2 will be increased by this by this right something like this right something like this yeah okay cool so that so that's the uh yeah okay cool so that so that's the uh the union find template right pretty the union find template right pretty straightforward straightforward now the next thing is that we have to now the next thing is that we have to uh do this uh minimum spinning trade uh do this uh minimum spinning trade which means we have to sort which means we have to sort sort this uh the coordinates by its sort this uh the coordinates by its value value from the smallest to the biggest uh so from the smallest to the biggest uh so i'm going to call i'm going to call sorted position right and then here sorted position right and then here i'm going to write a pretty long like i'm going to write a pretty long like expression here expression here so we need to have a sort sorted so the first part is it's a list so it's a list gonna be it's a list of it's a list of the the coordinates so it's a list of the the coordinates so it's going to be the inj it's going to be the inj right so where does ij coming from right right so where does ij coming from right so it's going to be a so it's going to be a for i in range for i in range n and then for j oh n and then for j oh where did i go here for j where did i go here for j in range and right so that's the uh in range and right so that's the uh so that's the the list we're trying to so that's the the list we're trying to sort sort how about the key for to sort and then how about the key for to sort and then we then we need this kind of we then we need this kind of lambda function right uh it's going to be x and the value we're looking for is the grade of this x right so the x has is a tuple here so and the first one is the i and the second one is the j right that's how we do sorting and then yeah i'm going to variables here now we can do a i think yeah also the scene stats i think so now we start processing the trying to do the union from the smallest uh smallest square uh the lowest square right for i and j insert it position right so every time we do this we first we add this one to the scene set right so to mark it we have okay so this this this position has already been visited which means we can a union with it later on okay and then i'm also going to copy this part there's always some there's always there's always some there's always something that never change you know for something that never change you know for example this part example this part uh oh yeah i think this is exactly what we need so right because we also on the oh this part now this is going to be in instead of not right because we only allow we should only union with the previously visited uh note then union uh yeah so for the union you know when whenever we have a 2d 2d board here you know we have to since you know i like you guys as you guys seen here right so we have we basically we flattened this 2d uh grid into a 1d list here okay and and then to find that location in this 1d 1d list we can simply convert this one into a do this conversion plus j right and then new i times n plus new j that's the basically the index for these two coordinates okay cool then after this union for after union this one do the unit for this one we can simply check if the find zero right is equal to the find of n minus one if this is true it means that okay we have find a path right or we have finished building the minimum spinning spinning tray to cannot connect the source and target and that's we can that's when we need we can simply return right right cool i think that's it right if i run cool i think that's it right if i run the code the code uh did i oh uh did i oh yeah okay oh i see uh yeah let me move this one down okay ci oh i see so this part yeah that's a that's the price you need to pay for copy and for copy and pas copy and paste right scores oh i think this part is it all right accept it and then submit all right accept it and then submit cool so it also works right cool so it also works right and yeah i think that's that's it for and yeah i think that's that's it for the the the uh the unified right and the uh the unified right and the time compressive for the union find the time compressive for the union find right right and the like i said the final union uh and the like i said the final union uh with this with this uh path compression for find uh path compression for find and with the score or the weight with and with the score or the weight with union union so we can treat this both two with so we can treat this both two with the operation with o1 time complexity so the real time complexity falls into so the real time complexity falls into this part right because here you know this part right because here you know here we have this is n square right here we have this is n square right we have one square of the position right we have one square of the position right and then here's the the and then here's the the the constant four four loop here and the constant four four loop here and then here then here here's o one right this is also one here's o one right this is also one so basically this four oops n square so so basically this four oops n square so but but the real uh deciding factor is this the real uh deciding factor is this sorting part sorting part right so because we have how many right so because we have how many elements we have here elements we have here n square right all right and the sorted n square right all right and the sorted it's n square it's n square log n square right see it's exactly the log n square right see it's exactly the same same as the previous two solutions as the previous two solutions for the union find and for the union find and yeah i think that's everything i can yeah i think that's everything i can i can talk for this problem how to stop i can talk for this problem how to stop okay cool thank you for watching this okay cool thank you for watching this video guys and stay tuned video guys and stay tuned see you guys soon bye | 2024-03-21 16:23:34 | 778 | LeetCode 778. Swim in Rising Water |
|
liC67an_azg | so we are looking at this question maximum products of array and it's a maximum products of array and it's a variation of basically maximum sums of variation of basically maximum sums of array so uh i won't go into detail you array so uh i won't go into detail you might have already seen so many videos might have already seen so many videos but this is specifically for the edge but this is specifically for the edge cases the test cases which are failing cases the test cases which are failing generally because everyone is telling generally because everyone is telling this max and men on youtube so you might this max and men on youtube so you might have seen them uh i'll just have seen them uh i'll just give you an overview uh how things will give you an overview uh how things will happen like uh this is a variation of happen like uh this is a variation of maximum subway okay and the only maximum subway okay and the only difference is uh while using cadance we difference is uh while using cadance we knew where we need to break it for knew where we need to break it for example this was our uh example this was our uh maximum sum array some question type maximum sum array some question type 765 3408 and this was some test case and 765 3408 and this was some test case and we knew that once we we knew that once we reaches at 34 we need to break our train reaches at 34 we need to break our train or break our cycle because or break our cycle because it got bigger and we'll start fresh from it got bigger and we'll start fresh from here so you must be having the idea of here so you must be having the idea of maximum sub sum square because it's a maximum sub sum square because it's a variation variation but here we do not know like where do we but here we do not know like where do we need to break and people are going bad need to break and people are going bad because because of the zero and because because of the zero and especially negative cases like here we especially negative cases like here we do not have any negative and if we have do not have any negative and if we have any negative any negative if we have any negative we just treat if we have any negative we just treat them like we just add them some but them like we just add them some but while multiplying while doing product while multiplying while doing product negative plays a vital role i'll just negative plays a vital role i'll just explain you i i'll just explain you why explain you i i'll just explain you why so three points you need to consider uh so three points you need to consider uh we need to consider this max min which we need to consider this max min which everyone is telling which everyone is everyone is telling which everyone is telling and how to treat zeros basically telling and how to treat zeros basically this one is the key point because many this one is the key point because many people like i have seen people like i have seen uh this video uh sorry is explaining uh this video uh sorry is explaining like this approach will work but but like this approach will work but but this will not work in you know zero case this will not work in you know zero case is something something and he just is something something and he just leaves you on a cliffhanger so instead leaves you on a cliffhanger so instead uh this is a very simple solution you uh this is a very simple solution you you just need not to treat zeros i'll you just need not to treat zeros i'll tell you why so uh tell you why so uh three things which i would like to tell three things which i would like to tell you max till now why we need this max you max till now why we need this max till now because uh this will provide us till now because uh this will provide us our answer basically this is like this our answer basically this is like this will be our answer we'll uh keep a count will be our answer we'll uh keep a count of max till now and this will just uh of max till now and this will just uh return answer in the end till now this return answer in the end till now this plays a vital role because because uh plays a vital role because because uh min min is a kind of number which can min min is a kind of number which can convert any time for example if you are convert any time for example if you are considering men if you are considering considering men if you are considering men and men is going on some minus 34 men and men is going on some minus 34 minus 34 okay then it change to minus 78 minus 34 okay then it change to minus 78 and now suddenly a negative number and now suddenly a negative number appears for example 48 appears now when appears for example 48 appears now when these two number will be multiplied this these two number will be multiplied this will result into a positive number which will result into a positive number which will be a huge number so suddenly our will be a huge number so suddenly our min changes to max that's why we are min changes to max that's why we are like considering our main it's a hope like considering our main it's a hope it's a kind of hope that someday someday it's a kind of hope that someday someday this will convert into positive if not this will convert into positive if not we are already having our max so we need we are already having our max so we need not to worry that like we are just uh not to worry that like we are just uh going with max so going with max so what we are doing how we are calculating what we are doing how we are calculating back so i'll just tell you and this back so i'll just tell you and this point i'll tell you in a while so for point i'll tell you in a while so for max what we are doing is uh this is my max what we are doing is uh this is my array and this is my provided array i'll array and this is my provided array i'll just write this is my provided error just write this is my provided error okay so uh you can do this either by uh okay so uh you can do this either by uh you know dp and you know dp and when ddp or you can do it simple by when ddp or you can do it simple by number so i'm preferring numbers because number so i'm preferring numbers because dp is just uh dp is just uh creating any you know array just creating any you know array just increases it's basically time little bit increases it's basically time little bit like i've checked uh it shows just a like i've checked uh it shows just a second like i've submitted uh quite a few times and whenever i'm using ra it's just giving me extra space and extra time you know basically extra time not extra space so what we are doing is we have this number uh we have this added 2 3 minus 2 4 and we are calculating our max and min in digits in number basically not in array what we'll do for this max is 2 and 2 for this and now the situation is till this we need to find maximum of an array which is ending on this number basically if you give me 3 2 3 4 8 and 6 and i'll ask you what does this 8 represent so this 8 represent maximum array ending on this 8 ending on this 8 this can be 4 and 8 it can be 3 and 4 it can be a whole area i don't uh like i don't mind whatever it is but i just need basically uh highest value so max how we are finding max this is our uh this is our provided number we'll just multiply with the previous max basically and how we are finding min i'll just tell you uh i'll just tell you just a second here so consider this thing consider i have uh consider this array max and min i need these three things array max and min okay how i'll calculate first i have array i have i'm calculating max now i'm calculating currently max i'm having a this thing like this thing can also be greater now we need to consider for example if this thing was 13 and our product came uh six something just imagine our product came something our product came six so this 13 will be our main answer like you should be getting it you should be getting it three then after three what uh we need to ask max and min max and min for these value okay how will consider that you need to multiply this with this max and with this min so you'll get your current max and min i'll tell you how multiplying this three with two will give you six multiply this three with min like two of men will give you again six so what is the max what is the max from it and what is the min from it what is the main three success what is the min so max is six and min is three basically so what will store will store three and will store basically uh six max six and then six sorry max six and bin three now uh for second number four minus two what we'll do just a second 4 minus 2 what will be doing same thing again 6 multiplied by like you need to find max now and you need to find min then so first uh hold this number minus 2 minus 2 because array okay now max multiply this 6 by -2 this will give minus 12 multiply this minus 2 with 3 this will give minus 6 minus 12 and minus 6 now find out the max from this what is the max max is minus 2 so we'll store minus 2 what is win min is minus 12 we'll store minus 12 okay we have another number which is 4 uh so thing again multiply it with this minus eight multiply with this this will be minus 48 okay uh and for minimum for minimum it won't be minus 48 it will be four because whenever you will enter this min 4 minus 8 and minus 48 so my bad for max it will be 4 for max it will be 4 and for minimum it will be minus 48 so now we have these number we have this number and we need to find which number is the highest basically so 6 is the i so 6 will be the answer i know like this explanation was kind of messy you must be having an idea and like this explanation is for those who are stuck on the edge cases instead like i won't uh give to interview 30 minutes explaining this whole concept and this i just gave you an overview like how we are doing it so now we are jumping onto edge cases because uh how we are finding max max is calculating by this is my array this is my current number this is my ar this is my current number on which i am working what is this max till now this is max till now this number 6 6 multiplied with my current number my current number is minus 2 so this 6 is multiplied by minus 2. now another number min i told you man i need to find min till now what is meant till now minus 3 multiplied again with minus 2 multiplied again with minus 2 multiplied again with -2 so uh this whole array this whole like expression will give me a number array max and min array like max and min all it will give me some value for example x and y now out of these value i need to find my max and my min basically arr now i need to find max and min so that's what i'm doing here and that's what i'll be using for min also one minute also same expression and nothing is saying this is just a hope this min till now multiplied with number like this lower uh thing is just a hope i hope that someday it will get multiplied with some negative value and it will convert itself into a greater uh max value basically so now let's hop on to the edge cases so edge cases many people are telling like on zero you need to change this to one you need to break it you need to do blah blah blah no we need not to do any uh nothing keep zero as zero like just keep going according to our formula this is our formula just keep going according to this uh sir also told that uh if you want to you know for 0 just change it no we need not to change it to 1 we'll just keep i'll show you how i'll take an example of this minus 2 0 and minus 1 minus 2 0 and minus 1 just remember the formula array x and y max of this and min of this max of this will go at this place and men of this will go at uh this place okay sorted i will start solving i guess so i'll just solve it here for you you know minus 2 0 and minus 1 okay i'll just solve it minus 2 0 and minus 1 this is my array this is my max this is my min for first value min and max will be same you know now uh what was our algorithm arr which is this array comma a number x and y how this x and y are calculated these are calculated by previous max previous max previous max is this thing multiply by my current array my current array is this thing so multiply minus 0 with 0 this will give us 0 okay and how this y is created this is created by previous min multiplied by ra so previous min was this thing multiplied by array what is 0 okay it will give again zero so uh people were telling like just convert them to one because you need to move forward no no need of that just keep them to zero and keep going according to your you know algorithm now on one on one again same thing multiply with this multiply with this find out max and min so my current number is minus 1 i i multiplied with previous max and previous min now i need to find max and i need to find min so what is the max out of this max is 0 what is the min out of this minus one max is zero uh min is minus one so i told you when uh after our traversing is complete we need to find maximum number from this array maximum number from this array is zero and that's our answer basically if you'll go one if you'll go like if you change it break it no no need of that then again this case uh 0 0 minus 20 0 0 again we'll do the same thing for 0 same max and min same max and min 420 what we need to do minus 20 x and y what is our x x is multiplication of this and this what is our y y is our multiplication of this and this multiplying them will give you 0 keep going in the same fashion 0 0 multiplied 0 this is multiplied this is again 0 0 now what we need to do we just need to find the max out of this array this can be array or this can be you know numbers if you're using number used this way we are using number used this way i'll just explain code also so our max will be zero again this is also like submitted so i'll just come back on to this uh these three what are these three this first line uh this first line i'm just initializing uh my max my min i'm just initializing my max my min and my overall max overall max will be my answer basically so i have declared uh them with zero now i'll move further because this is indexing is like zero one two three and four now i'll move from one to four so i started on one and i'll be going till four basically less than the size now this is a very crucial part like why why i'm implementing this because earlier what i was doing i was just using i was just updating my dp of max air only but a problem with that thing is you need to use tp of max here also and once i'll update my dp of max here i will never be able to use my previous value so what i have done i created this you know variable i stored my value in this variable once my dp of min is calculated i stored that value back in my dp of max and then i have just calculated if my value if my current d like if my current value is greater than what was the previous value for example uh this thing is basically i'll explain this thing is uh saving me a single loop for example i'm using array just imagine this for this max thing for this max thing i'm using a array and in my array there are numbers stored like 0 0 for this okay i'll just go to a better example this is a test case we'll go to this example for this for example consider that i am using a array 2 6 minus 2 4 i have this array now i need to find the max of this array either i'll run a loop or i'll just use something else okay you'll run the loop you'll increase the complexity instead what we are doing whenever we are filling the values in we are just checking hand by hand like we are checking hand by end if we are getting a greater value we are adding we are like putting it in our overall max same thing is with numbers basically uh this is arrogantly now just imagine these are number two six minus two and four and imagine that they are falling from top so whenever two falls you check with your number like uh with your omax overall max my overall max was in the starting whatever number is given the starting basically this 2 my overall max was 2 so my first number will be checked if it's greater then no it's not it's like equal okay no worries keep my omax equals to 2 only now 6 will fall uh if six is greater than two yes it's greater than update my omax overall max to six now minus two will fall is minus two greater than two no i keep my o max same omax is six now four will fall four is for is is four greater than my omax sorry my bad is four greater than my omax so no my omax is greater so omax will be six and i'll return this six so i'll return this so that was all for this question see | 2024-03-21 13:15:01 | 152 | #152. Maximum Product Subarray | Leetcode | GFG | C++ | DP | DSA | DSA SHEET |
|
nMGL2vlyJk0 | Have Hello Guys Welcome Back To Back Door Sign In This Video Will See How To Find The In This Video Will See How To Find The Evening Element In Adhere This Is From Evening Element In Adhere This Is From List To Date Waiver Of The Match Challenge So Let's List To Date Waiver Of The Match Challenge So Let's Not Look At The Problem Statement The Not Look At The Problem Statement The Problems That Are Very Single Unique Element Problems That Are Very Single Unique Element Noida Noida Noida not listening to know where you can find all the elements of all the elements of elements of the year subscribe for techniques will take you need to solve this problem in log in to This This This long and 10ft is a property of long and 10ft is a property of decreasing order so they can take benefit decreasing order so they can take benefit from its requirements for elementary and give them to give you from its requirements for elementary and give them to give you want to search and its properties in order to solve this problem which gives no the first Indian to Present at the event will Present at the event will Present at the event will share this post with the return of the day share this post with the return of the day disciple statement in this will not be you unique element disciple statement in this will not be you unique element in this cassette is not unique in this cassette is not unique elements which was unique element and will have elements which was unique element and will have just returned without performing in just returned without performing in research no this is the richest which research no this is the richest which research no this is the richest which Doing Property Paper Property This Is The Real Name Of The Element Will Exist In Ten This Chapter Notes Withdrawal West Is The This Chapter Notes Withdrawal West Is The Property Of But You Can Actually Make Property Of But You Can Actually Make Decisions Which Partner For Dust Properties Decisions Which Partner For Dust Properties Be queries the Be queries the Be queries the previous element and will not be previous element and will not be construed as a statement of a unique construed as a statement of a unique element property in order for property element property in order for property is the partition property latest from this is the partition property latest from this point * this point index three ok no you point * this point index three ok no you found at nh-3 you have value 218 text does found at nh-3 you have value 218 text does well well well Tank Property You Can See What This Point To Is Setting On Its Related Unique Element Will Not Be Present At The Center From next9news See What Is The Forest Witch Subscribe Subscribe After Partition Property After Partition Property After Partition Property in order to apply brain research so let us know how to apply brain research for this problem solve if you are already explained plus minus subscribe and subscribe the plus minus subscribe and subscribe the Channel and subscribe the Channel Please Video like Video like Video like and subscribe the Channel and subscribe the Channel Okay so ifin Takkar Samudra left side dene will depart to a what was Okay so ifin Takkar Samudra left side dene will depart to a what was the beginning the beginning daughter for the beginning whats the year will always stand daughter for the beginning whats the year will always stand events and will end turnon isse phir width events and will end turnon isse phir width istri in between this point to istri in between this point to solve with 000 0123 solve with 000 0123 solve with 000 0123 From Debit The Element subscribe this Video not Is The Name Of The Question Is Very Point To The Day Point To The Day And And I Will Remain In The Same Position 9 Meet Will And And I Will Remain In The Same Position 9 Meet Will Be Equal To Low Plus High - Low Be Equal To Low Plus High - Low Bittu Which Bittu Which Bittu Which nodes page directly 4600 width union's president of mother and son will make a call to the time subscribe to that subscribe to that this is the code that you can see this is the code that you can see this is the code that you can see Exam Start Size Minus One Which You Want to Know The Current President Should Not Be Considered Otherwise This Is Not True When Will The Current Element Fear Or Turn On The The The Swadeshi Central Gautam Fear Not Able To Find Anything When Will Simply Return Minus One But In This Question Sensitive Guaranteed Dubai This Limit Will Never Run For This Is Very Simple Banner Solution I Hope You Enjoy Difficulty Other Approach And Solution Here Here Here everyone can benefit from it like share everyone can benefit from it like share and Video subscribe our Channel 020 This and Video subscribe our Channel 020 This Program in Videos 0 0 | 2024-03-20 10:33:06 | 540 | Single element in a sorted array | Leetcode #540 |
|
BPBQVGM3kvk | hey hi guys today we will see the good problem 792 which is saying number of problem 792 which is saying number of matching subsequences what does it mean matching subsequences what does it mean so the problem is saying that we have a so the problem is saying that we have a given a string and we have given an given a string and we have given an array of words now we have to return the array of words now we have to return the total number of subsequences which are total number of subsequences which are available in the given string s so how available in the given string s so how do we do that do we do that so if you can see that we are having few so if you can see that we are having few examples over here which is saying that examples over here which is saying that we have the input s which is the string we have the input s which is the string required to check how many subsequences required to check how many subsequences are available in the words a b b's a c d are available in the words a b b's a c d a c a c okay the output is 3 for the example one okay the output is 3 for the example one and why the output is three so if I can and why the output is three so if I can walk you through walk you through just check just check this a is available in this ABCD yes it this a is available in this ABCD yes it is available at the first position is available at the first position then this ACD it is available in the then this ACD it is available in the string is okay a is available in the string is okay a is available in the zeroth index then C is available in the zeroth index then C is available in the second index and then D is available on second index and then D is available on the third index so this ecd is also has the third index so this ecd is also has a subsequences of string s a subsequences of string s now we need to check AC so a then C and now we need to check AC so a then C and then e is also available in the string s then e is also available in the string s is not available is not available so the reason over here is so the reason over here is if we walk go through this particular if we walk go through this particular string this B is available in the string string this B is available in the string s only for once and how many B's are s only for once and how many B's are over available over here is two so over available over here is two so we'll cancel this particular B with this we'll cancel this particular B with this B do we have any other B in the string B do we have any other B in the string as that can be matched and create a as that can be matched and create a subsequences no so that is why the subsequences no so that is why the output of this particular output of this particular s is equal to a b c d e and the words a s is equal to a b c d e and the words a b b a c d and AC is three so remember b b a c d and AC is three so remember one thing over here the question is one thing over here the question is given that we have to return the integer given that we have to return the integer means we have to return the total number means we have to return the total number of count not we are not that we have to of count not we are not that we have to print the subsequences of the string print the subsequences of the string okay so we over here the subsequences okay so we over here the subsequences are three so we have printed three in are three so we have printed three in the example two if we can see that we the example two if we can see that we have few of the string and then we have have few of the string and then we have the words so out of this four only two the words so out of this four only two words can be the subsequences of this words can be the subsequences of this string as so we are returning the output string as so we are returning the output 2. 2. now if we write this particular code now if we write this particular code over here let's write the code and then over here let's write the code and then we'll go one by one to check we'll go one by one to check what exactly what exactly the logic we are trying to implement it the logic we are trying to implement it over here over here to solve this question okay so first of to solve this question okay so first of all all because we have to return the value as because we have to return the value as integer so let's take one counter and integer so let's take one counter and then we'll return this particular then we'll return this particular counter okay okay now now what we need to do so first what we'll what we need to do so first what we'll try to do over here is we try to create try to do over here is we try to create a map and this map will holds the a map and this map will holds the occurrence of this a b b a c d and AC so occurrence of this a b b a c d and AC so what we exactly trying to do over here what we exactly trying to do over here is we are trying to iterate over the is we are trying to iterate over the words array words array and then we are trying to capture the and then we are trying to capture the number of occurrence of this number of occurrence of this words words into a map okay so let's define a map into a map okay so let's define a map which is a map of which is a map of string string comma integer and now how do we add the values in this and now how do we add the values in this so we'll use a simple for Loop so we'll use a simple for Loop we'll treat over we'll treat over or gods of Harry it's Dr this particular key it's Dr this particular key as my key so this e will become the key as my key so this e will become the key of a map this BB will become the key of of a map this BB will become the key of a map and then we'll try to capture the a map and then we'll try to capture the number of occurrence of this a in the number of occurrence of this a in the whole word area whole word area so how do we do that so we'll say a map so how do we do that so we'll say a map Dot Dot get get over over default default this is estia this is estia zero zero plus one so now if you will get confused plus one so now if you will get confused what this get or default means so get a what this get or default means so get a deferred means let's say I have this a deferred means let's say I have this a available twice in this word array so available twice in this word array so why do we go and iterate over this a why do we go and iterate over this a multiple times when we say this a is a multiple times when we say this a is a subsequences of a b c d e that means the subsequences of a b c d e that means the other a is also going to be the other a is also going to be the subsequences subsequences okay so rather than going and iterating okay so rather than going and iterating over the same word again and again we'll over the same word again and again we'll see if my map already contained that see if my map already contained that particular string word then we'll take particular string word then we'll take the counter of it and the counter of it and add one particular counter in the add one particular counter in the current occurrence otherwise we'll take current occurrence otherwise we'll take the default value as 0 so this is the by the default value as 0 so this is the by default default method provided by Java which takes the method provided by Java which takes the default value if you don't have the map default value if you don't have the map contains key and it will take the value contains key and it will take the value or it will get the value for you if you or it will get the value for you if you have a particular value associated with have a particular value associated with the key so that is what we have done the key so that is what we have done over here over here so now we'll iterate toward so now we'll iterate toward our map and we'll try to find out what our map and we'll try to find out what all occurrences are there all occurrences are there so we all know how to so we all know how to trade over a map so map dot entry I am trade over a map so map dot entry I am using using I'm using a string dot integer I'm using a string dot integer then let's try map dot I hope you all know how to so the string so the string K will become K will become entry Dot get key and when we're trying to get the value what what exactly you are trying to get okay so I'll tell first what I'm trying okay so I'll tell first what I'm trying to do over here is now I'll write one more function which will iterate over my this word map and this string so we will try to match this a is available in this string or not this BB is available in the string or not so this method this method so let's say get and it will take two integer and it will take two integer sorry two string the key which we have stored like a is the key which we have stored like a is present in the map at once so first present in the map at once so first we'll pass this key over here and along with this we'll pass this particular string because we need to check the subsequences in this string itself okay so now what this function will exactly do so I'll tell you this function is exactly going to check One By One The each character availability so how does it is going to less than str1 Dot less than str1 Dot length length and JS less than thank you okay so what does this mean so when we say this this particular a is available in this or not so I'll try to take this word as I counter and this word is a g counter so my I should always be less than the length of this particular word and my Gene should be always less than this particular total string okay so this is where my while loop will run we will check whether this a we will check whether this a exist in this string or not so how do we exist in this string or not so how do we check that so we check if I check that so we check if I sorry if str1 sorry if str1 dot Care at dot Care at I I equal to equal to str2 equal to equal to str2 Dot Dot care care correct correct means if this a is available over here means if this a is available over here yes I can see this this is available yes I can see this this is available over here so if it is available over over here so if it is available over here we'll say I plus plus will here we'll say I plus plus will increment this counter to B and then we increment this counter to B and then we will check whether this if this will check whether this if this particular word has some other particular word has some other characters then we'll have to check in characters then we'll have to check in the remaining string so in this case the remaining string so in this case we'll see I plus plus we'll see I plus plus or else or else we in every of the case we have to move we in every of the case we have to move one G counter why because one G counter why because we are checking one by one this word to we are checking one by one this word to this string so if first word is not this string so if first word is not available at the second or first word is available at the second or first word is available at the first position then available at the first position then we'll have to check the second word or we'll have to check the second word or we'll have to check the second character we'll have to check the second character B likewise C and all so we'll go and do B likewise C and all so we'll go and do J plus plus J plus plus okay and if this particular J plus plus is 10 I equal to equal to str1 I equal to equal to str1 what length what length then we will say yes then we will say yes the subsequence is available otherwise the subsequence is available otherwise the subsequences is not available or not and then on the basis of that we'll increment the counter one by one and we'll return the counter so let's I hope it should work okay so there is some spelling mistake okay so now we'll test for all the test okay so now we'll test for all the test cases available example one and two cases available example one and two it will get successfully executed yes it it will get successfully executed yes it gets so I'll submit this code okay so guys we have submitted this code successfully and to this question has been solved I hope you like this video thank you so | 2024-03-21 17:04:52 | 792 | Number of Matching Subsequences | Leetcode #792 | String | Arrays | Java |
|
eIDjm-0GX_I | intel's problem that we are going to discuss today so there is a famous lead code problem so what is given here is so what is given here is there are n number of houses so i have there are n number of houses so i have taken only three houses taken only three houses which are presented in the rows which are presented in the rows and and they are colored with three colors okay they are colored with three colors okay red green green and blue here red green green and blue here there can be more colors also there can be more colors also so so what you have to find out is like color what you have to find out is like color all the houses all the houses uh uh with the minimum cost in such a way with the minimum cost in such a way so that so that the the first house first house or like the nth house let's say this or like the nth house let's say this house house if it is colored with colored red then if it is colored with colored red then the previous house cannot be colored the previous house cannot be colored with red so it can be either colored with red so it can be either colored with green or cloud colored with blue with green or cloud colored with blue ok now if it is colored with green then ok now if it is colored with green then previous one can be colored with red or previous one can be colored with red or blue like anything but not the same blue like anything but not the same so two consecutive houses cannot be so two consecutive houses cannot be colored with the same color it means colored with the same color it means short short okay so let's see the okay so let's see the problem at first problem at first and i will and i will remove the solution for now so there are in houses so here there are one two three houses where each house can be colored with red blue or green so these things are limited here it can be more also but here it's told that it's only three red green and blue okay now the cost of painting each house with certain color is different it's 17 to 17 which is different for house one you have to paint all the houses such that no two adjacent houses same color okay so this i already said the cost of painting each house is represented by the matrix cost so for this it is 17 for the this it is two cost of painting house one with red house one with green and house one with blue okay cost zero zero yeah this they'll explain cost zero zero yeah this they'll explain this this return the minimum cost to pay and all return the minimum cost to pay and all the houses the houses so basically so basically this is a dp problem this is a dp problem okay okay and uh how we can solve it is i'm and uh how we can solve it is i'm directly going into the explanation of directly going into the explanation of how we can solve it and not explaining how we can solve it and not explaining the why it is a dp the why it is a dp why like why like if a problem has to be a dp problem it's if a problem has to be a dp problem it's solved by dynamic programming then it solved by dynamic programming then it has to have optimal substructure and has to have optimal substructure and overlapping sub problems okay if you overlapping sub problems okay if you know the basics of dp if you don't know know the basics of dp if you don't know the basics of udp you can the basics of udp you can go and watch any other videos on youtube go and watch any other videos on youtube now let's see how to solve this now let's see how to solve this so at first the first step is to solve so at first the first step is to solve it it the the using dp is to find the dp stats using dp is to find the dp stats okay okay so for so for this we have to find the dp states and this we have to find the dp states and the second step is to find the the second step is to find the recurrence relation so what is the dp recurrence relation so what is the dp state it is the state it is the like definition of what is the meaning like definition of what is the meaning of tph of tph dpi j and i and j are the states or i j dpi j and i and j are the states or i j k l whatever there can be n number of k l whatever there can be n number of states states okay okay so here we can so here we can tell is that dpis let's say tell is that dpis let's say we are solving it with the 2d dp we are solving it with the 2d dp and dpi j and dpi j denotes denotes minimum cost minimum cost okay listen this very carefully okay listen this very carefully so dpij so dpij let's say this is dpi j let's say this is dpi j dpi one dpi one y one this is because zero based y one this is because zero based indexing zero zero through first okay so indexing zero zero through first okay so dp1 dp1 and then j j is this column and then j j is this column so dpij is cost so dpij is cost took minimum cost to color took minimum cost to color like all the houses till now i houses because it is in ninth row so minimum goes to color eye houses with jade color in the eighth house so this is the ieth house last house okay jth color in the last house also you can see so if i have to choose this one right if i have to choose this one this color for the ith row then what i can't do is i can't pick the previous row with the same color so it cannot be two other than two it can be anything like it can be red or it can be blue but it cannot be green because i'm picking green here okay so this is the definition of the dp or if i say let's say i'm saying this so what can be the color of this this can be the color of this can be red like i am saying the dpi one so we are picking red for this and then what we are saying is that the previous row cannot have red it can have either green or blue or whatever other color is there so minimum of all this or in here you will actually have the minimum of all this tp i minus 1 j so so this is dpi 0 this is dpi 1 and this is this is dpi 0 this is dpi 1 and this is tpi 2 tpi 2 same for here same for here so so we'll have the previous computed we'll have the previous computed values here in the dp values here in the dp so so at first this is if this is dpi 1 this at first this is if this is dpi 1 this dp dp this is dpi zero this dpi one and this this is dpi zero this dpi one and this is dp is dp i2 i2 so you can consider that there are many so you can consider that there are many other states before also so here we have other states before also so here we have only taken three houses you can consider only taken three houses you can consider there are many other houses and in here there are many other houses and in here when i take uh choose red color for this when i take uh choose red color for this house house then i can find the answers to the then i can find the answers to the previous houses previous houses whatever there are whatever there are in n number of houses let's say before in n number of houses let's say before this so you can find the answer for this this so you can find the answer for this here here so what is the answer for this what is so what is the answer for this what is the definition of this it's that the definition of this it's that the cost of coloring all previous all the cost of coloring all previous all houses with green being the houses with green being the color of the like i minus one eighth color of the like i minus one eighth house house here it is the cost of coloring all here it is the cost of coloring all whatever houses are there whatever houses are there before this like n number of houses last before this like n number of houses last ten house last i minus one houses ten house last i minus one houses with blue being the with blue being the last last like color of the eye minus one eighth like color of the eye minus one eighth house so you can take the minimum of house so you can take the minimum of this one this one this one this one this one this one and all of this the minimum of all this and all of this the minimum of all this is cost of coloring last time minus one is cost of coloring last time minus one houses okay houses okay so let's see so let's see what we have in the definition here here stated the dp states and it is the minimum goes to color first it's the minimum cost to color minimum first i houses with jth color in the 8th house okay and recurrence relation we have to see which is dpij equal to color ij plus minimum of dpi minus 1 j minus 1 let's see if this one first first i houses here let's they're the first n i houses here let's they're the first n houses or i houses houses or i houses with with color blue color blue for the eighth house so i am fixing this for the eighth house so i am fixing this this one has to be blue so if i am this one has to be blue so if i am fixing this i just cannot take this 5 fixing this i just cannot take this 5 anymore because these two will be same anymore because these two will be same color then so i have to take either this color then so i have to take either this column so i have to take answer for this column so i have to take answer for this or this or this anything or this or this anything so which one will i choose i will choose so which one will i choose i will choose the minimum the minimum because that is what i am doing because that is what i am doing in the recurrence relation so minimum of in the recurrence relation so minimum of dpi minus 1 j minus dpi minus 1 j minus and dpi minus 1 j plus 1 so i have and dpi minus 1 j plus 1 so i have considered that this is here there can considered that this is here there can be another be another color but here there is no other color color but here there is no other color so so all all so here i have taken only for 2 all all so here i have taken only for 2 because there are only three colors so because there are only three colors so remaining only two colors are there if i remaining only two colors are there if i don't take this color then they're don't take this color then they're remaining two colors but if there are remaining two colors but if there are let's say let's say an m number of colors here so you can an m number of colors here so you can take all minima except this one the one take all minima except this one the one on the above it we can take all minimum on the above it we can take all minimum for all and then this value so this is for all and then this value so this is dpij and the answer is minimum of all dpij and the answer is minimum of all this dpis why it is the minimum of all this dpis why it is the minimum of all this answer like why is this one answer this answer like why is this one answer this one is the answer because this one this one is the answer because this one gives the value dpn minus one zero gives gives the value dpn minus one zero gives the value when the color is the value when the color is zeroth color and when the color is first zeroth color and when the color is first color for the last row but color for the last row but like for the last house the color can be like for the last house the color can be anything it can be the red or green or anything it can be the red or green or blue so when the color is red then some blue so when the color is red then some answer is there when it is green then answer is there when it is green then some other answer is that when it is some other answer is that when it is blue then some other answer is there and blue then some other answer is there and you have to take the minimum of all this you have to take the minimum of all this to get the final answer to get the final answer okay okay so let's see the code so let's see the code a bit so here it's only for three houses so it becomes a smaller version of the problem and limited number of colors so it's not three hours i think it's n houses only but colors are three so there are only three colors but there can be more colors also the problem remains the same okay so here i have taken it directly i have not taken the jth loop because only three colors are there so for columns we can do it directly so here i have done it directly i have not taken any other loop but if there are m colors then you have to run a loop okay so at first this is the color matrix i have renamed it to a and is the number of rows number of columns so number of rows means number of houses okay so first house one house two house three there are three houses here so number of rows is three and number of colors is fixed so you can also take it as fixed but i have taken it in a variable now you have to initialize the dpi i have taken it i have taken a dp array with in rows and m columns where n is the number of houses and m is the number of so this is houses and this is for each house okay for each house okay so how many colors are there so how many colors are there and first row is same so first row and first row is same so first row we have taken it as the basic this one it will be the minimum okay so many more of this this this so imagine that if there is only one house okay if there is only one house this is the base case so what will you color it you will color it with the either red green but which is the minimum cost you will color it with that one so simple you will just take the minimum for first so we have initialized the first stress this one now from the second row for house so this tpi zero what is this this is like coloring here for eighth house so here we are taking as a second house we are coloring it with zeroth color then you're taking the cost directly so you're taking the cost directly and then you're taking the minimum of all this from the other on the previous row on the previous house you can you cannot color to color it with the same color so this is the concept so you are doing it as minimum of dp of i minus one one because this is a zeroth color so you can take one or two first color or the second color okay so next is your coloring with the house if you choose to color the house with one then you can take zeroth or second okay and if you choose the color choose to color it with two then you can either take it as zero or one on the previous whatever is transferred to the previous houses and you have to color it with ai to simple and then you have to return the minimum from the last row of tp so this contents what is the last row of definition last row definition disks the same definition as dp definition minimum cost to color first i houses or first n houses because this is the last row and i equal to n then it is the last row so first in houses which is the answer actually so minimum cost to file part of the answer because once it is minimum of this one so minimum cost to color first n houses with jth color on the nth house so red color on the nth house green color on the ninth house blue color on the nth house okay so if anything else contains this color then what is the minimum cost to cloud color in houses so you have to take the minimum of this one to find the final answer okay i hope this is clear and if you have any questions or can comment down | 2024-03-22 12:11:24 | 256 | Paint House | Leetcode | Dynamic Programming | Basic concept |
|
XNKCkX_tHhM | Hello Hi Everyone Welcome To My Channel It's All The Best Quotes From Unique Bar 300 All The Best Quotes From Unique Bar 300 Basis Of Your Problem Of Uniform 125 Basis Of Your Problem Of Uniform 125 Amount As Well As Opening Day Of Mushroom Amount As Well As Opening Day Of Mushroom Grid Yaar Four Types Of One Representing Starting Grid Yaar Four Types Of One Representing Starting Competition Lever Starting And Competition Lever Starting And Ending Teri Dekhi 150 Ki Pitch Ball Ending Teri Dekhi 150 Ki Pitch Ball Subscribe our channel subscribe our channel like from starting and every subscribe on subscribe and share and subscribe that and subscribe ud in over 500 start from where one of the way can go all like this way is so this is vibrant energy approach another Start From A Group Start From A Group Start From A Group Se Se Ek Pan Come With Saroj Time Take This And Come Ek Pan Come With Saroj Time Take This And Come Hair Sunidhi Hai Nazar Password Have Two Part To Avoid Doing Hair Sunidhi Hai Nazar Password Have Two Part To Avoid Doing So Will Solve This Problem So Will Solve This Problem For Tourists Visit All Dual App Phone Number Of Rose In A Number Of Columns When Will This one is well This one is well This one is well that this vansh will load in this that this vansh will load in this claim Ujjain to our such Zee claim Ujjain to our such Zee coordinator of standards and good enough to start your coordinator of standards and good enough to start your day starting channel subscribe number of cases on that anti sales and zero sales will condom policy of development slide Indian once riching Tours And Here And Need To Check Weather Will Cover All 20 Know That Is Not A Solution Of The Match Will Start From Vishnu Directly With Us For B.Com Final Year To Do Subscribe Starting From Do And Listen And Evil Returns In All Directions And Subscribe Our Channel Created Str Subscribe 0 Half Diary Marking Idiots Marking Vitamin Thorning Acid And Difficult Candle This Point To Receive New Updates Reviews And Little But It's Recent Examples Start One Of The Likes Recent Examples Start One Of The Likes And Subscribe Hair Growth In This Page Have So Instant Of Taking Describe It Can Have So Instant Of Taking Describe It Can Start From Hair Growth Sexual This Is This Start From Hair Growth Sexual This Is This Feel VPN Emergency Come 10th Time 5 Minutes Feel VPN Emergency Come 10th Time 5 Minutes Click Subscribe Button On Side Subscribe 0 Subscribe 10 For It's A A Breed Of 0497 A Breed Of 0497 A Breed Of 0497 reddy 90 bill account plus0 plus grade one will not dalungi a thousand hua hai ne yes starting that according advice such facilities for studies page subscribe this uniform share and subscribe the number 90 to 100 subscribe and you will regret and wide that enterr10 account first of all will change it's possible cases can't avoid it acts as an executive editor in chief in his voice mail - Dr that an ax has greater than or equal spoon number of roles which is the great don't like Noida Greater Noida Greater Noida Greater Noida and Greater Subscribe Noida and Greater Subscribe To That XY Effective Already Visited And To That XY Effective Already Visited And Obstacle Obstacle That Ranbir Will Replace Return That Ranbir Will Replace Return 2019 Paswan Hai If Roy Jab Scooter Great 2019 Paswan Hai If Roy Jab Scooter Great Planning And History Planning And History 's Sister Will Return 's Sister Will Return Which Hair Buffalo Mist 109 Which Hair Buffalo Mist 109 - 151 - One Because CD And Number 90 - 151 - One Because CD And Number 90 Degree 3621 Soviet Decreasing 33051 Total Degree 3621 Soviet Decreasing 33051 Total Processing Subscribe Start 2010 Subscribe Must Subscribe My Channel I Will Be Total Five I Hotel Talk Share Fennel According to All Four Directions of But Can Go in the Direction Over Close Sell Susan Boyle Egg Vighn All And And And subscribe ns200 video time for love you tell a message hair let's make a moderate thursday switch on the tribe skin total thursday switch on the tribe skin total advice appointment advice appointment subscribe channel and subscribe Translate Translate Translate Samay Decode Hai Samay Decode Hai Director Shirts For This Is The Same War Director Shirts For This Is The Same War Little Bit Familiar With Questions And Little Bit Familiar With Questions And Difficulties No Problem subscribe and Difficulties No Problem subscribe and subscribe the Channel thanks for subscribe the Channel thanks for watching | 2024-03-25 14:23:10 | 980 | unique paths iii | unique paths iii leetcode | leetcode 980 | dfs + backtrack |