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
|
---|---|---|---|---|---|
YB-A6OUj98o | hey hey everybody this is larry this is me going over q3 me going over q3 of the weekly contest 227 uh of the weekly contest 227 uh largest merge of two strings so actually largest merge of two strings so actually this one pretty quickly i spent too much this one pretty quickly i spent too much time time at the end testing for this one because at the end testing for this one because i wasn't sure i wasn't sure um but but i think this is uh greedy in um but but i think this is uh greedy in a way a way and and how is it greedy um i think for and and how is it greedy um i think for me me during the contest the way that i proved during the contest the way that i proved to myself is green and i noticed that n to myself is green and i noticed that n is less than three thousand so i have to is less than three thousand so i have to be be um so n squared works but not so much in um so n squared works but not so much in python i don't know why they do it that python i don't know why they do it that way way um the only reason why my n square um the only reason why my n square solution works is because solution works is because in python the strings optimize in python the strings optimize the string operations are optimized but the string operations are optimized but but like if i had to rewrite my own but like if i had to rewrite my own string operations it would be too slow string operations it would be too slow so i think that's actually um so i think that's actually um that's actually not great um yeah uh yeah so so the pro so this problem is yeah so so the pro so this problem is going to be going to be um and squares i said the intuition um and squares i said the intuition between behind the greedy between behind the greedy is just for me during the contest is is just for me during the contest is just try out every case just try out every case right so this is a good case to kind of right so this is a good case to kind of highlight it highlight it let me put it here for visualization let let me put it here for visualization let me also make me also make a little bit bigger here a little bit bigger here um you know so the tricky um you know so the tricky part about this one is knowing that here part about this one is knowing that here the solution you actually the solution you actually because you know you take the a you because you know you take the a you don't know which a to take don't know which a to take first um and the the this prefix that first um and the the this prefix that you want to take you want to take is the one that gives you the largest is the one that gives you the largest lexographically lexographically earlier or like the graphically largest earlier or like the graphically largest string right and string right and that means that you're gonna go okay do that means that you're gonna go okay do i take the first character i take the first character nope uh can i take the second character nope uh can i take the second character no um because they're still the same and no um because they're still the same and then the third cat the three characters then the third cat the three characters a b and d a b and d and because this is good then we we just and because this is good then we we just want to take this chunk because want to take this chunk because a b and d is before a b and c right so a b and d is before a b and c right so that's kind of that's kind of one uh one case the other case that i one uh one case the other case that i tested and i did this during the contest tested and i did this during the contest it was decreasing right if it's it was decreasing right if it's decreasing i don't know b decreasing i don't know b and c say um then you actually don't do and c say um then you actually don't do the prefix right because d the prefix right because d because then you do the greedy of um if because then you do the greedy of um if they're the same they're the same um well i mean i do the same logic but i um well i mean i do the same logic but i i do one string at i do one string at one character at a time so then i go one character at a time so then i go okay c is better than b okay c is better than b so let's take it from this string it's so let's take it from this string it's just a tiebreaker it actually doesn't just a tiebreaker it actually doesn't matter in this case matter in this case because then now you take the d and you because then now you take the d and you remove the d but then here remove the d but then here again because it's lexographically again because it's lexographically largest you take the second d largest you take the second d and then so forth um and then you kind and then so forth um and then you kind of keep on going that way of keep on going that way and um and i think this is also uh and um and i think this is also uh for this problem if you have trouble for this problem if you have trouble seeing why for lexographically seeing why for lexographically largest greedy works um it's because largest greedy works um it's because you know if you look at any given string you know if you look at any given string uh let's say you know you have a uh let's say you know you have a um or maybe even do something like um or maybe even do something like you know z sentences that says that you know z sentences that says that right right in this case you always want to optimize in this case you always want to optimize for the earlier for the earlier character because in this case even character because in this case even though though it doesn't matter what the rest of the it doesn't matter what the rest of the characters are right because as long as characters are right because as long as we have b we have b this is the string will always be larger this is the string will always be larger than this string right than this string right so so that's kind of the idea and we try so so that's kind of the idea and we try to figure out how to be as greedy as to figure out how to be as greedy as possible possible and in a way that the code works fast and in a way that the code works fast enough right enough right so that's basically the idea behind this so that's basically the idea behind this problem um yeah problem um yeah um cool uh so then after that um basically i built a deck of the two words you could also use a pointer i think it's just i mean it's definitely the same but i like using a deck because it lets me do what i'm about to do but also just um yeah it just makes it a little bit uh clearer so that i don't have to understand it um though with any goes 3000 maybe that was a little bit cutting it close so i don't know we'll see but um but yeah but so i created a deck of the two words and then here this is kind of similar to merge sword uh where okay while they both have string i do comparison and again we use greedy because because if the two characters are not the same whatever character you take there's no way to make it bigger by taking the other one right because it's smaller by default so so yeah um and then after that we look at the entire substring which is what this does um and this is basically the same thing that we talked about earlier where we looked at you know if it's a b c d a b c e we want to be able to take uh the a from here because we know that um if there is a way to get to the e earlier so that's basically what this does is that it does a substring comparison and this is actually o of n even though this is very um you know this this line is very short and and that you know you might not notice it but this is o n because this this the the length of the string could be o of n and and this is an oven comparison so yeah so that that's why this loop is n square um but thankfully because i guess string comparisons in python is fast enough because they optimize it um that's my guess i don't know for sure but in any case that's you know this is n square and we just take the first character from that and we pop it um so that so the reason why we do it this way instead of taking the prefix is so that we handle both cases of increasing and decreasing uh strings and then at way end we just make sure that if there's any characters left we put in the at the end and that's pretty much it so what is the complexity of this uh so it's gonna be dominated by this part again this is this is o of n this is linear hopefully that's clearer and this is all also oven this is the part that's subtle even if you might have gotten it without noticing so yeah so this is o of n square kind of we're going to call it that or o m uh whoops the square if you want to call it that the square if you want to call it that uh roughly speaking uh roughly speaking and in terms of space the way that i did and in terms of space the way that i did it's going to be old it's going to be old and plus m because i use dex but but this can be improved to o of one and the way that you do an of one is just having two pointers right instead of having a deck um you just keep track of what was the the beginning of the the the string um and then just pop them off as necessary that's all i have for this problem let that's all i have for this problem let me know what you think and i me know what you think and i will yeah will yeah and i will yeah you can watch me stop it and i will yeah you can watch me stop it during the contest during the contest next let me make this smaller a little next let me make this smaller a little bit bit for a second so you can screenshot it or for a second so you can screenshot it or whatever so yeah whatever so yeah and now you can watch me do this next hmm the hot case is trying to figure out it works you you so okay spending too much time hey uh yeah thanks for watching uh hit the like button to subscribe and join me in discord um let me know what you think about this farm and this solution this explanation um and yeah do have a good day and a good weekend stay good stay healthy to good mental health and i will see you next problem | 2024-03-22 12:02:31 | 1,754 | 1754. Largest Merge Of Two Strings (Leetcode Medium) |
|
daiFr6ul7IE | to the right by K places so actually through this problem there are two things that we should know and the both of the two things are pretty much explained by the examples so in the first example we have k equal to 2 so basically we have to rotate the list by to the right by two places and uh we are given one two three four five as a sequence basically that represents our linked list and as you can see there are two rotations happening and the end result will basically be just the two elements at the end of the list because K is equal to two they are moved to the front in the in and the rest of the of the nodes so and the rest of the of the nodes so basically the nodes that were in front basically the nodes that were in front uh in front of the uh during the before uh in front of the uh during the before the rotation uh will we will be shifted the rotation uh will we will be shifted down uh after the K elements from the down uh after the K elements from the from the back of the linked list so in from the back of the linked list so in this case we have four and five as the this case we have four and five as the last two elements they will be put into last two elements they will be put into front and then we will have the same front and then we will have the same sequence of nodes that we had in front sequence of nodes that we had in front before these uh two uh elements so before these uh two uh elements so basically you have to rotate the list by basically you have to rotate the list by K places means to put the K places means to put the last K elements in the front that's what last K elements in the front that's what that's basically what it means that's that's basically what it means that's the first thing that we we should know the first thing that we we should know and the second thing um is going to be and the second thing um is going to be the second example so we have zero one the second example so we have zero one and two and two um Sr nodes in the link list and we have um Sr nodes in the link list and we have k equals we have to four important thing k equals we have to four important thing here is to know that the length of the here is to know that the length of the list is in this case true list is in this case true and your number of rotations that we and your number of rotations that we will do is the uh is uh four K is equal will do is the uh is uh four K is equal to four but as you can notice after the to four but as you can notice after the third rotation so one two three uh after third rotation so one two three uh after this two rotation We have basically the this two rotation We have basically the same list that we have at the beginning same list that we have at the beginning basically the same list as with uh basically the same list as with uh without any any rotation and that's without any any rotation and that's basically generally the rule here uh if basically generally the rule here uh if we if we have a list of flagged n and we we if we have a list of flagged n and we rotated K times where K is equal to n rotated K times where K is equal to n uh or any multiplier of n we will uh or any multiplier of n we will basically arrive at the same destination basically arrive at the same destination where we started we will arrive at the where we started we will arrive at the same linked list that we had before the same linked list that we had before the rotations so rotations so the only uh contribution of K are the the only uh contribution of K are the elements that are left when we are done elements that are left when we are done dividing K by n so if you for example dividing K by n so if you for example have in this case four have in this case four uh the we have total of three uh the we have total of three rotations before and the only only rotations before and the only only rotation that contributes basically is rotation that contributes basically is the last rotation and how do we actually the last rotation and how do we actually get the uh the number of rotation that get the uh the number of rotation that contributes we just basically say the contributes we just basically say the module so for model of three is one to module so for model of three is one to get the number of rotations that get the number of rotations that contribute uh or we we basically use contribute uh or we we basically use just the modular operator now the number just the modular operator now the number of nodes in the list in directly Center of nodes in the list in directly Center rate is 0 to 500 the node values are rate is 0 to 500 the node values are from minus 100 to 100 and the case from from minus 100 to 100 and the case from 0 to 10 to uh two times at 10 to the 0 to 10 to uh two times at 10 to the ninth ninth um out here we will have a linear time um out here we will have a linear time complexity solution because uh basically complexity solution because uh basically we will proceed to solve this problem in we will proceed to solve this problem in three steps the first step would be to three steps the first step would be to actually calculate the length of the actually calculate the length of the list length list to do that we will just list length list to do that we will just reverse the linked list as long as we reverse the linked list as long as we have valid uh notes as long as we don't have valid uh notes as long as we don't have a iterator that's equal to no have a iterator that's equal to no that's the first thing then we will that's the first thing then we will calculate the number of frustrations and calculate the number of frustrations and to calculate the number of stations we to calculate the number of stations we will just do K module of n will just do K module of n to get the number of stations that make to get the number of stations that make actually the contribution that may take actually the contribution that may take effect on the on the links list and then effect on the on the links list and then after that's done we will get basically after that's done we will get basically the number of nodes from the end of the the number of nodes from the end of the linked list that we have put in the linked list that we have put in the front and how do we actually get to the front and how do we actually get to the uh basically to the uh basically to the uh a node before that group of N and uh a node before that group of N and nodes so in the first linked list we had nodes so in the first linked list we had one two three one two three four and five so we wanted to take these four and five so we wanted to take these two nodes and put it in the front we two nodes and put it in the front we kind of did a similar thing in the kind of did a similar thing in the removal of the ant nodes from the linked removal of the ant nodes from the linked list uh basically we use the fast and list uh basically we use the fast and slow approach slow pointer approach uh slow approach slow pointer approach uh we uh basically move the fast fast we uh basically move the fast fast pointer end times and notes and then uh pointer end times and notes and then uh be removed the fast and slow points or be removed the fast and slow points or simultaneously one note at a time at the simultaneously one note at a time at the end the slow pointer will be pointing end the slow pointer will be pointing just before the group of n nodes because just before the group of n nodes because it has to catch up to the fast pointer and it has to catch up to the fast points are in and the differences basically and and notes so slow will be pointing to the node T value three so the thing that we have to do is first so to do that we can just do slow next so to do that we can just do slow next is equal to null is equal to null but before that we will Mark the slow but before that we will Mark the slow next as our new head because we will next as our new head because we will return this as the final result so we return this as the final result so we have our new head which will return this have our new head which will return this will be the beginning of the rotary will be the beginning of the rotary table list and we have broke have broken table list and we have broke have broken the connection between these two uh the the connection between these two uh the last thing that we have to do we have to last thing that we have to do we have to put the first group of nodes before the put the first group of nodes before the end and and notes group of endnotes uh end and and notes group of endnotes uh to the back of the linked list so these to the back of the linked list so these uh two notes K C because K is equal to uh two notes K C because K is equal to two have to be in the front and to do two have to be in the front and to do that we know that the if you have a that we know that the if you have a pointer on the let's say tail that pointer on the let's say tail that points I will be pointing to the last points I will be pointing to the last element that's where we have iterated element that's where we have iterated over all the elements so we'll just uh over all the elements so we'll just uh keep our keep our table pointer to point keep our keep our table pointer to point to the last element in the length twice to the last element in the length twice so basically to put the first group of so basically to put the first group of pointer first group of nodes uh to the pointer first group of nodes uh to the back of the list we will just do tail back of the list we will just do tail next is equal to the Head next is equal to the Head because initially head will be pointing because initially head will be pointing to this element here it's in the first to this element here it's in the first element in the linked list uh so we can element in the linked list uh so we can just connect it if the tail is pointing just connect it if the tail is pointing to the last element it can just connect to the last element it can just connect it like this it like this and that in this case if you return the and that in this case if you return the new head new head we will have 4 5 and then the rest of we will have 4 5 and then the rest of the notes the notes so we will have linear time complexity so we will have linear time complexity and because you are not creating these and because you are not creating these shots in the addition this actually has shots in the addition this actually has a constant space complexity a constant space complexity first we will check if you have an empty first we will check if you have an empty list basically for now if there is we list basically for now if there is we cannot rotate it so we just return the cannot rotate it so we just return the head as it is next we'll create our head as it is next we'll create our dummy node and The Ether will be dummy node and The Ether will be pointing to the first note in the UFOs pointing to the first note in the UFOs which is basically the head and we will which is basically the head and we will clear the list no tail which will clear the list no tail which will basically point to the last element in basically point to the last element in the link list after we are done with the the link list after we are done with the first reversal and to do the first first reversal and to do the first reversal we will basically use it to reversal we will basically use it to calculate the length the total length of calculate the length the total length of the list so we will initialize our list the list so we will initialize our list length to zero and we will iterate over length to zero and we will iterate over the list as long as the iterator is not the list as long as the iterator is not equal to null basically as long as we equal to null basically as long as we have notes in the list and we will link have notes in the list and we will link each iteration will increment the length each iteration will increment the length uh and uh before we move data to the uh and uh before we move data to the next element we will record the last next element we will record the last element that we have visited so element that we have visited so basically man once the uh the condition basically man once the uh the condition in the Bible is not fulfilled anymore in the Bible is not fulfilled anymore the it will be equal to no but the two the it will be equal to no but the two will be the last well the element it's will be the last well the element it's just basically the last element in the just basically the last element in the linked list linked list uh then we'll calculate the number of uh then we'll calculate the number of rotation in using the former K module of rotation in using the former K module of Link's length to calculate the number of Link's length to calculate the number of number of predictions that actually make number of predictions that actually make the effect to the uh that you have that the effect to the uh that you have that effect uh linked list uh then if the effect uh linked list uh then if the number of rotation is equal to zero we number of rotation is equal to zero we just returned the head as it is there's just returned the head as it is there's no uh there are no changes to the to the no uh there are no changes to the to the linked list otherwise we declare our linked list otherwise we declare our slow and fast pointer and we make them slow and fast pointer and we make them point to the same node the dummy is point to the same node the dummy is pointing to and then we will move uh pointing to and then we will move uh we'll basically create this we'll basically create this um a few notes ahead for the for the um a few notes ahead for the for the fast pointer by just iterating the fast pointer by just iterating the number of station times and each time number of station times and each time moving the fast pointer to the next uh moving the fast pointer to the next uh to the next node next we'll move this to the next node next we'll move this fast and slow pointer simultaneously as fast and slow pointer simultaneously as long as we don't uh basically reach the long as we don't uh basically reach the last element in the in the linked list last element in the in the linked list then we know that the uh slow pointer is then we know that the uh slow pointer is now pointing to the first element of the now pointing to the first element of the last n notes in the linked list so that last n notes in the linked list so that will represent our new head and we will represent our new head and we declare that new node as our new head declare that new node as our new head then we break the connection between the then we break the connection between the first and second group by using our first and second group by using our slope pointer and then finally slope pointer and then finally and we connect the second group to be and we connect the second group to be now the first group uh by just now the first group uh by just connecting the last element which is my connecting the last element which is my priority to the initial head uh or the priority to the initial head uh or the linked list B initial head will be the linked list B initial head will be the first element in the first group that's first element in the first group that's the first element in the whole length the first element in the whole length plus so we just made the we create that plus so we just made the we create that connection and then we just return our connection and then we just return our own new head | 2024-03-20 10:50:46 | 61 | Rotate List - Leetcode 61 |
|
lp7rlaI5suo | hi everyone so welcome back to our new video today's lead code daily challenges video today's lead code daily challenges largest odd number in string this is an largest odd number in string this is an easy level question okay now let's see easy level question okay now let's see the problem description so in this the problem description so in this problem we have been given a string problem we have been given a string which is called num okay and it is which is called num okay and it is representing a large integer and what we representing a large integer and what we need to do is we need to return the need to do is we need to return the largest valued odd integer that is a largest valued odd integer that is a nonempty substring of num or an empty nonempty substring of num or an empty substring if no odd integer exist now substring if no odd integer exist now they have told that what a substring is they have told that what a substring is what is a substring basically it is a what is a substring basically it is a continuous sequence of characters within continuous sequence of characters within a string so if we have let's say and a string so if we have let's say and okay so a substring of and will be a n okay so a substring of and will be a n or n d a d cannot be a substring Okay so or n d a d cannot be a substring Okay so so what it means here is that a so what it means here is that a substring is a continuous sequence of substring is a continuous sequence of characters within a string now what we characters within a string now what we need to do here like we have been given need to do here like we have been given a string right and what we need to do we a string right and what we need to do we need to return the largest valued odd need to return the largest valued odd integer that means that it can be five integer that means that it can be five it can be 35 it can be 37 it can be 547 it can be 35 it can be 37 it can be 547 anything is possible right now let's see anything is possible right now let's see with an example like we have been given with an example like we have been given here 52 right now we have 52 also now in here 52 right now we have 52 also now in this the largest odd integer is five this the largest odd integer is five right because if it was 55 then we would right because if it was 55 then we would have written 55 itself but here what we have written 55 itself but here what we have we have two at the last index so have we have two at the last index so that means that 52 as a whole is an even that means that 52 as a whole is an even number right so we need to return only number right so we need to return only five five here so the output that will be returned here so the output that will be returned here is five now in the second example here is five now in the second example they have given given as they have given given as 4206 in this four is also even 2 is also 4206 in this four is also even 2 is also even 0 is also even and 6 is also even even 0 is also even and 6 is also even so they told us that if there is no odd so they told us that if there is no odd integer then we need to return an empty integer then we need to return an empty string so we will just return an empty string so we will just return an empty string now let's see the third example string now let's see the third example in this example we have 33 5 4 2 7 in in this example we have 33 5 4 2 7 in this 3 5 and 7 all are odd right 3 5 4 2 this 3 5 and 7 all are odd right 3 5 4 2 2 7 in this all are odd right now when 2 7 in this all are odd right now when we if we start from this index okay we we if we start from this index okay we see that we have three now when we move see that we have three now when we move on to five we see that it is a value on to five we see that it is a value greater than three right now when we greater than three right now when we move on to four we see that we have an move on to four we see that we have an even integer so when we now we move even integer so when we now we move forward right and we see that again we forward right and we see that again we have an even integer but at last we have have an even integer but at last we have an odd integer right so what it is what an odd integer right so what it is what is happening here the number as a whole is happening here the number as a whole is an odd integer is an odd integer right the number as a whole is an odd right the number as a whole is an odd integer so what we have to do we will be integer so what we have to do we will be returning this entire string now if we returning this entire string now if we start started from the first index then start started from the first index then the chances of losing our pointers with the chances of losing our pointers with the help uh with the uh even and odd the help uh with the uh even and odd integer is very high because we had here 35 427 right now we started we had here 35 427 right now we started from this we checked that it is 35 right from this we checked that it is 35 right now we came to five we came here then we now we came to five we came here then we saw that there is four we and in this saw that there is four we and in this even integer um the problem was that uh even integer um the problem was that uh we don't need this but in order to have we don't need this but in order to have the largest integer there is possibility the largest integer there is possibility that after this four there was a that after this four there was a presence of three then what would have presence of three then what would have be done so in order to avoid this we be done so in order to avoid this we know that any odd integer will be ending know that any odd integer will be ending with a odd number right means here like with a odd number right means here like we have seven it is an odd number right we have seven it is an odd number right and this entire number is odd because of and this entire number is odd because of the seven here right now what we will do the seven here right now what we will do therefore we will start iterating from therefore we will start iterating from the back and we will see that our number the back and we will see that our number lies between 1 3 5 or 7 or 9 or not if lies between 1 3 5 or 7 or 9 or not if it is one uh it if it is in varying it is one uh it if it is in varying between these numbers then the number between these numbers then the number from the starting to that Index right from the starting to that Index right will be odd only like here um we had will be odd only like here um we had let's take for an example let's take for an example 3 52 okay now we started from this index 3 52 okay now we started from this index we see that this is a even number this we see that this is a even number this is an even number so we move forward we is an even number so we move forward we see that this is an odd number now since see that this is an odd number now since five is an odd number that means five is an odd number that means whatever number is before that let's say whatever number is before that let's say it was four here and two here okay so it was four here and two here okay so whatever number are before that it whatever number are before that it doesn't matter right we just need the doesn't matter right we just need the last index to see that it is odd or not last index to see that it is odd or not as soon as we got to know that it is as soon as we got to know that it is five at this index so what what we can five at this index so what what we can say that 2 4 3 5 is an odd number right say that 2 4 3 5 is an odd number right so what we will do we will take the so what we will do we will take the entire string from 0 to that index entire string from 0 to that index whatever index we are on so now we whatever index we are on so now we understood that what what what is understood that what what what is happening in this question let's move on happening in this question let's move on to the approach so basically in the approach what we saw we were starting the iteration from the back right or the end of the integer so our integer uh the iteration was starting from nus one and it was continuing till n is I is equals to Z right right so I is greater than or equals to Z and I ++ iusus because we are iterating in the opposite one opposite direction now we have the loop now what we need to see if let's say this is num right so what we need to see if num of I is equals equal 1 or num of I is equals equals 3 or num of I is equals equals five or num in the same way we will also also now we have checked that uh any of now we have checked that uh any of the character is equals to these numbers the character is equals to these numbers or not right now if we found this then or not right now if we found this then what we have to do we will simply what we have to do we will simply return the number from 0o to whatever the value this string is on like if we have 2 3 4 5 7 okay uh 2 3 4 5 six let's say okay so 0 1 2 3 4 this is on Fourth Index right now uh this is an even number so we will leave it out we will move on to the third index now we see that this is an odd number that means we need this entire entire string or subring right so what we have to um return we have to return the string from zero to third index so what we will do we will return the value from 0 to I + 1 why we are using here I + 1 because the value here will be uh ready uh will be returned till I I minus one that means it will be returned till I only that's why we are using I + 1 and if we come out of this Loop and none of this satisfied that means we never found a number which was equals to 1 3 5 or 7 or 9 so simply what we need to do we need to return empty string right so when we didn't find anything out of the loop we will return empty string now let's move on to the code so whatever little doubts are there will be cleared with it so let's move on to the code now here we have a reverse Loop so I will start Loop it will start from n minus one and Loop it will start from n minus one and continue till zero continue till zero and here we have a reverse Loop now what and here we have a reverse Loop now what we need to do we need to check if our we need to do we need to check if our character at that index is equals equals character at that index is equals equals 1 or 1 or five or five or 7 7 or 9 now we have these values now what we need to do if we found any of these values then we will return the string from that index to the IAT index so we will take this here I + 1 because uh it will take the the integer from 0 to I only now if we didn't find anything what we need to do we need to return an empty string so I will be returning an empty now now okay I didn't Define the length of the okay I didn't Define the length of the string so let's define the length of the string so let's define the length of the string let's try to run it string let's try to run it now so the test cases have passed sample now so this code has been accepted now so this code has been accepted that's it for today guys thank you for that's it for today guys thank you for watching if you found this video video watching if you found this video video helpful please let me know in the helpful please let me know in the comments also subscribe to the channel comments also subscribe to the channel and hit the Bell notification so you and hit the Bell notification so you will be notified every time I post a new will be notified every time I post a new video thank you for | 2024-03-25 12:23:15 | 1,903 | 1903. Largest Odd Number in String| Easy| Leetcode - 1903 | Leetcode daily challenge | Dec challenge |
|
iM4QKS4GxA4 | hello friends in this session we are going to discuss another lead code going to discuss another lead code problem lfu cache least frequently used problem lfu cache least frequently used cache cache which is different from lru cache least which is different from lru cache least recently used cache it is good to recently used cache it is good to understand lru cache implementation understand lru cache implementation before understanding lfu cache i have before understanding lfu cache i have given lru cache video link in the given lru cache video link in the description description please watch it if you are interested please watch it if you are interested our cache comes with limited capacity we our cache comes with limited capacity we must provide cache capacity as part of must provide cache capacity as part of the cache initialization we must the cache initialization we must implement two functions get and put implement two functions get and put get function takes key as input and get function takes key as input and returns the value if it exists it returns the value if it exists it returns -1 if the value does not exist returns -1 if the value does not exist the put function takes both key and the put function takes both key and value as input value as input it updates the value of the key if it is it updates the value of the key if it is present present otherwise it inserts the key value pair otherwise it inserts the key value pair into the cache into the cache in case if the cache reaches its in case if the cache reaches its capacity limits then it should every capacity limits then it should every least frequently used key before least frequently used key before inserting a new item inserting a new item in case there are multiple keys with in case there are multiple keys with same usage frequency same usage frequency then remove least recently used key out then remove least recently used key out of them the expectation is we should of them the expectation is we should implement get and put functions at implement get and put functions at constant average time complexity let's constant average time complexity let's directly jump into the solution directly jump into the solution since the solution is expected with since the solution is expected with constant time complexity constant time complexity hash map is the best suited data hash map is the best suited data structure here we will store key value structure here we will store key value pair into this hash map insertion and pair into this hash map insertion and retrieval of data takes constant time retrieval of data takes constant time with hash maps let's assume that this with hash maps let's assume that this hash map is our cache hash map is our cache our cache comes with limited capacity as our cache comes with limited capacity as per the problem statement let's assume per the problem statement let's assume that our cache capacity is 2. that our cache capacity is 2. it can store maximum of 2 key value pays it can store maximum of 2 key value pays only any time when you try to insert new only any time when you try to insert new key value pair when it is at its maximum key value pair when it is at its maximum capacity capacity it must evict one of its key value page it must evict one of its key value page to create a room for the new insertion to create a room for the new insertion the eviction policy is least frequently the eviction policy is least frequently used we must identify which key is used used we must identify which key is used least frequently and then delete it least frequently and then delete it before inserting a new key before inserting a new key so we must track each key usage count we so we must track each key usage count we will use this hash map we have named it will use this hash map we have named it frequency map frequency map in this hash map the key represents in this hash map the key represents count and the value represents list of count and the value represents list of cachet keys cachet keys why list of caches why list of caches because it is very common that multiple because it is very common that multiple keys usage count can be same keys usage count can be same so we are using list of keys as a value so we are using list of keys as a value in this hash map in this hash map now when the least frequently used keys now when the least frequently used keys are more than one in this list how to are more than one in this list how to choose which key to be deleted choose which key to be deleted as per the problem statement we need to as per the problem statement we need to identify least recently used keys out of identify least recently used keys out of this list this list so rather using list as a value here so rather using list as a value here we will use doubly linked list as a we will use doubly linked list as a value value so that we can control node order based so that we can control node order based on usage on usage i suggest to watch lru cache i suggest to watch lru cache implementation to understand better why implementation to understand better why we need doubly linked list here we need doubly linked list here in general registering raw value into in general registering raw value into this hash map as it is we can store this hash map as it is we can store linked list node as a value in this hash linked list node as a value in this hash map map so we can keep track of each key's usage so we can keep track of each key's usage count within the node itself count within the node itself then we can easily identify in which then we can easily identify in which linked list this node is part of we can linked list this node is part of we can easily relate these two hash maps easily relate these two hash maps i mean here we have count as a key and i mean here we have count as a key and linked list as a value linked list as a value there will be multiples of key value there will be multiples of key value page if we know the count then only we page if we know the count then only we can identify respective nodes linked can identify respective nodes linked list in this hash map list in this hash map in our case node will be holding the key in our case node will be holding the key usage count if we know the count then we usage count if we know the count then we can directly relate to the linked list can directly relate to the linked list in this hash map in this hash map in general if we want to reduce code or in general if we want to reduce code or if we want to use language provided if we want to use language provided linked list as it is linked list as it is we don't need to maintain node objects we don't need to maintain node objects we can simply store raw values into this we can simply store raw values into this hash map as it is in such cases how can hash map as it is in such cases how can we maintain key usage count we maintain key usage count this is why we need this hash map to this is why we need this hash map to maintain key usage count here in this maintain key usage count here in this hash map hash map key will be cache a key and value will key will be cache a key and value will be usage count be usage count if we know the key if we know the key then we will get its usage count from then we will get its usage count from this map and then we can identify which this map and then we can identify which linked list it is part of linked list it is part of now now how do we know least usage count at any how do we know least usage count at any given point of time given point of time we need to keep track of it we need to keep track of it this variable min usage count will hold this variable min usage count will hold least frequently usage count at any least frequently usage count at any given point of time given point of time let's apply these actions and understand let's apply these actions and understand the logic better the logic better initially the cache is empty initially the cache is empty we are making a put call here key is one we are making a put call here key is one and the value also one we will be and the value also one we will be inserting this key value pair into the inserting this key value pair into the cache cache in general we will check that the key in general we will check that the key already exists or not in the map before already exists or not in the map before insertion insertion we will consider put call also as part we will consider put call also as part of usage count let's track the count so of usage count let's track the count so our key is 1 and its usage count is 1. our key is 1 and its usage count is 1. now in the frequency map we will add now in the frequency map we will add count as 1 and we will maintain a linked count as 1 and we will maintain a linked list list in the list we will add our key here in the list we will add our key here we will maintain key usage order in this we will maintain key usage order in this linked list we'll update minimum usage linked list we'll update minimum usage count value as 1 here count value as 1 here by default we will update this value by default we will update this value with 1 during any new insertions with 1 during any new insertions let's go to the second action let's go to the second action again it is put call again it is put call since the cache size is 1 and the key 2 since the cache size is 1 and the key 2 does not exist in the cache just insert does not exist in the cache just insert it it we will update usage count also the key we will update usage count also the key is 2 and its count is 1. is 2 and its count is 1. since its usage count is 1 we will add since its usage count is 1 we will add this key under this linked list itself this key under this linked list itself now look at the insertion order now look at the insertion order the tail is always carries the most the tail is always carries the most recently used case and the head always recently used case and the head always carries the least recently used case carries the least recently used case so it is always easy to identify which so it is always easy to identify which is least recently used key from this is least recently used key from this list the next action is get call the key list the next action is get call the key one is exist in the cache simply return one is exist in the cache simply return its value its value before returning the value we must before returning the value we must update our usage counts update our usage counts increment key 1 value to 2. increment key 1 value to 2. since the count became 2 we need to since the count became 2 we need to maintain a separate list for count 2 maintain a separate list for count 2 here here and then move key one from here to here and then move key one from here to here the next action is put call if you the next action is put call if you notice here the cache is already at its notice here the cache is already at its maximum capacity too there is no room maximum capacity too there is no room for new element so we must evict one of for new element so we must evict one of the element before adding another the element before adding another element based on our minimum usage count element based on our minimum usage count variable the least frequently used count variable the least frequently used count is 1. is 1. based on this based on this 2 is the key supposed to be evicted 2 is the key supposed to be evicted remove two from here remove two from here delete this entry also delete this entry delete this entry also delete this entry now add new entry into the cache now add new entry into the cache also update its count key is 3 count is also update its count key is 3 count is 1 and here we will add 1 and here we will add key 3. key 3. the next action is get call since key 2 the next action is get call since key 2 does not exist in the caching simply does not exist in the caching simply written -1 written -1 the next action is again get called the next action is again get called key 3 exists in the cache key 3 exists in the cache return the value return the value before returning the value update counts before returning the value update counts as well as well increment key 3 count as 2 here and move increment key 3 count as 2 here and move 3 from here to here 3 from here to here since count 1 linked list is empty we since count 1 linked list is empty we need to update minimum usage count value need to update minimum usage count value from 1 to 2. from 1 to 2. the next action is put call since the the next action is put call since the cache is at its maximum capacity we must cache is at its maximum capacity we must evict one of the element before evict one of the element before inserting another element inserting another element least frequently used key count is to least frequently used key count is to here here but there are two keys in this usage but there are two keys in this usage count so we must find least recently count so we must find least recently used key from this list used key from this list as discussed as discussed linked list head carries the least linked list head carries the least recently used key here recently used key here key 1 is part of linked list head so key 1 is part of linked list head so remove this remove this delete this entry here delete this entry here delete this entry also delete this entry also and then insert new element 4 and then insert new element 4 4 4 update its usage count four the count is update its usage count four the count is one and the key four will be here one and the key four will be here now update least frequently accessed now update least frequently accessed counter to one counter to one the next action is get call the next action is get call since key 1 does not exist return -1 since key 1 does not exist return -1 the next action is again get call the next action is again get call since key 3 is exists return its value since key 3 is exists return its value before returning its value let's update before returning its value let's update its count its count increment its count to 3 and here increment its count to 3 and here since count 3 does not have a list since count 3 does not have a list create one before moving from here to create one before moving from here to here here and the next action is again put call and the next action is again put call since key 3 already exists just update since key 3 already exists just update its value with 8. its value with 8. update the counters update the counters it is 4 since 4 count 4 does not have a it is 4 since 4 count 4 does not have a list create a list and move key 3 from list create a list and move key 3 from here to here here to here so this is how lfu cache least so this is how lfu cache least frequently used cache will be frequently used cache will be functioning hope you understood let's functioning hope you understood let's write code now write code now i have already copied method signatures i have already copied method signatures from lead code as it is from lead code as it is let's declare a hash map to hold key let's declare a hash map to hold key value page let's declare another hash map to hold now declare a hash map to hold key now declare a hash map to hold key frequency usage count frequency usage count we will be using linked hash set as a we will be using linked hash set as a value here declare a variable to hold cache declare a variable to hold least declare a variable to hold least frequently used key count at any given frequently used key count at any given point of time we have initialized its value with -1 we will fill frequency map for count 1 we will fill frequency map for count 1 with empty linked list now let's fill get function as a first step let's validate does the key exist in the cache or not written minus 1 if if it exists update counts before if it exists update counts before returning value returning value get the key usage count from counts map since we have incremented the count since we have incremented the count remove the key from the counter linked remove the key from the counter linked list from the frequency map when the current minimum count linked list is empty then it should be pointing to next count if frequency map does not have linked if frequency map does not have linked list for the given count list for the given count add it now add the key into the respective count finally return the value from cache now let's update put function simply return back if capacity value is check does the key exist or not in the check does the key exist or not in the cache update counts by simply calling git update counts by simply calling git function we will be reusing code here function we will be reusing code here get function increments the key usage get function increments the key usage count whenever required and return back in case the key does not exist then in case if it is at its max capacity in case if it is at its max capacity limits then we need to evict one of the limits then we need to evict one of the key value path so identify the head key value path so identify the head element in the linked list as per our element in the linked list as per our earlier discussion now remove the key from all possible places now insert the new key value pair into now insert the new key value pair into the caching make sure to update least frequently make sure to update least frequently used count as one as it is a new insert we are done with coding let's test our we are done with coding let's test our code i have already written main method code i have already written main method to save some time here we are making to save some time here we are making sequence of put and get calls let's run here is the output which is as expected so this is about lfu cache hope you like the video thanks for watching please do like the video and do subscribe to the channel | 2024-03-22 15:00:57 | 460 | LeetCode 460. LFU Cache | Least Frequently Used Cache Implementation | Solution Explained |
|
kNze68GYkA0 | hey hey everybody this is Larry this is day 11 of the good day challenge hit the day 11 of the good day challenge hit the like button hit the Subscribe button Jo like button hit the Subscribe button Jo the Discord let me know what you think the Discord let me know what you think about today's bar I'm in uh Ali Shan about today's bar I'm in uh Ali Shan here um watching the sun rise the sun here um watching the sun rise the sun has already risen but hopefully so will has already risen but hopefully so will your the code skills let's do this one yeah I hope you like the intro uh yeah let's do day 11 I'm here in where my chai right now uh much uh the internet should be faster so hopefully I should be getting you know I don't know whatever fast internet things anyway to F is 1287 element appearing more than 25% in sorted away all right there's exactly one okay uh yeah I mean if it's sorted then that means that uh uh that number of things in a row will um well will be the same number right so my first thought is to do a scan and then you know like like for index I you do I plus um n/4 or something like this right and of course that's still linear time so that doesn't help enough I'm curious whether you can do it in all of one I believe you should be right I don't know about one but at least log in because from the pitchon hole principle if yeah if there one if it exists in more than 25% then it has to be one of the like if you divide it into uh uh uh you know you divide and and uh can't English right now if you divid in the way of length n into four Eco components or roughly EO then then um at the border it should be then then um at the border it should be that that one of them should be uh one of those one of them should be uh one of those numbers numbers right uh and check those cuz it check those cuz it has right okay well let me let me step has right okay well let me let me step back for second I know that this is easy back for second I know that this is easy there other ways to do it that's easier there other ways to do it that's easier but I'm trying to like you know uh but I'm trying to like you know uh upsolve this a little bit let's say a upsolve this a little bit let's say a number appears in more than half the number appears in more than half the away and it's sorted right if that's the away and it's sorted right if that's the case then you know that the middle case then you know that the middle number uh has to be um the element right number uh has to be um the element right just because there's no way to put put just because there's no way to put put it so I think by the same logic by the it so I think by the same logic by the pigeon pigeon ho ho um one of those elements should be it um one of those elements should be it right so here then now we can do right so here then now we can do something something like um yeah like you have one of those three numbers which is at n by 4 uh or n no it's uh n no no yeah n by 4 this may be very pointed off by one that's why I'm a little bit worried about it but uh and then right CU those are the if you divide them into four equal parts those are the integers that could be like I said possibly off numbers and the way that you can I mean numbers and the way that you can I mean and there's a easy thing right if that and there's a easy thing right if that if one of these three numbers is true if one of these three numbers is true then you can just binary then you can just binary search um the beginning and you can search um the beginning and you can binary search the end and then you can binary search the end and then you can figure it out and that's all of log n figure it out and that's all of log n right right but can I do guess because that could be just any uh guess because that could be just any uh it could appear like you know within the it could appear like you know within the one one quarter it could be any of those one one quarter it could be any of those places right so you can't just like be places right so you can't just like be oh this is the beginning let's add oh this is the beginning let's add one let's do it that way then right so one let's do it that way then right so let's say uh and I'm not going to lie you know I'm uh and I'm not going to lie you know I'm experimenting so as a result this may be experimenting so as a result this may be wrong and it may be wrong not for any wrong and it may be wrong not for any like math reasons just uh possibly all like math reasons just uh possibly all five ones uh and I'm too late and you five ones uh and I'm too late and you could like I guess add one to these so could like I guess add one to these so then now you're checking six candidates then now you're checking six candidates or something like this so you really or something like this so you really want add n minus one or something like want add n minus one or something like this so it would be like nine candidates this so it would be like nine candidates I don't know something like that if you I don't know something like that if you want to play around with it but H right so then now going do a BC left H right so then now going do a BC left right of or just find like or just right of or just find like or just account of uh X right and then that'll account of uh X right and then that'll just be bisc bicec left of X just just be bisc bicec left of X just assumes that this is in the assumes that this is in the array which it should be because we're array which it should be because we're only getting it from here right so only getting it from here right so that's is the first index and then the that's is the first index and then the last index is going to be BCT right last index is going to be BCT right right minus one of right minus one of course so then now uh might as well plus course so then now uh might as well plus one right so then now uh yeah for X in one right so then now uh yeah for X in candidates if count of X is greater than candidates if count of X is greater than equal to n/ 4 or maybe just times four equal to n/ 4 or maybe just times four for you for you know return X and then now assert for so know return X and then now assert for so it's not possible again I probably made it's not possible again I probably made it way trickier and funner more fun than it way trickier and funner more fun than it needs to be let go submit maybe it needs to be let go submit maybe there's yeah like H like I said they all there's yeah like H like I said they all possibly uh off by on why is this possibly uh off by on why is this I mean it's probably just the way I said I mean it's probably just the way I said candidates like I said uh okay uh so candidate is two three and right okay so why is this no good why right okay so why is this no good why are you no H oh more than oh okay okay this is an H oh more than oh okay okay this is an actually unrelated bug then uh this I I actually unrelated bug then uh this I I did uh 25% not okay actually that did uh 25% not okay actually that worked in theory that would have worked worked in theory that would have worked the first time if I didn't have that Eco the first time if I didn't have that Eco thing what did I do last time did I do thing what did I do last time did I do the same the same thing oh know I did some lazy thing and thing oh know I did some lazy thing and still got it wrong twiice it's kind of still got it wrong twiice it's kind of that but uh you know even I am growing that but uh you know even I am growing as an engineer but yeah as you can see as an engineer but yeah as you can see this is um two binary search and you but this is um two binary search and you but you only do it three times so it's going you only do it three times so it's going to be log in and yeah that's what I have to be log in and yeah that's what I have for this one let me know what you think for this one let me know what you think let me know if this makes sense and yeah let me know if this makes sense and yeah oh my head ler stay good stay healthy do oh my head ler stay good stay healthy do go mental health I'll see yall later and go mental health I'll see yall later and take care byebye | 2024-03-20 10:35:21 | 1,287 | 1287. Element Appearing More Than 25% In Sorted Array - Day 11/31 Leetcode December Challenge |
|
Nf7fkh_Hi_A | 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 find mode in a binary search tree and so find mode in a binary search tree and so in this problem you have the root of a in this problem you have the root of a binary search tree without duplicates binary search tree without duplicates and you want to return the mode I.E the and you want to return the mode I.E the most frequently occurring element in it most frequently occurring element in it if the tree has more than one mode if the tree has more than one mode return them in any order assume BST is return them in any order assume BST is defined as follows the left sub tree of defined as follows the left sub tree of a node contains only nodes with keys a node contains only nodes with keys less than or equal the nodes key and the less than or equal the nodes key and the right sub tree contains only nodes with right sub tree contains only nodes with keys greater than or equal to nod key keys greater than or equal to nod key both left and right sub trees must also both left and right sub trees must also be binary search trees and so what's be binary search trees and so what's weird about this problem is usually for weird about this problem is usually for almost every problem with the BST the almost every problem with the BST the BST has unique values but in this one BST has unique values but in this one you can have weird stuff like this where you can have weird stuff like this where you have repeating values so here our you have repeating values so here our mode would be two and you might think mode would be two and you might think like well I can just somehow figure out like well I can just somehow figure out a way to track like may maybe all my a way to track like may maybe all my nodes with the same values would be nodes with the same values would be right next to each other right so I'll right next to each other right so I'll have like one two two and then maybe have like one two two and then maybe I'll have like a four over here and then I'll have like a four over here and then like this might have another four and so like this might have another four and so on but the problem is this isn't on but the problem is this isn't necessarily true so you can't just like necessarily true so you can't just like keep track of two nodes next to each keep track of two nodes next to each other and that's what I actually other and that's what I actually originally tried to do and I actually originally tried to do and I actually made a problem where I would just like made a problem where I would just like check you know do I have the same node check you know do I have the same node and if I do let's increase my count and and if I do let's increase my count and so on and so the other example is for so on and so the other example is for this one with a node with just zero you this one with a node with just zero you want to return zero so here is the case want to return zero so here is the case that I got you that was weird and so that I got you that was weird and so here it is right here so let's think here it is right here so let's think about this one so like I said before you about this one so like I said before you can't really just like check for nodes can't really just like check for nodes that are right next to each other that are right next to each other because here there's a six here and because here there's a six here and there's a six here and this does still there's a six here and this does still maintain the property of like a BST maintain the property of like a BST where yeah every every node here is where yeah every every node here is bigger than two and every node here is bigger than two and every node here is less than or equal to six but they're less than or equal to six but they're not necessarily unique so the question not necessarily unique so the question is like how do I keep track of this six is like how do I keep track of this six and this six and how do I keep track of and this six and how do I keep track of this two and this two right like I can't this two and this two right like I can't just like see what values returned or just like see what values returned or something right like I can't just like something right like I can't just like return up here cuz then like how do I return up here cuz then like how do I maintain the six value and maintain all maintain the six value and maintain all these other values that seems kind of these other values that seems kind of hard and so the property we're going to hard and so the property we're going to use is no matter even if a BST is like use is no matter even if a BST is like that now obviously uh so really quick that now obviously uh so really quick and really easy solution is just either and really easy solution is just either have a hashmap or like do some kind of have a hashmap or like do some kind of traversal and get an array of all the traversal and get an array of all the values and then from there get the values and then from there get the frequencies like that's like an easy frequencies like that's like an easy problem right like you just Traverse problem right like you just Traverse every node get a hash map and then you every node get a hash map and then you know check out which key has like the know check out which key has like the biggest value so I'm not going to go biggest value so I'm not going to go over that one but for a BST even like over that one but for a BST even like this where you do have duplicate values this where you do have duplicate values there is still a property that an there is still a property that an inorder traversal will still give you inorder traversal will still give you increasing value so let's actually run increasing value so let's actually run an inorder traversal of this and see an inorder traversal of this and see what we get and then this will give us what we get and then this will give us like intuition of what to do so remember like intuition of what to do so remember in order traversal is left in order traversal is left root root right so we're going to run this right so we're going to run this traversal so we're going to start here traversal so we're going to start here so obviously left which means we go left so obviously left which means we go left left as far as possible so we will go left as far as possible so we will go here now there's nothing here so now here now there's nothing here so now we're going to so we try to go left here we're going to so we try to go left here we can't right there's a null node so we can't right there's a null node so then we will get the root so we will put then we will get the root so we will put in zero into the array now we will in zero into the array now we will recurse so this node is or actually recurse so this node is or actually we're going to do right but there is no we're going to do right but there is no node here so now we will recurse up back node here so now we will recurse up back to the two now we went left now we're to the two now we went left now we're going to get the root now we are going going to get the root now we are going to go to go right now remember we go left before right now remember we go left before getting the root so we go left there is getting the root so we go left there is nothing left here so now we're going to nothing left here so now we're going to get this value so two and then right and get this value so two and then right and there's nothing here so now we will there's nothing here so now we will recurse up here to the four we already recurse up here to the four we already went left so now let's get the root went left so now let's get the root let's recurse right now we'll go down let's recurse right now we'll go down here there is no left now let's get that here there is no left now let's get that root let's go right nothing there so now root let's go right nothing there so now we're done here recurse back up to the we're done here recurse back up to the four we're done with a four recurse back four we're done with a four recurse back up to the two we're done with two up to the two we're done with two recurse back up here and now we did the recurse back up here and now we did the left so now we'll do the root then we left so now we'll do the root then we will go right so we go left first go will go right so we go left first go left nothing root left nothing root 7 right nothing recurse back up then 7 right nothing recurse back up then here we get the root then we go right so here we get the root then we go right so left is nothing root is nine and then go left is nothing root is nine and then go right and we actually oh we wrote down right and we actually oh we wrote down the value but anyway yeah then we go the value but anyway yeah then we go right and then we recurse uh so we're right and then we recurse uh so we're done with this node so we recurse up done with this node so we recurse up we're done with this node and now we are we're done with this node and now we are done with this node so if you actually done with this node so if you actually take a look even with duplicate values take a look even with duplicate values no matter where they are for a BST and no matter where they are for a BST and we're a traversal all of our we're a traversal all of our values like all of the values that we values like all of the values that we care about are right next to each other care about are right next to each other right so all the twos are next to each right so all the twos are next to each other all the sixes are next to each other all the sixes are next to each other every number is next to each other other every number is next to each other so we're going to get some increasing so we're going to get some increasing array where all the duplicates are right array where all the duplicates are right next to each next to each other so how do we use that to our other so how do we use that to our advantage like how do we get the modes advantage like how do we get the modes in place not counting for their in place not counting for their recursive stack space so they are saying recursive stack space so they are saying like yes their recursion of a tree will like yes their recursion of a tree will be oven but not counting that that how be oven but not counting that that how do we actually get the mode without do we actually get the mode without actually storing the in veral Array or actually storing the in veral Array or hashmap and so that part we're going to hashmap and so that part we're going to use four variables and it's going to be use four variables and it's going to be really straightforward so we're going to really straightforward so we're going to have four variables so one variable is have four variables so one variable is we're going to have our result right we're going to have our result right that we're actually going to be that we're actually going to be returning we'll call this like modes returning we'll call this like modes maybe or whatever we want to call it maybe or whatever we want to call it right let's say then we have a modes right let's say then we have a modes count and this variable will count and this variable will represent represent uh actually let's let's call this like I uh actually let's let's call this like I don't want it to be uh just do this or don't want it to be uh just do this or something okay so it's going to be one something okay so it's going to be one variable but I just want it to have like variable but I just want it to have like the spell check thing so essentially the spell check thing so essentially this is going to represent the count of this is going to represent the count of every single mode in here and so for every single mode in here and so for this problem if there are multiple nodes this problem if there are multiple nodes that have the biggest value they're all that have the biggest value they're all going to have the same value right so going to have the same value right so all of these modes in here will have the all of these modes in here will have the same frequency so modes count will just same frequency so modes count will just represent like the frequency of all of represent like the frequency of all of these modes then we need two more these modes then we need two more variables we need a Curr variable so variables we need a Curr variable so let's write it down here and Cur is let's write it down here and Cur is going to represent let's call it current going to represent let's call it current so it doesn't uh give us an error so so it doesn't uh give us an error so current will be the current number we're current will be the current number we're on so we can initialize that To None to on so we can initialize that To None to start off and then we have a current start off and then we have a current count which is like the count of the count which is like the count of the number that we are on and we'll iniz number that we are on and we'll iniz this to zero okay so now we can this to zero okay so now we can basically so I'm not going to show this basically so I'm not going to show this DFS again but this is going to be the DFS again but this is going to be the way that the things are returned right way that the things are returned right so we're going to return this then this so we're going to return this then this and this then this then this then this and this then this then this then this then this right like if we just return then this right like if we just return the uh or not not even return we can the uh or not not even return we can just like when when when we like we go just like when when when we like we go left then when we do this root part uh left then when we do this root part uh that's when these values will be checked that's when these values will be checked right so essentially what what we can do right so essentially what what we can do is whenever we are at these we can is whenever we are at these we can actually uh get the values so actually I actually uh get the values so actually I I will kind of show traversal one more I will kind of show traversal one more time I guess U maybe I think what I time I guess U maybe I think what I could do is I can actually take this could do is I can actually take this picture and I can just copy it and then picture and I can just copy it and then I can delete all of this there we go I can delete all of this there we go perfect now I can paste it so we can perfect now I can paste it so we can kind of show what this traversal will kind of show what this traversal will look like one more time with these look like one more time with these things so essentially we start here and things so essentially we start here and we go left left then we go left here and we go left left then we go left here and we have nothing so then what we're going we have nothing so then what we're going to have here is we are going to take to have here is we are going to take this value now right this will be the this value now right this will be the current value and we'll say okay well if current value and we'll say okay well if this value is different than the current this value is different than the current value then let's update the current value then let's update the current value so the current is currently none value so the current is currently none so it is different so this current oops so it is different so this current oops this current will now be zero and the this current will now be zero and the current count will be one right that's current count will be one right that's like the node we're on then we'll like the node we're on then we'll obviously do this and we'll recurse back obviously do this and we'll recurse back up here and so that that's kind of how up here and so that that's kind of how the recursion will work now I'll just the recursion will work now I'll just work with these values like their work with these values like their recursion is going to be the same way recursion is going to be the same way and this value just means like we are and this value just means like we are currently at this value so we did the currently at this value so we did the zero now let's look at the two so for zero now let's look at the two so for the two what's going to happen is we're the two what's going to happen is we're going to say okay oh by the way I forgot going to say okay oh by the way I forgot one step so once we do get this current one step so once we do get this current value we're going to check is the value we're going to check is the current count greater than the nodes current count greater than the nodes count or modes count and if it is that count or modes count and if it is that means that this node is now the biggest means that this node is now the biggest occurrent node right so this zero occurs occurrent node right so this zero occurs more than every mode so mode should be more than every mode so mode should be deleted and we should have a new mode of deleted and we should have a new mode of what we have so we're going to have mode what we have so we're going to have mode zero with a count of one now zero with a count of one now let's actually move this over here so we let's actually move this over here so we don't actually need this like tree but don't actually need this like tree but we will just go through the node so we we will just go through the node so we did this one now we're going to go to did this one now we're going to go to this node so we went so and this and this node so we went so and this and this would just mean like you go down this would just mean like you go down here then you Rec curse so so this node here then you Rec curse so so this node means like you were just at the node means like you were just at the node right it's left root right so this is right it's left root right so this is this root part so for this two we're this root part so for this two we're going to say okay what's the current going to say okay what's the current node is it two no it's not it's zero so node is it two no it's not it's zero so then we need to replace zero with two then we need to replace zero with two and that means if since we have a new and that means if since we have a new current node it's going to have count current node it's going to have count one now we're going to check what's the one now we're going to check what's the mod's count it's one and our note is mod's count it's one and our note is also count one that means that this node also count one that means that this node should be added to the modes right should be added to the modes right because it has the same count as the because it has the same count as the biggest node in there so if the node if biggest node in there so if the node if the current count is equal to the modes the current count is equal to the modes count then we're just going to want to count then we're just going to want to add that node in there so we add it in add that node in there so we add it in the node then we go to this node and we the node then we go to this node and we say okay what's our current node it's say okay what's our current node it's still two so now we have to increment still two so now we have to increment the count then we're going to check is the count then we're going to check is our count greater than nodes count or our count greater than nodes count or modes count yes it is so then modes modes count yes it is so then modes count gets updated to two and because count gets updated to two and because our current count is greater than all of our current count is greater than all of these that means that these need to all these that means that these need to all get replaced so I think I should be able get replaced so I think I should be able to just delete now yeah so these just to just delete now yeah so these just all need to get replaced by this uh two all need to get replaced by this uh two oh I can't I there you oh I can't I there you go cuz essentially like if we have a go cuz essentially like if we have a bunch of numbers with frequency one and bunch of numbers with frequency one and then we get a number with frequency two then we get a number with frequency two that means that that number is bigger that means that that number is bigger than all of them so then that's our new than all of them so then that's our new mode but if it's the same as the other mode but if it's the same as the other ones then we'll just depend okay so now ones then we'll just depend okay so now we go to the four and we're going to say we go to the four and we're going to say okay well four is not two so that means okay well four is not two so that means our count should be one now and since our count should be one now and since the count is less than modes count we the count is less than modes count we don't need to do anything right this don't need to do anything right this can't this isn't one of the modes so we can't this isn't one of the modes so we go to the next number so we go to six so go to the next number so we go to six so we replace the four with six and our we replace the four with six and our count is one and since it's less than count is one and since it's less than two we don't need to do anything then two we don't need to do anything then here we will have six and our current here we will have six and our current count will be count will be two so it's the same so we need to two so it's the same so we need to actually add it to our actually add it to our modes and and then for seven it'll be modes and and then for seven it'll be count one which will won't do anything count one which will won't do anything for eight it'll be count one right eight for eight it'll be count one right eight count one and for nine it'll be count count one and for nine it'll be count one so that's kind of like the algorithm one so that's kind of like the algorithm of getting the most frequent number if of getting the most frequent number if you know all the duplicates are in order you know all the duplicates are in order you just keep track of like how many of you just keep track of like how many of the number do I have and if it's greater the number do I have and if it's greater than what I had before I will replace than what I had before I will replace that number and I'll delete this whole that number and I'll delete this whole array of modes because now this is my array of modes because now this is my most occurring element and if it's the most occurring element and if it's the same then I'll just add it to the array same then I'll just add it to the array because if I have a bunch of numbers because if I have a bunch of numbers with the same large count then I want to with the same large count then I want to just keep adding to the array so that's just keep adding to the array so that's kind of the algorithm and it's pretty kind of the algorithm and it's pretty straightforward so we can write this as straightforward so we can write this as well so if current count is greater than well so if current count is greater than modes modes count then we want to replace count then we want to replace array with Cur and update count if they are equal just add Cur to modes and the nice thing is that even if we add a number like let's say we add this six the nice thing is if there are more then then we'll just get a greater count and we'll just replace it later so it's okay to add right away like it's not going to cause an error and that's pretty much it for like the algorithm like you basically have to realize that in a in an uh inward traversal even with this tree with duplicates I know it's kind of rare to have duplicates but even with this problem with duplicates you're still going to have all of your same number right next to each other and then you can just keep track of like how many are there and by doing this by just checking the number one at a time and just only keeping track of the last number and these these four variables we keep like the minimum information we need to update our modes without actually storing this whole array right so this modes is going to be the result which we have to have obviously but then for the modes count and current and current count these are all just variables so this is this is just like three variables we're not actually storing the array so this is like a much better uh time complexity like I said also be the same but if you if you assume that the traversal is zero and you're not counting your result then this would be an o one space solution okay and so now we can code it up okay so instead of mode I'm going to call this result and I'm going to have a result count and a cur and a cur count and we're going to have a Traverse count and we're going to have a Traverse [Music] [Music] function which if there's not a node we function which if there's not a node we can just return I'm not going to check can just return I'm not going to check for for like nodes existing I'm just for for like nodes existing I'm just going to recurse to them and then we going to recurse to them and then we will go will go left and now we have to do our Logic for left and now we have to do our Logic for actually actually uh actually like getting the the get uh actually like getting the the get filling out these values so essentially filling out these values so essentially because we made these outside of the because we made these outside of the function we don't have we can't modify function we don't have we can't modify them inside the function unless we use them inside the function unless we use non-local so we're going to nonlocal non-local so we're going to nonlocal them which basically tells python like them which basically tells python like hey we have these variables we can use hey we have these variables we can use them we can modify them them we can modify them otherwise you can use a dictionary with otherwise you can use a dictionary with these keys or you can make these like these keys or you can make these like class class uh variables like self Cur class class uh variables like self Cur and so on other one on all of those work and so on other one on all of those work so now we can do our logic so if node. so now we can do our logic so if node. Val equals Cur that means that this Val equals Cur that means that this value is the same as the last one so we value is the same as the last one so we just increment C just increment C count otherwise CER equals no. Val right count otherwise CER equals no. Val right we have a new value so if we have a new we have a new value so if we have a new value the count is one and the new value value the count is one and the new value is this now we have to check if the Cur is this now we have to check if the Cur count is greater than the result count count is greater than the result count if it is that means that the count of if it is that means that the count of this is greater than all of other modes this is greater than all of other modes so all those other modes should be so all those other modes should be deleted and our result should just now deleted and our result should just now be Cur and result count equals curve be Cur and result count equals curve count now other or there's one more case count now other or there's one more case right where the Cur count equals the right where the Cur count equals the result result count and if this is the case so if the count and if this is the case so if the Cur count equals the result count that Cur count equals the result count that means that means that this node should just be added into the this node should just be added into the modes so it's going to be res. modes so it's going to be res. append L and we can then Traverse to the append L and we can then Traverse to the right side right it's left root right right side right it's left root right for inorder traversal so Traverse no for inorder traversal so Traverse no right and finally we call this function right and finally we call this function with the root and we return result see with the root and we return result see what what happens and looks like it's happens and looks like it's fine and it's pretty efficient so so for fine and it's pretty efficient so so for the time and space basically um if you the time and space basically um if you do count the stack of traversing it do count the stack of traversing it would be o of n because worst case would be o of n because worst case scenario your tree is entirely right scenario your tree is entirely right sided right where every node only has a sided right where every node only has a right child um but if you don't count right child um but if you don't count the stack it would be of one because the stack it would be of one because this is just the result so that we we this is just the result so that we we have to have this and then these are all have to have this and then these are all just uh local just uh local variables and for the variables and for the space actually so this was the space space actually so this was the space yeah this is the space um for the time yeah this is the space um for the time we do have to Traverse every single node we do have to Traverse every single node in the tree so that is in the tree so that is okay uh and yeah so that's going to be okay uh and yeah so that's going to be all for this problem hopefully this is all for this problem hopefully this is helpful definitely think the uh the helpful definitely think the uh the follow-up section where you have to do follow-up section where you have to do it in constant um space is definitely it in constant um space is definitely like not an easy problem but just like a like not an easy problem but just like a normal hash map or something would be an normal hash map or something would be an easy problem so hopefully you enjoyed easy problem so hopefully you enjoyed this one and if you did please like the this one and if you did please like the video and subscribe to the channel and video and subscribe to the channel and I'll see you in the next one thanks for I'll see you in the next one thanks for watching | 2024-03-22 15:56:39 | 501 | Find Mode in Binary Search Tree - LeetCode 501 - Python |
|
HAA8mgxlov8 | hey everyone welcome back now let's write some more neat code today so today write some more neat code today so today let's solve a pretty hard problem let's solve a pretty hard problem regular expression matching so we are regular expression matching so we are given an given an input string s and a pattern or a input string s and a pattern or a regular expression regular expression p and we want to implement regular p and we want to implement regular expression matching expression matching and these are the two special characters and these are the two special characters that we're gonna have to worry about that we're gonna have to worry about a period and a star so the stars or so a period and a star so the stars or so the period will match the period will match to any particular character and the star to any particular character and the star basically means that any character that basically means that any character that comes before it can be repeated comes before it can be repeated zero times or it can be repeated zero times or it can be repeated infinite times right so it can be infinite times right so it can be repeated as many times as it needs to be repeated as many times as it needs to be and the match or the pattern has to and the match or the pattern has to cover the entire input string so it has cover the entire input string so it has to match to match the full input string so one example the full input string so one example is let's say so these are the special is let's say so these are the special characters we worry about right the characters we worry about right the period period and the star if we don't have either of and the star if we don't have either of them then it's basically them then it's basically string matching right so we see in this string matching right so we see in this example we have example we have two a's right that's one input string two a's right that's one input string and a single a so basically do these and a single a so basically do these strings match each other they strings match each other they don't match each other so we have to don't match each other so we have to return false return false meaning that the input string s does not meaning that the input string s does not match this regular expression match this regular expression and remember it's only going to be a and remember it's only going to be a regular expression which possibly has regular expression which possibly has the star the star or possibly has the period now imagine or possibly has the period now imagine instead if our pattern instead if our pattern was a period so in that case was a period so in that case we would compare it to the string double we would compare it to the string double a and we would see that yes they do a and we would see that yes they do match because remember the period can be match because remember the period can be any character so we could any character so we could say okay we'll given this pattern this say okay we'll given this pattern this could be double a so could be double a so it would match this input string what if it would match this input string what if we were checking does it match we were checking does it match this input string a b in that case it this input string a b in that case it would also match because this period would also match because this period could then turn into a b could then turn into a b so it would be a b and these two match so it would be a b and these two match each other each other but of course if we had a period period but of course if we had a period period checking if it matches double a it checking if it matches double a it doesn't because they're not even the doesn't because they're not even the same length this has same length this has three this has two there's no way we three this has two there's no way we could put any characters for these two could put any characters for these two periods that would match periods that would match double a and what about this second double a and what about this second example let's say the input string example let's say the input string is double a and the pattern is a star is double a and the pattern is a star so what this star means is a star so what this star means is a star so a star basically means that the so a star basically means that the element that comes before element that comes before this a could be repeated multiple times this a could be repeated multiple times or zero times so or zero times so the possible strings that this pattern the possible strings that this pattern could match to could be could match to could be an empty string because this character an empty string because this character could be repeated could be repeated zero times right so empty string this zero times right so empty string this character could be repeated once character could be repeated once so a single a this character could be so a single a this character could be repeated twice repeated twice so double a this character could be so double a this character could be repeated three times so repeated three times so aaa and so on and so on right we could aaa and so on and so on right we could repeat this a infinite number of times repeat this a infinite number of times but if you take a look at our input but if you take a look at our input string we're only checking does it match string we're only checking does it match double a of course it does right we just double a of course it does right we just repeat the a repeat the a twice so in this case we return true twice so in this case we return true a third example so let's say our input a third example so let's say our input string is a b string is a b and we're checking does it match the and we're checking does it match the pattern dot star pattern dot star so basically what this dot star means is so basically what this dot star means is we could have we could have a string that's empty right repeating a string that's empty right repeating the dot zero time so empty string the dot zero time so empty string uh we could repeat the dot once so dot uh we could repeat the dot once so dot we could repeat it twice double dot we could repeat it twice double dot right and so on and so on and right and so on and so on and so let's say this right double dot is so let's say this right double dot is what we're looking for we're checking what we're looking for we're checking does does this match a b well one of the dots this match a b well one of the dots could be could be a and one of the dots could be b so that a and one of the dots could be b so that matches matches double dot so this would return true double dot so this would return true so as you can see that there's probably so as you can see that there's probably going to be a few edge cases we have to going to be a few edge cases we have to deal with right deal with right the complexity really mainly comes from the complexity really mainly comes from the star the dot isn't so difficult the star the dot isn't so difficult right right but the star makes things interesting so but the star makes things interesting so let's just try to brute force this let's let's just try to brute force this let's look at one example look at one example this example let's say this is our this example let's say this is our string s and string s and this is our pattern a star so as you this is our pattern a star so as you know the star know the star is really where the complexity comes is really where the complexity comes from so let's make a decision tree let's from so let's make a decision tree let's brute force this brute force this so this is the string we're trying to so this is the string we're trying to match to this is our pattern a star match to this is our pattern a star we know so we're first gonna look at the we know so we're first gonna look at the first a first a and then we're gonna look at the first and then we're gonna look at the first character of this now character of this now this isn't just an ordinary character this isn't just an ordinary character there's a star that comes after it so there's a star that comes after it so this could be repeated this could be repeated zero times or more times right so let's zero times or more times right so let's brute force this brute force this we know we have a choice are we gonna we know we have a choice are we gonna repeat the a repeat the a at least once or are we gonna repeat it at least once or are we gonna repeat it zero times if we repeat it zero times zero times if we repeat it zero times then we then we end up with an empty string right if we end up with an empty string right if we repeat it once repeat it once we end up with a single a now clearly we we end up with a single a now clearly we want the single want the single a because it matches this right a because it matches this right and if we decided to to have an empty and if we decided to to have an empty string meaning we want this star to string meaning we want this star to or and this character a to repeat zero or and this character a to repeat zero times then we would have to times then we would have to move to this position right and there move to this position right and there clearly clearly isn't any character here maybe there isn't any character here maybe there would be a b maybe there would be would be a b maybe there would be an a but there's clearly nothing there an a but there's clearly nothing there so this is this so this is this decision is going to stop right we decision is going to stop right we cannot go any farther cannot go any farther all we can do here is an empty string all we can do here is an empty string but it's okay because we ended up but it's okay because we ended up matching with this a when we were on matching with this a when we were on this this path right so now the character we're path right so now the character we're looking to match in the input string is looking to match in the input string is this this single a so now again we have a choice single a so now again we have a choice are we gonna repeat the star like in are we gonna repeat the star like in this this spot we repeated the star and this we spot we repeated the star and this we didn't repeat the star didn't repeat the star now again we have that choice are we now again we have that choice are we going to repeat the star or are we going to repeat the star or are we not going to repeat the star if we don't not going to repeat the star if we don't repeat the star we're going to end up repeat the star we're going to end up with a with a single a and then we're gonna have to be single a and then we're gonna have to be shifted over to this position meaning we shifted over to this position meaning we cannot use the star anymore cannot use the star anymore so we're gonna stop right this is going so we're gonna stop right this is going to be our string a single a to be our string a single a but you can see in our input our input but you can see in our input our input string was a double a string was a double a so really our other decision where we do so really our other decision where we do repeat the star at least one more time repeat the star at least one more time is gonna lead us to is gonna lead us to double a and that's good because now we double a and that's good because now we have the second a meaning we matched have the second a meaning we matched this second a right so now in reality we this second a right so now in reality we have matched have matched the input string but just to show you in the input string but just to show you in theory we could theory we could keep going we could decide not to use keep going we could decide not to use the star anymore right we would be the star anymore right we would be shifted to that position shifted to that position and in which case our ending string and in which case our ending string would just be double a or we could use would just be double a or we could use the star the star one more time meaning we'd get triple a one more time meaning we'd get triple a but then of course you can see we're but then of course you can see we're even bigger than the input string that even bigger than the input string that we wanted to match so we stop we wanted to match so we stop but we see that we did end up finding but we see that we did end up finding the results since we the results since we found the result right we found the found the result right we found the input string input string that means that these do match right so that means that these do match right so we would return we would return true because the input string matches true because the input string matches the regular expression but as you can the regular expression but as you can see see we're doing a decision tree this is not we're doing a decision tree this is not exactly going to be super efficient exactly going to be super efficient right right how many decisions are we going to have how many decisions are we going to have well any time we get to a star well any time we get to a star we're going to have two different we're going to have two different decisions how many times can we repeat decisions how many times can we repeat that decision it's going to be that decision it's going to be n where n is the input string n where n is the input string s so clearly you can tell this is not s so clearly you can tell this is not super efficient super efficient but in case you haven't noticed this is but in case you haven't noticed this is a dynamic programming problem and if we a dynamic programming problem and if we take this take this and we implement a cache then we can get and we implement a cache then we can get this time complexity down this time complexity down to n squared or in other words really to n squared or in other words really we're getting it down to we're getting it down to n times m where n is the length n times m where n is the length of the input string and m is the length of the input string and m is the length of of the pattern and this is if we do the top the pattern and this is if we do the top down down memoization with a cache we can also do memoization with a cache we can also do the actual the actual bottom up dynamic programming solution bottom up dynamic programming solution so the bottom up dynamic programming so the bottom up dynamic programming solution solution and both of these actually have the same and both of these actually have the same time time complexity so i'm going to time time complexity so i'm going to show you the top down coding solution show you the top down coding solution but once you know the top down solution but once you know the top down solution getting the bottom up full dynamic getting the bottom up full dynamic program solution program solution is not usually impossible but before is not usually impossible but before that let's look at one more example that let's look at one more example so the index i'm going to use so let's so the index i'm going to use so let's say this say this is our input string s and this is our is our input string s and this is our pattern p so i'm going to use two pattern p so i'm going to use two variables to keep track of where we are variables to keep track of where we are in each of the strings i'm going to use in each of the strings i'm going to use i to tell us where we're at in the input i to tell us where we're at in the input string i'm going to use string i'm going to use j to tell us where we're at in the j to tell us where we're at in the pattern so pattern so remember whenever we reach a character remember whenever we reach a character that has a star that comes after that has a star that comes after we have two choices so i'm going gonna we have two choices so i'm going gonna draw our decision tree draw our decision tree we have a choice to use the star we have a choice to use the star or we have a choice to not use the star or we have a choice to not use the star so in this case if we use the star so in this case if we use the star meaning we use the character at least meaning we use the character at least once we're gonna get a c right we're once we're gonna get a c right we're gonna repeat the c gonna repeat the c just once if we don't do that we're just once if we don't do that we're gonna gonna get an empty string so i'll just draw get an empty string so i'll just draw this dash for empty string now you can this dash for empty string now you can see we have a c see we have a c but the first character of our input but the first character of our input string is a string is a so really what we want to do is not use so really what we want to do is not use this c any times meaning we do not want this c any times meaning we do not want to use the star we don't want to use the star we don't want to repeat c even a single time to repeat c even a single time so the decision we want is not this so the decision we want is not this decision but this decision but this is the path that's going to lead us to is the path that's going to lead us to the correct answer the correct answer so what am i going to do with this j so what am i going to do with this j pointer i'm going to shift pointer i'm going to shift j so i'm going to shift j over here j so i'm going to shift j over here right so notice what we just did in this right so notice what we just did in this path where we do not use the path where we do not use the star right we didn't use the star what star right we didn't use the star what did we do did we do we ended up shifting j by two so we we ended up shifting j by two so we took j and then added two to it that's took j and then added two to it that's very important because any time we very important because any time we choose choose not to use the star we're gonna take our not to use the star we're gonna take our pointer where it's at and then shift it pointer where it's at and then shift it twice because we're shifting one to get twice because we're shifting one to get to the next character but also look at to the next character but also look at the star we don't want to land the star we don't want to land on the star we want to land at the next on the star we want to land at the next character character and what about pointer i are we going to and what about pointer i are we going to shift that well since we didn't use the shift that well since we didn't use the star that means we weren't star that means we weren't able to match with the character a right able to match with the character a right so actually i so actually i is going to stay exactly where it is is going to stay exactly where it is so in this decision what we did is we so in this decision what we did is we left i left i the exact same and then we took j and the exact same and then we took j and added added 2 to it and this is very important 2 to it and this is very important because this is exactly what i'm going because this is exactly what i'm going to do to do in the code so i remains the same j in the code so i remains the same j plus 2. okay so now we're still at this plus 2. okay so now we're still at this a but our j is over here so notice how a but our j is over here so notice how j right after j is a star that means j right after j is a star that means this character a can this character a can can be repeated zero times or it can be can be repeated zero times or it can be repeated one or more times repeated one or more times so again we have a decision to make so so again we have a decision to make so one decision is we use the star at least one decision is we use the star at least once the other decision is we do not use once the other decision is we do not use the star at all the star at all so if we use the star once we'll get a so if we use the star once we'll get a string of string of a if we don't use the star again we'll a if we don't use the star again we'll end up with an end up with an empty list or an empty string so empty list or an empty string so remember when we used the star over here remember when we used the star over here we got a c that didn't match the a but we got a c that didn't match the a but now we actually have now we actually have an a that exactly matches the character an a that exactly matches the character over here right over here right but what about this path right right now but what about this path right right now we have an empty string we have an empty string is this path gonna lead us to the is this path gonna lead us to the correct answer well the only way to find correct answer well the only way to find out would be to continue on this out would be to continue on this decision tree right making decisions decision tree right making decisions and stuff but i'm not going to show that and stuff but i'm not going to show that because it's going to get pretty messy because it's going to get pretty messy and you can tell by looking at the and you can tell by looking at the string since we chose this path we would string since we chose this path we would have to have to leave i as it is and we'd have to add 2 leave i as it is and we'd have to add 2 to j to j so i would stay here j would be moved so i would stay here j would be moved over here and then you see the pattern over here and then you see the pattern left at this point is just b does that left at this point is just b does that match the input string s it definitely match the input string s it definitely does not does not right so clearly this decision is not right so clearly this decision is not going to lead us to the correct answer going to lead us to the correct answer but let's look at this this is promising but let's look at this this is promising let's continue on this path so let's continue on this path so so if we end up using the star as we did so if we end up using the star as we did right now how are we going to update our right now how are we going to update our pointers well take a look at i pointers well take a look at i we matched a exactly what we wanted to we matched a exactly what we wanted to do do right so what are we going to do with i right so what are we going to do with i well we're allowed to shift it by 1 now well we're allowed to shift it by 1 now so we're going to take i and move it so we're going to take i and move it over here right we already matched over here right we already matched this character we don't really need to this character we don't really need to match it again match it again but we do need to match the remaining but we do need to match the remaining string of s string of s a and b what about j well j a and b what about j well j can stay the same because we use the can stay the same because we use the star once we repeated this star once we repeated this a once now we can continue to repeat it a once now we can continue to repeat it or we can repeat it zero times or we can repeat it zero times and we can make that decision by rem by and we can make that decision by rem by leaving leaving j exactly where it is so when we go down j exactly where it is so when we go down this path this path when we actually use the star what we're when we actually use the star what we're going to do is add one to i going to do is add one to i but leave j exactly as it is and this is but leave j exactly as it is and this is important too important too these two things are important because these two things are important because this is exactly what i'm going to do this is exactly what i'm going to do when i write the code when i write the code so since we're still at j and there's so since we're still at j and there's still is a star still is a star that comes after it we again have two that comes after it we again have two choices so we can choose again choices so we can choose again to repeat this a or we can choose to repeat this a or we can choose to not repeat the a so if we repeat the to not repeat the a so if we repeat the a a then we're gonna get the string double a then we're gonna get the string double a right right and if we choose not to repeat a then and if we choose not to repeat a then we're gonna have a single we're gonna have a single a and then meaning we're not gonna use a and then meaning we're not gonna use this anymore and then we're gonna have a this anymore and then we're gonna have a b that comes b that comes after right and you can tell a b by after right and you can tell a b by itself itself does not match the entire input string does not match the entire input string right so clearly right so clearly this is not going to be the solution but this is not going to be the solution but you can see that the new character we you can see that the new character we just added the single a just added the single a it matches exactly what we were looking it matches exactly what we were looking for another for another a right so that means we can repeat what a right so that means we can repeat what we just did we just did up here we can take this i and shift it up here we can take this i and shift it by one by one and we can leave j exactly where it is and we can leave j exactly where it is so now i is at the last character in s so now i is at the last character in s and i was shifted by one and j remained and i was shifted by one and j remained the same the same okay i'm starting to run out of space okay i'm starting to run out of space but let's see if we can finish this but let's see if we can finish this again we're at this position where star again we're at this position where star comes after right j comes after right j is over there so we have two choices we is over there so we have two choices we can can use the star or we can not use the star use the star or we can not use the star if we use the star we're going to get if we use the star we're going to get triple a triple a right and see the third a it does not right and see the third a it does not match the character that we're currently match the character that we're currently at b so clearly at b so clearly this is not going to be the decision we this is not going to be the decision we go down go down if we don't match the a then we're going if we don't match the a then we're going to end up to end up with a double a right exactly what we with a double a right exactly what we had before had before right but in this case as we usually do right but in this case as we usually do when we when we don't use the star what we're going to don't use the star what we're going to end up doing is taking i end up doing is taking i leaving it where it is because we know leaving it where it is because we know we didn't match this character right now we didn't match this character right now but we're going to take but we're going to take j and add 2 to it and since j and add 2 to it and since we add 2 to j that means we have to we add 2 to j that means we have to shift it by two so now j shift it by two so now j is going to be at the last character in is going to be at the last character in p at the b p at the b and notice how j now the character after and notice how j now the character after there's no there's no star that comes after right so we star that comes after right so we actually don't have a actually don't have a choice right now we are only checking choice right now we are only checking does the character at j this b does the character at j this b does it match the character at i this does it match the character at i this other b other b we don't have a choice because there's we don't have a choice because there's no star we're not allowed to repeat this no star we're not allowed to repeat this b b zero times or one time or three times we zero times or one time or three times we have to use it have to use it only a single time right we must use it only a single time right we must use it we're required to use this b we're required to use this b but lucky for us we have a b right here but lucky for us we have a b right here right so we don't have a choice right right so we don't have a choice right now now we're just checking do they match and we're just checking do they match and they do so they do so what we're going to do now is see that what we're going to do now is see that our string that we created with our our string that we created with our regular expression regular expression is now a a and is now a a and b right and that matches what we wanted b right and that matches what we wanted to to in the input string but it's important in the input string but it's important to note to note when we do not have a star we're when we do not have a star we're strictly checking do the characters strictly checking do the characters equal we're checking does s of i equal we're checking does s of i equal p of equal p of j and if they do equal what we're gonna j and if they do equal what we're gonna do do how are we gonna update our pointers i how are we gonna update our pointers i and j we're gonna take and j we're gonna take i add one to it and take i add one to it and take j add one to it we're going to do this j add one to it we're going to do this in the code in the code so now when you see if we take our i and so now when you see if we take our i and then then shift it over here so i'm just going to shift it over here so i'm just going to make a barrier between these two and if make a barrier between these two and if we take our j we take our j and shift it by one you see both of and shift it by one you see both of these these are out of bounds right i is out of are out of bounds right i is out of bounds bounds and j is out of bounds that's how you and j is out of bounds that's how you know we have know we have perfectly matched so really when we say perfectly matched so really when we say that that i is greater than or equal to the length i is greater than or equal to the length of s meaning it's out of bounds and of s meaning it's out of bounds and j is greater than or equal to j is greater than or equal to the length of p that's how you know they the length of p that's how you know they have matched exactly perfectly have matched exactly perfectly but my question is what if i wasn't but my question is what if i wasn't was i was still in bounds but what if j was i was still in bounds but what if j was out of bounds what if j was greater was out of bounds what if j was greater than or equal to the length of than or equal to the length of p so an example would be this let's say p so an example would be this let's say our input string was our input string was a a right that's our input string our a a right that's our input string our pattern pattern is a is just a single a right let's say is a is just a single a right let's say our our our index of i was here let's say our our index of i was here let's say our index of index of j was over here right clearly this does j was over here right clearly this does not match this is our string s this is not match this is our string s this is our pattern p our pattern p this does not match this right this does not match this right so basically if only j is out of bounds so basically if only j is out of bounds then they do not match because we still then they do not match because we still have some string have some string in the input that hasn't been matched in the input that hasn't been matched but but what if the opposite was true what if i what if the opposite was true what if i was out of bounds right i was out of bounds right i is out of bounds so i is greater than is out of bounds so i is greater than the length of the length of s but j was still in bounds what does s but j was still in bounds what does that look like that look like an example would be this let's say we an example would be this let's say we had an input of had an input of a and let's say our pattern was a and let's say our pattern was a star and b star a star and b star so let's say our index of i was shifted so let's say our index of i was shifted by one so our i by one so our i is over here and we took our j starting is over here and we took our j starting over here over here we matched the a a single time then we we matched the a a single time then we shifted our j shifted our j to be at this b character so basically to be at this b character so basically i'm asking so with our i over here and i'm asking so with our i over here and our j our j over here do these two strings match over here do these two strings match each other each other technically yes right because this b technically yes right because this b could be repeated could be repeated zero times and still match zero times and still match the input a so just because i is out of the input a so just because i is out of bounds bounds doesn't mean we have to return false but doesn't mean we have to return false but as i just showed a second ago as i just showed a second ago if the j happens to be out of bounds so if the j happens to be out of bounds so if the j if the j is out of bounds then we must return is out of bounds then we must return false i know this is probably a little false i know this is probably a little confusing with these edge cases confusing with these edge cases but i hope the examples make it clearer but i hope the examples make it clearer and i hope the code that i'm about to and i hope the code that i'm about to show you makes it even more clear show you makes it even more clear so again i'm going to do the top down so again i'm going to do the top down memoization dynamic programming solution memoization dynamic programming solution not the bottom not the bottom up i think the top down is easier to up i think the top down is easier to understand when you're first starting understand when you're first starting this problem just doing the bottom up this problem just doing the bottom up solution solution is more confusing in my opinion but we is more confusing in my opinion but we are going to do this are going to do this recursively so i'm going to do a nested recursively so i'm going to do a nested function depth first search inside function depth first search inside of our uh is match function i guess you of our uh is match function i guess you could call this backtracking or you could call this backtracking or you could call it could call it uh whatever else you wanted i'm just uh whatever else you wanted i'm just going to call it dfs going to call it dfs and we're passing in i and j which are and we're passing in i and j which are going to tell us what position we're at going to tell us what position we're at in the input string s for i and j is in the input string s for i and j is going to tell us where we're at in the going to tell us where we're at in the input string p input string p so as always with recursive functions so as always with recursive functions let's start with the base case i just let's start with the base case i just showed you that if showed you that if i is out of bounds and j is out of i is out of bounds and j is out of bounds that means we have found bounds that means we have found our solution that means we were able to our solution that means we were able to match the pattern to the string so we match the pattern to the string so we can return true can return true but as i showed you if i is not out of but as i showed you if i is not out of bounds but bounds but j is out of bounds we have some string j is out of bounds we have some string in s in s that we haven't matched and there's no that we haven't matched and there's no way we're going to be able to match it way we're going to be able to match it so we have to return so we have to return false so these are our two base cases false so these are our two base cases notice notice that given these two cases it's still that given these two cases it's still possible that possible that i could be out of bounds right i i could be out of bounds right i technically could be out of bounds technically could be out of bounds and neither of these return statements and neither of these return statements would execute right because would execute right because this needs i and j to be out of bounds this needs i and j to be out of bounds so so we would pass this and we would pass we would pass this and we would pass this and i could still be out of bounds this and i could still be out of bounds but i'm going to show you how i'm going but i'm going to show you how i'm going to handle that right now to handle that right now so the first thing we want to check is so the first thing we want to check is is there a match is there a match between the first character so between the first character so is there a match between s of i is there a match between s of i and p of j and the other thing we could and p of j and the other thing we could check check technically right p of j could have technically right p of j could have a period in that position meaning the a period in that position meaning the period matches to period matches to any character right so we have to check any character right so we have to check this or check this this or check this and since we know i could technically be and since we know i could technically be out of bounds before we even out of bounds before we even check this we have to confirm that i is check this we have to confirm that i is inbound so i is less than the length of inbound so i is less than the length of s so strictly less than not less than s so strictly less than not less than equal so equal so if these conditions are satisfied that if these conditions are satisfied that means the first character means the first character of each string matches exactly the of each string matches exactly the reason i'm putting this in a variable is reason i'm putting this in a variable is we're gonna have to repeat it a couple we're gonna have to repeat it a couple times in the following code times in the following code so the first thing i want to check is so the first thing i want to check is does the does the following character in uh the pattern following character in uh the pattern string so p string so p of j plus one does it match the star of j plus one does it match the star is it a star and the reason i'm checking is it a star and the reason i'm checking this first is because the star has the this first is because the star has the highest precedence and i'm checking j highest precedence and i'm checking j plus one because we know the pattern the plus one because we know the pattern the first character in the pattern string is first character in the pattern string is never going to be a star and since i'm never going to be a star and since i'm checking p checking p of j plus one i have to first check that of j plus one i have to first check that j plus one j plus one is inbound so i have to check that it's is inbound so i have to check that it's less than the length of less than the length of p so if this is true that means we're p so if this is true that means we're gonna have to gonna have to we're gonna have to take care of this we're gonna have to take care of this star right and star right and we remember when we encounter a star we we remember when we encounter a star we have two choices so i'm going to do a have two choices so i'm going to do a recursive call right recursive call right that first search the first choice we that first search the first choice we have have is don't use the star right if we is don't use the star right if we don't use the star we leave i as it is don't use the star we leave i as it is and we take and we take j and add two to it right that's one j and add two to it right that's one now we know we have two choices if now we know we have two choices if either of them evaluates to true either of them evaluates to true then we can return true right we're then we can return true right we're brute forcing this right now brute forcing this right now so the other decision we have is the so the other decision we have is the other decision we have other decision we have is use the star right so if we use the is use the star right so if we use the star star that means we can take i and add one to that means we can take i and add one to it it and we can leave j where it is but and we can leave j where it is but remember we can remember we can only use the star if there's a match only use the star if there's a match between between the first character right the first two the first character right the first two characters right because we only want to characters right because we only want to use the star if there happens to be a use the star if there happens to be a match match so really here we're checking if there's so really here we're checking if there's a match a match and this whole thing about this and this whole thing about this recursive call evaluates to true right recursive call evaluates to true right so i'm going to wrap this so i'm going to wrap this in parentheses so basically what i'm in parentheses so basically what i'm saying saying is these are our two choices this is one is these are our two choices this is one recursive call and this is another recursive call and this is another recursive call if either of these recursive call if either of these evaluates to true then we can return evaluates to true then we can return true and that's what i'm doing basically true and that's what i'm doing basically by putting these by putting these on the same line so i don't know the on the same line so i don't know the best way to format this best way to format this maybe this is somewhat readable maybe this is somewhat readable so if either of these is true we're so if either of these is true we're going to end up returning true if going to end up returning true if neither of them is true we're going to neither of them is true we're going to return false so this return false so this by itself this these three lines of code by itself this these three lines of code handles handles that star for us now if this isn't true that star for us now if this isn't true meaning we don't have a star meaning we don't have a star character then we're looking just for a character then we're looking just for a simple match right so we can just simple match right so we can just check if match if the two characters check if match if the two characters match match then what are we gonna do well remember then what are we gonna do well remember we can then we can then increment i by one and we can increment increment i by one and we can increment j j by one and return the result of that by one and return the result of that now if there's not a star and the now if there's not a star and the characters don't match characters don't match in that case it's simple right then we in that case it's simple right then we can just return false meaning that this can just return false meaning that this string will never match the pattern so string will never match the pattern so then we return false then we return false and this is the brute force solution and this is the brute force solution it's actually as simple it's actually as simple as that so let's let's return it and let as that so let's let's return it and let me show you how me show you how inefficient it is right now so we can inefficient it is right now so we can call our debt for search call our debt for search starting at zero in both of the strings starting at zero in both of the strings oops i had a syntax error so we had oops i had a syntax error so we had double equal over here we have to put double equal over here we have to put double double equal over here oops and one last thing equal over here oops and one last thing when you have multi-line stuff in python when you have multi-line stuff in python you have to wrap it all in parentheses you have to wrap it all in parentheses so i'm just going to wrap this entire so i'm just going to wrap this entire thing in parentheses thing in parentheses hopefully it's still readable and a hopefully it's still readable and a third bug so i don't know why i checked third bug so i don't know why i checked if j if j is out of bounds of string s when j is out of bounds of string s when j refers to the refers to the index of string p so sorry about these index of string p so sorry about these bugs bugs but okay so this time it finally worked but okay so this time it finally worked you can see it's not you can see it's not super efficient right it took about i super efficient right it took about i think this is 1.3 seconds think this is 1.3 seconds and it was 11 so we did the top we did and it was 11 so we did the top we did the brute force solution but look i the brute force solution but look i forgot to do the memoization right so forgot to do the memoization right so let's let's actually do the caching now and make actually do the caching now and make this efficient so i'm going to create a this efficient so i'm going to create a cache cache it's going to be a hash map so before we it's going to be a hash map so before we do anything do anything whenever we call this function we're whenever we call this function we're first going to check if i first going to check if i if the pair i j has already been added if the pair i j has already been added to our cache to our cache if it has then we can return it right so if it has then we can return it right so this is going to this is going to basically not have to is basically going basically not have to is basically going to take care of repeated work for us if to take care of repeated work for us if we we execute this we're not going to have to execute this we're not going to have to do all the repeated work but now we do all the repeated work but now we actually have to use this cache so actually have to use this cache so instead of returning this right away you instead of returning this right away you can see down here i'm going to actually can see down here i'm going to actually take this and add it take this and add it to the cache so at index ij to the cache so at index ij i'm going to put the value that this i'm going to put the value that this returns to returns to and after that after we add it to the and after that after we add it to the cache cache then i'm going to return it and i'm then i'm going to return it and i'm going to do the exact same thing going to do the exact same thing down here so adding this down here so adding this to the cache and then we can take this to the cache and then we can take this and return it so we're all we're doing and return it so we're all we're doing right now is caching right now is caching the work that we do so we don't have to the work that we do so we don't have to repeat it lastly down here we can repeat it lastly down here we can say in the cache add say in the cache add false and then return false so basically false and then return false so basically by just adding what by just adding what like four or five lines of code we've like four or five lines of code we've added the caching element to this added the caching element to this function it was pretty easy so taking function it was pretty easy so taking the brute force to the the brute force to the optimal solution was actually pretty optimal solution was actually pretty easy and look at the result easy and look at the result look how much faster this is 44 look how much faster this is 44 milliseconds milliseconds 81 so we actually didn't even 81 so we actually didn't even need to do the bottom up dynamic need to do the bottom up dynamic programming solution right programming solution right and this i will be honest with you is and this i will be honest with you is not the prettiest way to write this code not the prettiest way to write this code i've seen solutions that are a lot i've seen solutions that are a lot better than this but i really hope that better than this but i really hope that you you at least were able to understand what at least were able to understand what we're doing right we're doing right the the meat of the work is done the the meat of the work is done in this call right basically these in this call right basically these two lines of code are the work that two lines of code are the work that we're doing right this is where we're we're doing right this is where we're handling the star handling the star case and you can see it's actually not case and you can see it's actually not that difficult right that difficult right all we're doing is i stays the same j all we're doing is i stays the same j added two added two or i plus one j stays the same right and or i plus one j stays the same right and you you understand why we're doing it like that understand why we're doing it like that from the picture that i drew from the picture that i drew but i encourage you to do the dynamic but i encourage you to do the dynamic programming solution i'll probably programming solution i'll probably link the code for that in the link the code for that in the description and i hope this was helpful description and i hope this was helpful if you enjoyed please like and subscribe if you enjoyed please like and subscribe it supports the channel a lot it supports the channel a lot and i'll hopefully see you pretty soon | 2024-03-19 12:16:50 | 10 | Regular Expression Matching - Dynamic Programming Top-Down Memoization - Leetcode 10 |
|
QVKsdhyo3uw | hey everybody this is larry this is day 10 of the 10 of the may legal daily challenge hit the like may legal daily challenge hit the like button hit the subscribe button join me button hit the subscribe button join me on discord on discord let me know what you think about today's let me know what you think about today's problem uh let's actually scroll down problem uh let's actually scroll down you should you should say that but one thing i wanted to point say that but one thing i wanted to point out was that you may notice my out was that you may notice my on the bottom uh there's this key stroke on the bottom uh there's this key stroke uh it's just so you could see it people uh it's just so you could see it people sometimes ask me sometimes ask me what i type uh usually you see most of what i type uh usually you see most of it because it's on the web browser but it because it's on the web browser but just so you know anyway today's problem just so you know anyway today's problem is count primes is count primes and as usual i do softies live so and as usual i do softies live so if it's a little bit slow you know skip if it's a little bit slow you know skip ahead watch on 2x do whatever you need ahead watch on 2x do whatever you need to do to do okay so counting number prime numbers okay so counting number prime numbers less than a non-negative number less than a non-negative number well they're eight hints what is going well they're eight hints what is going on here um on here um i'll say this one it's a little bit i'll say this one it's a little bit weird because weird because it goes to five to ten to six so the it goes to five to ten to six so the ideal way to do it is just to ideal way to do it is just to do it once and then use the same do it once and then use the same [Music] [Music] code pre-cached answer in all your your code pre-cached answer in all your your tests but tests but maybe some i'm just not always easy um maybe some i'm just not always easy um and because of this and because of this and the running time on the code and and the running time on the code and stuff like that is a little bit awkward stuff like that is a little bit awkward but do but do i was it five times ten to six i was it five times ten to six was that five million was that five million wow that's that's actually kind of hard wow that's that's actually kind of hard um that's a lot of things to store in um that's a lot of things to store in memory memory uh usually i would say uh usually i would say yeah i mean but the standard way of yeah i mean but the standard way of doing this is doing this is just gonna be prime stiff uh just gonna be prime stiff uh i always i don't ever start do this i always i don't ever start do this i'm probably saying it incorrectly but i'm probably saying it incorrectly but that's just a safe that's just a safe um let's see try to think um let's see try to think why is this end so large i might why is this end so large i might actually run out of time actually run out of time even if i do the sieve most of the time even if i do the sieve most of the time i'm gonna take a look at some hints just i'm gonna take a look at some hints just to see what they to see what they what they're because i mean could why i what they're because i mean could why i say that is that because i say that is that because i actually know i mean some of it is that actually know i mean some of it is that this is just a little bit of a mind this is just a little bit of a mind reading reading i don't think this test case is gonna be i don't think this test case is gonna be that complete but the test cases they that complete but the test cases they give you it's give you it's it's a little bit of a guessing game of it's a little bit of a guessing game of how because how because because you can imagine that if i do because you can imagine that if i do something that goes to five times ten to something that goes to five times ten to the six the six but you know um but you know um if there are 100 cases on that it's if there are 100 cases on that it's going to time out no matter what going to time out no matter what so that's basically what i'm i'm saying so that's basically what i'm i'm saying and i'm going to take a small hint and i'm going to take a small hint and knowing that okay this is just this and knowing that okay this is just this is not a small hand this is the sif is not a small hand this is the sif and this is what i was talking about and this is what i was talking about with okay fine with okay fine i i mean i know how to do it so i'm not i i mean i know how to do it so i'm not gonna look at it that much i just gonna look at it that much i just thought that there'll be a smaller hint thought that there'll be a smaller hint to be honest but uh but yeah that's to be honest but uh but yeah that's that's implemented the dumb way and then that's implemented the dumb way and then we'll see if we can we'll see if we can or we have to implement it there's uh a or we have to implement it there's uh a smaller way so yeah let's just say smaller way so yeah let's just say primes is equal to force times primes is equal to force times was it n plus one for n inclusive yeah not negative numbers n right less than okay yeah less than so we can just do n and then prime you know it's just four oh actually technically this is all true oh actually technically this is all true whoops uh we said primes whoops uh we said primes of zero is equal to the primes of one is of zero is equal to the primes of one is equal to fours equal to fours and then now we start by just for x and and then now we start by just for x and range sub range sub and i guess oh n plus one well it doesn't really matter i guess but uh if prime sub x i guess this actually doesn't matter because this is not inclusive for some reason if this is a prime then you go out and you keep on doing it until it is not right so i is equal to x while i i is less than n i'm gonna do it a little bit i mean so i'm gonna do it a little bit i mean so there's a there's a technically you start with two times x technically you start with two times x but you can do some but you can do some proofs to yourself that this is good and proofs to yourself that this is good and technically you're supposed to do this technically you're supposed to do this but i think you can also just do this but i think you can also just do this oops um for reasons that you can maybe oops um for reasons that you can maybe do the math one do the math one um because every other pro number is um because every other pro number is gonna be multiplied by two but i'm just gonna be multiplied by two but i'm just gonna keep it simple for now uh yeah and then now just return i'll do it forget how to do uh i'll do it forget how to do uh whatever yeah let's just do a follow-up whatever yeah let's just do a follow-up oh i guess i could just check it here as oh i guess i could just check it here as well well count zero zero and let's start this at count zero zero and let's start this at 2 by the way 2 by the way [Music] [Music] what are the test cases it's 10 0 1 what are the test cases it's 10 0 1 and what is it five two three four five and what is it five two three four five seven oh whoops oh okay obviously this is true and return zero and return zero i think that's the only case now that looks good um i'm going to just now that looks good um i'm going to just check one case just make sure that it's check one case just make sure that it's less than strictly which is if you give less than strictly which is if you give it a prime because i think it a prime because i think that was a little bit un unclear in this that was a little bit un unclear in this problem problem uh so okay so it is good because it's uh so okay so it is good because it's two three five two three five so let's give it a submit there may be so let's give it a submit there may be micro optimizations here but we'll see micro optimizations here but we'll see how fast that goes how fast that goes okay so this is accepted like i said uh okay so this is accepted like i said uh the problem with leak code is that they the problem with leak code is that they don't tell you how many don't tell you how many test cases they give you so test cases they give you so and but the tle is based off the sum of and but the tle is based off the sum of those test cases right so it's a little those test cases right so it's a little bit clearer that by this constraint bit clearer that by this constraint is sufficient that it's gonna be fast is sufficient that it's gonna be fast enough but turns out that the sip is enough but turns out that the sip is fast enough fast enough um you want to read up on it i guess um you want to read up on it i guess look at look at uh yeah hint eight which is a little bit uh yeah hint eight which is a little bit too much of a hint too much of a hint but i guess it's in eight i was just too but i guess it's in eight i was just too lazy yeah so look up say if this is lazy yeah so look up say if this is going to be going to be of n space and o of n log log and time of n space and o of n log log and time um the proof is there i'm not gonna go um the proof is there i'm not gonna go over too much um you can over too much um you can you know do summation and this is uh you know do summation and this is uh for competitive this is definitely for competitive this is definitely important and well known and something important and well known and something that you should know that you should know um but but for interviews i don't um but but for interviews i don't i can't imagine number theory comes up i can't imagine number theory comes up that much so that much so i wouldn't worry about it that much uh i wouldn't worry about it that much uh but but it's hard to say but you know i'm just it's hard to say but you know i'm just saying that if you have other things to saying that if you have other things to prioritize then prioritize other things prioritize then prioritize other things but otherwise but otherwise yeah uh that's all i have for this yeah uh that's all i have for this problem let me know what you think problem let me know what you think let me know what you think about the let me know what you think about the typing thingy bye typing thingy bye anyway uh yes so yeah have a great rest anyway uh yes so yeah have a great rest of the week of the week it's monday hit the like button hit the it's monday hit the like button hit the subscribe button join me on discord subscribe button join me on discord and stay good stay healthy and i'll see and stay good stay healthy and i'll see you tomorrow you tomorrow bye bye | 2024-03-22 09:50:53 | 204 | 204. Count Primes - Day 10/31 Leetcode May Challenge |
|
fyw8P3UwRBU | hey hey everybody this is larry this is day 26 of the august lego daily day 26 of the august lego daily challenge hit the like button hit the challenge 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 me know what you think about today's farm my internet's been kind of bad so farm my internet's been kind of bad so this video may be a little bit weird this video may be a little bit weird because i am recording it live so if because i am recording it live so if if it does get bad just fast forward or if it does get bad just fast forward or watch it on the fastest speed anyway watch it on the fastest speed anyway okay okay so what if i pre-order so what if i pre-order is to pre-order traversal you is to pre-order traversal you uh you record the notes value otherwise uh you record the notes value otherwise we call it a sentinel we call it a sentinel okay okay for example for example return true if it is a correct return true if it is a correct pre-ordered stress of a binary tree pre-ordered stress of a binary tree is guaranteed that okay so you're given is guaranteed that okay so you're given this pre-order e thing oh you're not allowed to reconstruct the tree that's a little bit awkward um why why what would be a force situation okay so basically you just have to consume everything okay yeah i mean i think this is pretty yeah i mean i think this is pretty okay you just have to do the recursion okay you just have to do the recursion and do it that way and the thing with and do it that way and the thing with pre-order is that pre-order is that it just means that for every it just means that for every node there's two corresponding um node there's two corresponding um children children but it's a little bit awkward the way but it's a little bit awkward the way that i have to figure out how to that i have to figure out how to because the way that i usually do this because the way that i usually do this or thinking about it is to use side or thinking about it is to use side effects effects but maybe there's a better way to handle but maybe there's a better way to handle this um this um yeah but basically yeah but basically you can just have like an index is equal you can just have like an index is equal to zero to zero and is equal to the length of the and is equal to the length of the pre-order pre-order and then now we just have a pre-order and then now we just have a pre-order uh uh okay okay let's just convert this to let's just convert this to the tree maybe the tree maybe so then because i like my function name so then because i like my function name being pre-order makes more sense but being pre-order makes more sense but yeah but given a node yeah but given a node so okay wait what what do i want to return here what do i want to return here well what is an input maybe that's a well what is an input maybe that's a little bit awkward but okay little bit awkward but okay but but oh yeah um oh yeah um no this is wrong obviously actually no this is wrong obviously actually so let's just call it this so let's just call it this tree tree naming things are solid for me naming things are solid for me but but but we'll just but we'll just ignore the fact that that's the case and ignore the fact that that's the case and uh and do this for now uh and do this for now um yeah i think that's okay um yeah i think that's okay so basically the value don't doesn't so basically the value don't doesn't even matter because it doesn't have to even matter because it doesn't have to be a binary search tree anything just a be a binary search tree anything just a regular binary tree so in that case i regular binary tree so in that case i don't even have to care about the don't even have to care about the contents contents uh uh just uh we just uh we care about the content care about the content long enough to know that it is a long enough to know that it is a a dollar sign of hashtag or whatever or a dollar sign of hashtag or whatever or not so okay so if if index is bigger than and then then this is no good return so now we have some good is return so now we have some good is either true maybe i'm not sold on this either true maybe i'm not sold on this quite yet this is quite yet this is this is way ad hoc and this is way ad hoc and [Music] [Music] whatever but yeah but if tree of index whatever but yeah but if tree of index is equal to is equal to uh uh then we we then we we just kind of return because then that just kind of return because then that means that this number is good um maybe means that this number is good um maybe on i'm trying to think whether it makes i'm trying to think whether it makes sense to increment the index here or sense to increment the index here or afterwards because i guess here doesn't afterwards because i guess here doesn't really really make sense either make sense either so i guess we'll just do it here so so i guess we'll just do it here so then we go to the next character else then we go to the next character else it's just a number then we go pre-order it's just a number then we go pre-order pre-order kind of and then return pre-order kind of and then return um um something like that but we have to something like that but we have to figure out how to do the index so then figure out how to do the index so then we consume the index so we index first we consume the index so we index first as the pre-order and then we do the net as the pre-order and then we do the net the left and then the right yeah i think this should be good maybe so now we do a pre-order and then we return good um we have to do some non-local index here as well i think this should be good but i am not as confident as i am usually so let's give it some testing give it some love oh i i am wrong on this by the way this case for example i think i'm wrong and again now i seem to be running into some internet tech it's been bad internet all day it's been bad internet all day um okay so i know that i usually say i um okay so i know that i usually say i don't cut away but there's actually not don't cut away but there's actually not well i guess actually i could improve well i guess actually i could improve the code because i know that this is the code because i know that this is wrong wrong but i might uh but i might uh cut out for a second cut out for a second because this is really stupid because this is really stupid uh uh what year do i live in living in new what year do i live in living in new york city york city okay okay uh oh yeah so i think we just have to uh oh yeah so i think we just have to return good and index is equal to return good and index is equal to and and [Music] [Music] because if index is not equal to n that because if index is not equal to n that means yeah if index is not equal to n then that means that we're either short which is in this case um or i guess if it's going over it good is already false so so yes i think this should be uh definitely more accurate a little bit more confident again i am having difficult uh internet connections i logged in i had um it was good for about five minutes of the last like two three hours so just long enough for me to start this video but not long enough for me to submit okay so i'm i mean you could stay i'm gonna this is one of the rare times i will edit away because you can see that literally my internet is having technical difficulties so yeah hey welcome back and i'm back i guess if i didn't do much but okay so now i'm able to run the code so it looks okay here um i probably am okay let's actually write a few more test cases like an empty one uh do do one two three no whatever okay one two three no whatever okay and let's give it another spin and let's give it another spin oh oh i hope this this internet stays up long i hope this this internet stays up long enough for me to submit so this looks enough for me to submit so this looks good i'm confident or i don't know if good i'm confident or i don't know if i'm confident my internet is having i'm confident my internet is having issues so let me just give this except issues so let me just give this except okay so it is an except yay okay so it is an except yay um um yeah so we look at each character slash yeah so we look at each character slash node if you want to call it that at most node if you want to call it that at most one so this is going to be linear time one so this is going to be linear time in terms of space this is going to be uh in terms of space this is going to be uh of h space where h is the height of the of h space where h is the height of the proposed tree because that's just the proposed tree because that's just the cost of the stack even if with no cost of the stack even if with no parameters there you do create some or parameters there you do create some or you do use some stack space so yeah so you do use some stack space so yeah so linear time of h space linear time of h space um um yeah i i don't like the side effect to yeah i i don't like the side effect to be honest of be honest of but i think that's how i i generally do but i think that's how i i generally do it maybe i have to do some learning it maybe i have to do some learning about um about um learning about how to write this in a learning about how to write this in a cleaner way so yeah so even you know cleaner way so yeah so even you know just because you get it accepted doesn't just because you get it accepted doesn't mean you can't improve the code and in mean you can't improve the code and in fact for me sometimes that i even do i fact for me sometimes that i even do i aim to do that afterwards because it aim to do that afterwards because it helps me to you know already have a base helps me to you know already have a base of what of what what is you know what what what is you know what what like i know what works so then i can like i know what works so then i can work to iterate on that um sometimes work to iterate on that um sometimes especially now that i know what i want especially now that i know what i want to express but yeah um to express but yeah um that's what i have for this one let me that's what i have for this one let me know what you think apologies for the know what you think apologies for the internet and weird cuts internet and weird cuts i'll talk to you later stay good stay i'll talk to you later stay good stay healthy to good mental health i'll see healthy to good mental health i'll see you later bye bye | 2024-03-24 10:40:56 | 331 | 331. Verify Preorder Serialization of a Binary Tree - Day 26/31 Leetcode August Challenge |
|
OCUq9tsiFR4 | hi hello today we will talk another binary search today we will talk another binary search question question find minimum in rotated sorted array 2. find minimum in rotated sorted array 2. let's see what this question is all let's see what this question is all about about all right so this question provide us a all right so this question provide us a rotated sorted array rotated sorted array and we had to find a min element from it and we had to find a min element from it with an extra condition that it hasn't with an extra condition that it hasn't it can have duplicates it can have duplicates i have write few examples here i have write few examples here in this case you can see it is rotated in this case you can see it is rotated and six is repeated and six is repeated in this case one is repeated in this case one is repeated and here one is repeated in more it can be other elements too it's not only one or one element that can have multiple elements which can be repeated so how we will solve this question the first thing we will look at it is look at these two points the first that it is a sorted array and we have to find main element considering these two conditions for sure we will try to look at bunny search but in this bunny search again we will use advanced by search because we will make some change and then we can solve this question easily considering these three examples here we can see what happened we will take the left pointer here we will take right here and in the middle now when we will see that we will then we will try to find as i discussed in the previous example uh the part one where we are mostly interested in this area which is the rotation point where actually it start rotating because there we can find this mean element in all examples here so in the first example if we will look at so what it's saying when we when we find mid we will ask this question this is mid is greater than this end if it is then me then this dropping point and this rotation point is in between some some place of mid and end then we will do the binary search accordingly and in the second example if you will see we will take the left pointer we take the right pointer and then we take the mid in this case uh when we ask this question that is this mid is greater than and so it is not then we will ask that does mid is less than end just to confirm where we are right now is sorted if it is sorted in that case we will either look here so when we are looking when we are saying mid is less than end then we are saying start looking here in the last example which is little trickier we will be left here we'll take right pointer here the midpointer will be at some place here now we will ask the question that does mid is greater than end mid is greater than and no is made less than end yes we will move here in that case it this will become four five one one one one two three again we'll take left pointer right pointer will come here because we start looking into this side of that side because mid was less so we start looking into this area and mid will go somewhere here now that now in that case this mid is becoming greater than and then we start looking here because this condition starts satisfying so we say mid is greater than and then yes it is then we start looking in this area so in this area for sure then our example will become like 4 five one one one one two three and we will move the pointer we'll save it goes here and will remain on its place mid will come here now in this condition you can see mid and end this become equal and once they are equal so what we will do we will say okay the end point you should come one step back so we will keep start here and we will ask and you should come one step back so we will do e minus one and so that we can come out of this duplication area step by step one by one because when we are in some uh duplication area it's it's not telling us some direction that either we have to look here or we have to look here in which direction so we we go one step one step one step to come out of this situation so in this case when we will use a binary search we can find our we can find the main let's see in the code how we can solve this welcome back so as we already know that we have to use binary search to solve this question i will do we'll call binary search function we will say here we are that's the first index will be on zero the last index will be on at the end and we can write this method here f b s left pointer is here right will be an end and we are expecting it will return as min so what will how we can solve this first we will simply ask we will say if left is greater than equal to right if it is we are in the base condition and we can return nums at left otherwise if it is not we can do actual the binary search here so we will save wall mid will be left plus right minus left divided by two when you find the mid we will say if nums at now we are asking the question that is the right side is sorted or no so we will say if nums at mid is greater than nums at and sorry right so in that case we were asked we are saying the number at the middle is greater than the number on the right so the rotation point is in between mid and right so we will start looking into mid and right so we'll say mid because mid is already greater than nums right so for sure that won't be uh our minimum number so we will go min plus mid plus one and we will go with the right else if it is not the case so we will say else if nums at mid is less than so if it is not greater than so we will ask is it less than right so if you'll say yes it is less than right so here in some sorted array where mid is less than the right then for sure we will try to look into the other side which is uh binary search from the start to you know i'll say restart it's left to now in the else part when we never find now in the else part when we never find so for sure that nums at mid is equal to so for sure that nums at mid is equal to numbers that right if all these two numbers that right if all these two conditions don't satisfy conditions don't satisfy so in that case we were in so in that case we were in some area where mid and right or some area where mid and right or duplicates so we can go with the duplicates so we can go with the binaural and here we can say left and we binaural and here we can say left and we will go will go right minus one right minus one now that's it we we keep on doing that now that's it we we keep on doing that and with this by search we'll find our and with this by search we'll find our minimum number minimum number let's run the code and it works thanks | 2024-03-21 13:22:42 | 154 | 7. Binary Search | Leetcode | 154 | Find Minimum in Rotated Sorted Array II |
|
EkJ2Us1DowA | Guys Welcome To Questions Today's Question Attacking In Speed This Question That Bihar Invoice Jaaye Zero Point Teams Undertaking Can Make This MSG Been Present Condition Not Given Date Attacking In This Question Teams On Standing Time Series Two Words Essay And Deposit Time Tuition That you need to put a total time till acidity point condition zoom zoom that teams takes it very beginning of this specific time point and make such bean present condition immediately let's understand this are timely active voice and devotion and devotion To cash withdrawal To cash withdrawal To cash withdrawal lineage giving trucks and again to lineage giving trucks and again to represent the time duration in which will represent the time duration in which will win in which will be in this printing off subscribe pimples that now young man youth floor and devotion 9 times from amazon time time time at which will give a good practice representative And for it means the taste one should stop And for it means the taste one should stop And for it means the taste one should stop vande giving the acid staff or the vande giving the acid staff or the giving acid keep and duration represents giving acid keep and duration represents effect illegal drug women sc dot in the giving its difficult effect illegal drug women sc dot in the giving its difficult one unit improve one unit improve effective deslast 30 deslast 365 days hello hi Made Made Made Things Better But This Happening At Unit Now I Things Better But This Happening At Unit Now I 'm Telling That I'm Explaining 'm Telling That I'm Explaining Using Debit Hindi Hindi Solution Can Using Debit Hindi Hindi Solution Can Not Go Into From Any Are Available In Your Not Go Into From Any Are Available In Your Letter How Does The Self Work Swayam Using Letter How Does The Self Work Swayam Using React Reaction Fenugreek Clear Tube Narao React Reaction Fenugreek Clear Tube Narao Which Represents A Timed Sure Which Represents A Timed Sure Detergent Unit Sunao Tips For Death Was Given To Add Detergent Unit Sunao Tips For Death Was Given To Add First Unit Distance From First Unit Distance From 0215 Was Not Arg 2009 Truck 20000 0215 Was Not Arg 2009 Truck 20000 Representatives Not Present In Every Person Does Representatives Not Present In Every Person Does Not Present At The Not Present At The And Sunao Hindi Are Vacancy 80 For And Sunao Hindi Are Vacancy 80 For Students Were Giving Effect To Share So And When Will Students Were Giving Effect To Share So And When Will Ra Ra Ra dentist third unit som words will see is deep active one second only one and only som one that at one wear giving back to such supreme one two 20 for a point nine from 2323 why this factor of women from pintu unit certificate unit and This Deep Treatment Depend Trimming Will Be 13816 Handsfree Unit Vacancy Date From Which 13816 Handsfree Unit Vacancy Date From Which Government Hospitals And Saw Three Government Hospitals And Saw Three Unit Not Giving Any Other Drugs Unit Not Giving Any Other Drugs If Such Person Minute Fourth Unit If Such Person Minute Fourth Unit Certificate Such Will Not Present At That Certificate Such Will Not Present At That Now Something To Forensibly Now Something To Forensibly Now Something To Forensibly hai dekho chief represented 10940 giving acid talk and laugh tuition 209 front four to five faces of devotion in the equipment poles and now not afraid at all song devotion and you should not do any one unit operation authority at so such a possible deposit a Vacancies after becoming a great Vacancies after becoming a great Vacancies after becoming a great fortune it is deposited present poisoning fortune it is deposited present poisoning effect continues till security question effect continues till security question and 2000s that total time in which she was and 2000s that total time in which she was present for physical to front of all given in this present for physical to front of all given in this regards for this regards for this that no one has Madan Singh died when not wanted to that no one has Madan Singh died when not wanted to family family family Things More Clear I Am Using Key Address Format Will Tell You This Solution Later And Please Avoid To Understand No In This Question Answers Come To 4 For The Time Roshan's Method To Increase Such Daily Point Knowledge Loaded To but what is this fennel To but what is this fennel To but what is this fennel represents one and to it means represents one and to it means festivals and tagged one second first festivals and tagged one second first unit android urination and excretion unit android urination and excretion of drug inspector August 2018 201 unit is not considered this government one unit show is not considered this government one unit show from and emotions to show the factors now from and emotions to show the factors now last from one last from one last from one One Second Supreme One Two 50% Now Under the Under the top two drops 1518 for students top two drops 1518 for students and mid doing only from devotion duration and mid doing only from devotion duration of two three under the influence of of two three under the influence of tourists in this world but not be tourists in this world but not be considered effective work with that that considered effective work with that that show come to three only show come to three only 10 days poles and spirit will not option 10 days poles and spirit will not option 250 250 from 212 from 212 from 212 years but will consider only day prince of conduct software beans 1234 answer one so 98 third second david vinod deficit which gives what is over thirty subscribe 2012 subscribe 2012 1000 minutes second 1000 minutes second 1000 minutes second Treatment For Sweet Sweet Dish Times Beneficial Than Three To Four Seats Under The Influence Of A Cylinder Day Prince Of Wales Is Conduct Show Any Special Soft Hanging Is Drug Ko Hai Sonth Ek Cheez Ban Now To To To Will And Asked For Will And Asked For That Bigg Boss Season Audition Is To Only For That Bigg Boss Season Audition Is To Only For 10 To Be Are Answer Bhi Kam 2008 10 To Be Are Answer Bhi Kam 2008 With The Message That Total Time At Which Schedule With The Message That Total Time At Which Schedule Call Day That Is Equal To Call Day That Is Equal To Three Seconds Sudhir Choudhary And Tire Three Seconds Sudhir Choudhary And Tire Examples Of This Examples Of This Examples Of This Formed During 20 20 Times Bsc In The Night Increase Drug New Delhi Rajdhani Rectangle Index - Drugs - New Delhi Rajdhani Rectangle Index - Drugs - Time Admission Graph - One Who Has Given When Any Time Admission Graph - One Who Has Given When Any Differences With Celebration At This Differences With Celebration At This For - For - For - With Lord Vishnu But I - Banat Second Day Which Given Youth Second Will Have Its Effect On Forest Date Means Minister Was Given That When It Was Given At One Second Saini One Second Saini Binti Effective Dashrath Blast Same Flat Binti Effective Dashrath Blast Same Flat Settle Two Settle Two New Delhi Only New Delhi Only New Delhi Only labs under the influence of only destructive one does she will repeat my flight mode settings from c timestamp of ias - 575 minus one is better than edition dated 4th - 3 and united nation in the scripters which was given and unique id - Once in next bill it is its effects to the fullest that Reddy Bandhu at one second will it will be only in saffron speed will only in flats such bindi third second third unit in the third desert festival only under the Drugs Drugs Drugs given in this time period given in this time period according to countryman's Swarna IA Times according to countryman's Swarna IA Times - Yuvan Ras Timestamp is greater than or - Yuvan Ras Timestamp is greater than or equal duration Know what is what is chief equal duration Know what is what is chief Timestamp - CIMS Word Timestamp Timestamp - CIMS Word Timestamp is not to be reduced to 100 is not to be reduced to 100 Jai Hind is Presidency Overlapping is Happening Jai Hind is Presidency Overlapping is Happening Show overlapping is happening sudhir Show overlapping is happening sudhir then a particular interval acid under the then a particular interval acid under the influence of two all models in this case in influence of two all models in this case in 2223 edison electronic under the 2223 edison electronic under the influence of two and mode rakh will consider only influence of two and mode rakh will consider only one day difference of two different white one day difference of two different white times - york times timestamp lets times - york times timestamp lets 110cc condition 110cc condition 110cc condition One is great benefit devotion of drug day well a day in the RMM drugs and you will have its effect on the police and will depend on a legitimate agent I donation will give and a legitimate agent I donation will give and celebration of decide twitter account celebration of decide twitter account that and when that and when that and when Not Greater Than Two Years Back In This Case Some Will Happen How To Weiler Friend Show Installed App I - Hair Oil - 110 012 Seconds X2 Settings Off Key New Dress But From One To Second Only wonder ladies duct is Only wonder ladies duct is Only wonder ladies duct is so English's will our will and share - so English's will our will and share - share - one so this point and then approach this question share - one so this point and then approach this question 9 Lucrative 9 Lucrative Codification Sunao Avoid Andar Code Already Know Codification Sunao Avoid Andar Code Already Know Electronic Code Line By Line For Electronic Code Line By Line For Cheap Ask This Banner Times Are This Cheap Ask This Banner Times Are This Style Se 0.5 Style Se 0.5 Style Se 0.5 in the point to the time series will start alarm equal to one Szechuan equal to one day disposal years back to sea warehouse youth is all value and note Sudhir will come from abroad in icon 212 i - times of - 1st i - times of - 1st i - times of - 1st edition addition in this is what will happen edition addition in this is what will happen or account classification means or account classification means a date and time only i is - time saif a date and time only i is - time saif first world immigration it means the 20.18 first world immigration it means the 20.18 dish valued at this time saif - 1the dish valued at this time saif - 1the effect of effect pause until maximized effect of effect pause until maximized A dentist in this kc banner banner drug 181 and against 40 minutes for the first don't have already completed in time duration sudhir for in this case will adaptive account plus equal to a nation will add 2.2 reaction to account mails valentines i - - One is not regret at the - One is not regret at the - One is not regret at the invitation like this invitation like this how to minus one so divine will be lit will be how to minus one so divine will be lit will be hair oil - Yuvan Big Boss hair oil - Yuvan Big Boss Which set up due point which gives Which set up due point which gives wealth will remain in only till debt point one wealth will remain in only till debt point one second charges not given second charges not given second charges not given For One To Three Second Minute It's Women Only Words Related To Women In Fact One And After That She Controls Given So Second Rottweiler Bar First Time Sudhir Will Add Value Of Controversy Over Time Series After Up What Will Happen Up What Will Happen Up What Will Happen Account Bestows Liberation Of Account Bestows Liberation Of The The Ko Bhi Roshan Admit Char Aisi Is Important Ko Bhi Roshan Admit Char Aisi Is Important Mode But See That This Vansh Lecture Detail Loot Value In Account Divya Account Will Be Only For -1.2 Only E Hai But Gilas Dravid Timestamp Admission Neighbor Come Into Power Shoaib Will Develop Neighbor Come Into Power Shoaib Will Develop Neighbor Come Into Power Shoaib Will Develop Depression Again For The Depression Again For The Last Timestamp Account Blood Circulation Last Timestamp Account Blood Circulation Exam Exam Bigg Boss 100 Deal-Points 210 In 2001 Bigg Boss 100 Deal-Points 210 In 2001 Last Date Which Was Guilty Last Time Last Date Which Was Guilty Last Time Stamp Which Gave There Last Time Stand Will Have Its Stamp Which Gave There Last Time Stand Will Have Its Effect On The Fullest Effect On The Fullest Effect On The Fullest gyan up and celebration in account siddhi indian vitamin e count and walnut time e weighted setting accepted commission ne district e weighted setting accepted commission ne district is the video thank you a | 2024-03-18 11:22:18 | 495 | Teemo Attacking Leetcode | Leetcode 495 | LeetCode September Challenge |
|
BoivnDkWoVU | uh hey hey everybody this is larry this is is q1 of the recent only contest you'll see q1 of the recent only contest you'll see me try to do it live and i gotta mess it me try to do it live and i gotta mess it up a little bit up a little bit but that but for this problem you're but that but for this problem you're trying to figure out the count of odd trying to figure out the count of odd numbers between low and high inclusive numbers between low and high inclusive uh and the user's way to do that uh and the user's way to do that is just by by um is just by by um case enumeration i think but so low and case enumeration i think but so low and high could only be odds and events uh high could only be odds and events uh just just just you know do the math and make sure just you know do the math and make sure you get it right you get it right uh i think that's kind of the idea uh i think that's kind of the idea behind it basically behind it basically if high is a odd number if high is a odd number um then that there's high or plus one over two numbers that are smaller than an odd number and then you just want to subtract from uh the same thing from the lower case uh yeah and now you can watch me cyber live during the contest where i hmm oh my let's see this is trickier than i thought | 2024-03-21 11:28:33 | 1,523 | 1523. Count Odd Numbers in an Interval Range (Leetcode Easy) |
|
XhF2mbzhYCo | hey guys I'm in this video we show see another problem partition array into another problem partition array into three parts with equal sum so given three parts with equal sum so given array of integers return return to if array of integers return return to if you can partition AR into three non you can partition AR into three non empty Parts with equal sums so question empty Parts with equal sums so question say says the given an array of say says the given an array of integers and we should check that if we integers and we should check that if we are able to partition the array are able to partition the array with into three partitions such that the with into three partitions such that the sums are equal in each partition so each sums are equal in each partition so each partition mean some of the numbers partition mean some of the numbers integers in the each partition should be integers in the each partition should be equal to some of the numbers in other equal to some of the numbers in other partitions as well that is what we need partitions as well that is what we need to check here and one more thing is they to check here and one more thing is they not told like exactly three it can there not told like exactly three it can there can be more than three partition with can be more than three partition with equal um number but minimum three is equal um number but minimum three is must must so let's see this example okay if we so let's see this example okay if we take the first take the first example 0 + 2 + 1 that will give you sum example 0 + 2 + 1 that will give you sum up to 3 - 6 + + + 6 will be 0 - 7 + 9 + up to 3 - 6 + + + 6 will be 0 - 7 + 9 + 1 again it will be 8 - 7 uh 9 10 - 7 3 1 again it will be 8 - 7 uh 9 10 - 7 3 yeah 2 + 0 + 1 last three elements three yeah 2 + 0 + 1 last three elements three so uh here we are performing the so uh here we are performing the partition of the array we are not taking partition of the array we are not taking subsequence from the array right you're subsequence from the array right you're not taking two one then Zero from here not taking two one then Zero from here no you are partitioning the array into no you are partitioning the array into three parts here so either this partion three parts here so either this partion can be this also 0 2 1 - 6 6 and - 7 9 1 can be this also 0 2 1 - 6 6 and - 7 9 1 21 or 0 2 1 - 66 - 7 91201 so you're 21 or 0 2 1 - 66 - 7 91201 so you're partitioning the array into three parts partitioning the array into three parts and we not performing and we not performing the subsequence subsequence in the sense the subsequence subsequence in the sense we are picking out some elements in the we are picking out some elements in the r order no we not finding that so we are r order no we not finding that so we are just partitioning the AR into equal just partitioning the AR into equal parts minimum three equal parts such parts minimum three equal parts such that the sum of the numbers in each that the sum of the numbers in each partition should be equal so how do we partition should be equal so how do we solve the problem so one thing is they solve the problem so one thing is they have told we have to partition the array have told we have to partition the array into three equal parts and some of the into three equal parts and some of the numbers in equal each part should be numbers in equal each part should be equal that means if we find the sum of equal that means if we find the sum of the entire array if you find the sum of the entire array if you find the sum of the entire AR then that sum divided by the entire AR then that sum divided by three if it is divisible by three only three if it is divisible by three only then we can partition the array into then we can partition the array into three parts that is for sure right so three parts that is for sure right so what we'll do is at first if they given what we'll do is at first if they given an array let's say with the given array an array let's say with the given array first what we'll find is we'll find the first what we'll find is we'll find the total total sum total sum so in this case total sum sum total sum so in this case total sum will be 0 + 2 + 1 3 - 6 + 6 will be 0 - will be 0 + 2 + 1 3 - 6 + 6 will be 0 - 7 3 - 1 - 7 3 - 1 - 4 + 9 so 9 - 4 it will be so 5 + 1 6 7 8 4 + 9 so 9 - 4 it will be so 5 + 1 6 7 8 9 so total sum what we get here is 9 so 9 so total sum what we get here is 9 so is this 9 is divisible by 3 9 by 3 is it is this 9 is divisible by 3 9 by 3 is it equal to Z is the remainder is z if the equal to Z is the remainder is z if the remainder is z yes that means if it is remainder is z yes that means if it is divisible by then only we can confirm divisible by then only we can confirm that we can do the partition in the that we can do the partition in the array to three equal parts otherwise we array to three equal parts otherwise we cannot perform cannot perform so if you take the next example uh let's so if you take the next example uh let's say this example okay here same thing 0 say this example okay here same thing 0 - - 7 - - 7 9 1 2 0 1 so if we do the addition of 9 1 2 0 1 so if we do the addition of the elements in this case so 3 6 + will the elements in this case so 3 6 + will get cancel 3 7 + 3 10 19 - 1 18 19 get cancel 3 7 + 3 10 19 - 1 18 19 20 so we get the sum of 21 so 21 by 3 20 so we get the sum of 21 so 21 by 3 means it's divisible by 3 but the means it's divisible by 3 but the question says is we have to addition the question says is we have to addition the into three parts initially I had told into three parts initially I had told minimum three or more than that also but minimum three or more than that also but more than three when it happens I I'll more than three when it happens I I'll tell that case at the end now we assume tell that case at the end now we assume that we have to partition AR to three that we have to partition AR to three that more than three comes in what if that more than three comes in what if the element the array is 0 comma 0 Comm the element the array is 0 comma 0 Comm 0 0 0 so in this case you can partition 0 so in this case you can partition these two this this right so if the these two this this right so if the total sum becomes zero and count can be total sum becomes zero and count can be greater than equal to three yes in that greater than equal to three yes in that case we can case we can say this is say this is partition but in the second example if partition but in the second example if we see it is divisible by 3 7 21 by 3 we we see it is divisible by 3 7 21 by 3 we get seven partitions are possible with get seven partitions are possible with three elements in that but can you three elements in that but can you divide it into three partiti no that is divide it into three partiti no that is not possible that is why we written not possible that is why we written false here so I said in the beginning false here so I said in the beginning like there can be more than three like there can be more than three partitions also that will be this case partitions also that will be this case explicit case where total sum is zero so explicit case where total sum is zero so if we have -1 1 -1 1 in this case total if we have -1 1 -1 1 in this case total sum is zero but if you see the number of sum is zero but if you see the number of partitions only two we form so in this partitions only two we form so in this case you return false which is not case you return false which is not greater than equal to three so but here greater than equal to three so but here if you see total sum is zero and count if you see total sum is zero and count can be greater than equal to three also can be greater than equal to three also because this one partition this one because this one partition this one partition this one partition this one partition this one partition this one partition possible or these two this partition possible or these two this this three partition possible so in this this three partition possible so in this case count will be greater than 3 uh case count will be greater than 3 uh here you find 0 tot time equal to 0 here here you find 0 tot time equal to 0 here again you find 0 0 0 0 matching so four again you find 0 0 0 0 matching so four partitions you get which is greater than partitions you get which is greater than three so in this case you return two but three so in this case you return two but if you have non zero total sum then in if you have non zero total sum then in such case only three par should be able such case only three par should be able to do it not more than that so in this to do it not more than that so in this case you return false similarly uh last case you return false similarly uh last example also so first you find a toal example also so first you find a toal sum that is 9 is 9 div by 3 yes it is sum that is 9 is 9 div by 3 yes it is there are if 9 is divisible by there are if 9 is divisible by 3 yes we can do it and if 21 is also 3 yes we can do it and if 21 is also divisible by three there are chance we divisible by three there are chance we can can get the partition of three but that get the partition of three but that depends on the elements in the if there depends on the elements in the if there are consecutive zeros like let's say we are consecutive zeros like let's say we have 2 1 okay then 0 0 0 again 2 one have 2 1 okay then 0 0 0 again 2 one here 0 2 one so in such case we will get here 0 2 one so in such case we will get the answer so depends if it is div yes the answer so depends if it is div yes there is a chance of getting the there is a chance of getting the partition uh it need not be like 21 by 3 partition uh it need not be like 21 by 3 will be question we get the 7 seven will be question we get the 7 seven partition no there are chances we get partition no there are chances we get the partition of uh the partition of uh three partitions of equal sum so it three partitions of equal sum so it depends on the elements in the so for depends on the elements in the so for that we have to check once you get that that we have to check once you get that your is divisible first we need to check your is divisible first we need to check so in this case total sum is 9 so next so in this case total sum is 9 so next Target sum will be nothing but 9 by 3 Target sum will be nothing but 9 by 3 that is 3 this is the target which we that is 3 this is the target which we are looking because we are dividing into are looking because we are dividing into three partitions so if we have 21 21 by three partitions so if we have 21 21 by 3 = 7 so we are 3 = 7 so we are looking three partitions with 7 7 7 as looking three partitions with 7 7 7 as the the sum sum in the second example so if you get 7 7 in the second example so if you get 7 7 7 as a su by partitioning the array into 7 as a su by partitioning the array into three parts then yeah there can be three parts then yeah there can be chance in the first example 3 3 3 which chance in the first example 3 3 3 which you are looking so total sum by three you are looking so total sum by three whatever is that will be the target sum whatever is that will be the target sum so let's keep a variable called current so let's keep a variable called current sum initialized to Z we start iterating sum initialized to Z we start iterating so what is the current sum now current so what is the current sum now current sum is 0 0 + 0 will be 0 again 0 + 2 sum is 0 0 + 0 will be 0 again 0 + 2 will be two updated to two then 0 + uh will be two updated to two then 0 + uh okay 1 + 2 will be 3 so now you can see okay 1 + 2 will be 3 so now you can see current sum is equal to Target sum hence current sum is equal to Target sum hence one partition we have obtained here okay one partition we have obtained here okay since we're partitioning the aray we since we're partitioning the aray we need not to check for the random need not to check for the random elements in the it will be the elements in the it will be the continuous element continuous elements continuous element continuous elements so once you found one partition current so once you found one partition current sumal let's have a variable called count sumal let's have a variable called count increment the count value by one and increment the count value by one and current Su will initialized to zero so current Su will initialized to zero so next element start again - 6 so current next element start again - 6 so current Su will be - 6 because 0 + - 6 will be - Su will be - 6 because 0 + - 6 will be - 6 again - 6 + 6 will be 0 again now it's 6 again - 6 + 6 will be 0 again now it's not equal to 3 then you get - 7 so this not equal to 3 then you get - 7 so this willed to - 7 then you get 9 so - 7 + 9 willed to - 7 then you get 9 so - 7 + 9 will be 2 which is not equal to Target will be 2 which is not equal to Target sum again you move hard so + 1 will be 3 sum again you move hard so + 1 will be 3 now current sum equal to Target sum yes now current sum equal to Target sum yes another one partition you can do so another one partition you can do so count will be to and current re count will be to and current re initialized to zero again you find here initialized to zero again you find here to up current sum to two it's not equal to up current sum to two it's not equal to Target sum zero it to remain as such to Target sum zero it to remain as such one upate current sum by three so 3 one upate current sum by three so 3 equal to 3 yes one more partition we equal to 3 yes one more partition we have so Total 1 2 three partitions count have so Total 1 2 three partitions count being three current will Beal to Z yes being three current will Beal to Z yes we are at the end of the hence we have we are at the end of the hence we have found that we have found three found that we have found three partitions partitions of equal sum which what is the sum here of equal sum which what is the sum here three here but if if you uh take the three here but if if you uh take the next next example same thing next example let's example same thing next example let's try out with this also so if you take try out with this also so if you take this example example now so in this case some was 21 so 21 by 3 will be 7 Target sum was 7 here so let's say current Su initialized to zero and count also initialize to Z you should get count equal to three here so you start here Z will be Z only two you found increment to two again you found one so 3 in 3 + 1 then - 6 means 3 3 - 6 will be - 3 + 6 you do so - 3 + 6 will be 3 again which is not equal to Target some yet plus 7 you get so this will be get incremented to 7 uh 7 + 3 10 this is more than Target some form then you found 9 here that will be 19 - one will be 18 then - + 2 will be 21 uh sorry minus okay 18 right 18 + 2 20 then you last 21 so nowhere you're getting it equal to Target some here you can find one partition but there only one partion the remaining elements whichever there previous prev will not be equal to seven right so that is why if you find a partition you start from beginning one partition another another partition so in the continuous manual you will be getting because you're dividing the into partitions you're not picking up some elements and finding the sum here you're not picking this two this one and this zero no you're not doing that elements which that means you're partitioning the array into three parts here it is not SP because nowh you're getting current Target count is zero here it's not equal to three so return false so this is the logic so let's define the variable first okay total sum initialize it to zero so for each number in the array so total sum that's equals to number okay if first you have to check whether total sum modulus 3 is equal to equal to Z only then you can do the partition if it is not equal to Z means you cannot partition the ARR into three partition that the sums are equal no so in this case you directly return false you not to check only if it is if the mod is equal to Z that are case there there is a possibility that you can partition the array to three partitions of equal size equal some so if that is the case so again in the array before to that we have to initialize variable current sum and let's have a variable count [Music] so first what we need to do is current sum plus equals to num so if in case current sum and we have to find write the target sum also that will be nothing but total sum by three it will be see only if the remainder is zero then only you divide it by three otherwise you won't so if current sum equal equal to Target sum that means count should be incremented and whatever current sum you have the initialized to zero so at the end you have to return if count is equal to equal to or uh there is a possibility total sum or uh there is a possibility total sum equal Z count can be greater than equal equal Z count can be greater than equal to 3 in that case to 3 in that case so say count equal toal 3 or total sumal so say count equal toal 3 or total sumal toal toal to0 and count greater than equal to to0 and count greater than equal to 3 because when you have the elements 3 because when you have the elements with 0 0 0 0 with 0 0 0 0 right target total sum will be zero so right target total sum will be zero so total sum means Target sum will also be total sum means Target sum will also be 0 by 3 will be 0 again when you find the 0 by 3 will be 0 again when you find the current sum here you find Z which is current sum here you find Z which is equal Target sum count will be one for equal Target sum count will be one for this again equal to Target count will be this again equal to Target count will be two again equal to Target count will be two again equal to Target count will be again equal to Target count will be again equal to Target count will be four if count greater than equal to 3 so four if count greater than equal to 3 so this let it be inside one more bracket check check total yeah yes so same logic applies to Java also directly can give greater it will not create a problem yeah so we should also yes successfully submitted if you also yes successfully submitted if you understood the concept please please do understood the concept please please do like the subscribe to the channel we'll like the subscribe to the channel we'll come up with another video in the next come up with another video in the next session until then keep learning thank session until then keep learning thank you | 2024-03-25 14:47:10 | 1,013 | LeetCode 1013 : Partition Array Into Three Parts With Equal Sum || EASY || C++ || JAVA || Solution |
|
gRAmXV0T5B4 | all right long as continuous are both absolute difference let's make a limit absolute difference let's make a limit so let's say i have this array of so let's say i have this array of numbers here numbers here and i have a limit of 50. and i have a limit of 50. and let's just look at this sub array and let's just look at this sub array here here so this is actually the longest sub so this is actually the longest sub array where the difference between any array where the difference between any two of the elements so if i like look at two of the elements so if i like look at any two elements that the difference any two elements that the difference between those will be less than or equal between those will be less than or equal to the limit to the limit and the way you can check the way you and the way you can check the way you can check very very quickly is you just can check very very quickly is you just look at what's the maximum element so look at what's the maximum element so the maximum element here is 55 let's the maximum element here is 55 let's write that down write that down and the minimum element is 20. why is my facing off all the time okay minimum 20 okay and if we just look at the difference between 55 and 20 or if we look at the difference between the maximum the minimum as long as that difference is also equal to the limit well then all the other numbers uh will have a difference that is the center equal to the limit as well so uh let's pretend let's pretend that i was able to like find the sub array by looping from let's get rid of this let me just actually i'll leave that there so let's say i was i started at the beginning right and i was just like traversing like increasing my window size increasing my window size and i got to this point right and i was like okay cool we're good so far but then where things get interesting is when i try to add the zero in so let's say i try to add the zero in what i'm going to do first is i'm going to update my minimum to zero and i'm gonna say okay is this zero uh is the difference between this zero my minimum is it less than equal to my limit and it is because your zero minus zero is zero and zero is less than fifty okay but now is this zero minus my maximum is it less than or equal to my limit of fifty and no because the difference between zero and fifty-five is 55 so 55 is greater than the limit so we need to exclude this 55 we don't want it and everything to the left of it we don't want it so we need to do is move our our window size one past it and you think we're good so far we you'd think this would be fine right but we're not because if you notice there's another number in here that's 52 if we take the diff so if we our new maximum would actually be 52 and 52 uh minus zero is 52 and that is greater than our limit of 50. so we would actually want to move one past this 52 as well and this would be our new window size uh if we include the zero here and so notice what i notice what i had to do there for a second let's actually go like wind that back a little bit so i had to find so i had to compare zero to my maximum and then if it if it broke my limit i had to go one past the maximum i didn't move my one to one past it and then i have to compare it i have to compare the zero to the next maximum element which would be this 52 and when i say next maximum it's whatever the maximum element is past this 55. so this 55 was my current maximum now it needs to be whatever my next maximum is whatever is to the right of the 55 and that would up to this point so this would be the 52 here so uh and then i would because that breaks our property 52 minus zero would break our limit then we need to move one past it as well okay and i'm going to explain how to find the next maximums and all that in a second but let me just keep going so now we're going to try to include the 10. and actually let me real quick let me update our maximum to 40. okay so uh we're going to try to include this 10 here and we can because our minimum right now is zero if we just we take we look at this 10 and we compare to our minimum well the difference between 10 and 0 is 10 that's less than our limit and the difference between 10 and 40 is 30 so that 30 is less than our limit too or less or equal to the limit so we're good there but uh now when we try to include 57 so we're going to update our maximum and we're going to say okay it's 57 is the difference between 57 and 0 is that less than or equal to our limit and it's not because 57 minus 0 is 57 57 is greater than 50. so uh we need to move one past the minimum now so we're going to update our bracket and move one past this minimum and then we would compare 57 so our new middle would be 10 now we compare 57 to 10 and that's 47 so we're good there because 47 is also equal to 50. all right so what we need to do is we need to have an efficient way of finding our maximum and minimum values and then we need to be able to find our next maximum and our next minimum values so that we can keep updating our the left side of our window so how are we going to do this so what we're going to do is we're going to use a monotonic stack so and you could use i'm sure you could use a monotonic here too um i'm not as like well-versed with monotonic cues but i'm pretty sure they just achieved the same thing so but if you want to go that route you can't but i just used excellent that's what i'm comfortable with so uh let's let's go over let's use a decreasing stack to find our next our next maximum elements so let's write that down so a decreasing stack will it finds the next max element and then an increasing stack will find okay so uh okay so uh we're gonna we're gonna just do a we're gonna we're gonna just do a decreasing stack so decreasing stack so and we're gonna use both in our and we're gonna use both in our algorithm but for now let's just go over algorithm but for now let's just go over what a decreasing stack is and all that what a decreasing stack is and all that so we're going to push this 30 into our so we're going to push this 30 into our stack stack let's do that here i'm going to push i'm let's do that here i'm going to push i'm going to try to push this 55 going to try to push this 55 but i can't because if i push 55 this is but i can't because if i push 55 this is increasing this needs to be decreasing increasing this needs to be decreasing so what i need to do first so what i need to do first then i need to pop 30 then i need to pop 30 and then push 55 and then push 55 and then i can push the 20 and then i can push the 20 and notice this is decreasing right and notice this is decreasing right well well what what's the relationship what what's the relationship uh between this 20 and this 55 well if uh between this 20 and this 55 well if you notice whatever's on the bottom of you notice whatever's on the bottom of our stack our stack is actually is actually our maximum element up to this point so our maximum element up to this point so like if we look at so right now we just like if we look at so right now we just did did we tried to we pushed 30 55 and 20 to we tried to we pushed 30 55 and 20 to our stack our stack and the maximum element and the maximum element with it up to this point with it up to this point is 55 and notice that it's at the bottom is 55 and notice that it's at the bottom of our stack of our stack so one property you should notice is so one property you should notice is that the just keep that in mind is that that the just keep that in mind is that the bottom of the stack is our maximum the bottom of the stack is our maximum element in a decreasing stack element in a decreasing stack and then the element on top of me and then the element on top of me is actually the next maximum element to is actually the next maximum element to the right of me so like the right of me so like whatever whatever element is on top of whatever whatever element is on top of me so 20 is on top of 55 me so 20 is on top of 55 that is the next maximum element to the that is the next maximum element to the right of me in the array right of me in the array so so or sorry so it'd be just this or sorry so it'd be just this would just be this so far would just be this so far okay and now when we add the 52 okay and now when we add the 52 uh uh we actually have to pop the 20 because we actually have to pop the 20 because this is that wouldn't be decreasing this is that wouldn't be decreasing anymore and then we could just push the anymore and then we could just push the 52 52 and now up to this point and now up to this point or we could or we could highlight the whole thing so up to this highlight the whole thing so up to this point 55 is my maximum element in the point 55 is my maximum element in the array because 55 is still on the bottom array because 55 is still on the bottom of the stack of the stack so notice 55 is still the maximum so notice 55 is still the maximum element and notice the next maximum element and notice the next maximum element element up to this point so like let's just up to this point so like let's just ignore this ignore this so so the next maximum element the next maximum element after the 55 so between 2052 is after the 55 so between 2052 is this would be the next maximum and this would be the next maximum and notice that that is directly on top of notice that that is directly on top of the 55 here the 55 here in our stack so now let's bring this in our stack so now let's bring this back back and now we're going to add we're going and now we're going to add we're going to try pushing 40 into our stack and because 40 was on top of the 52 that is 40 is the next maximum element to the right of 52 which is right after 52 in the actual array now we can push 0 and 0 would be the maximum element that comes after 40. like the to the right of it okay and let's go ahead and finish this up so 10 let's push the 10 in well we have to pop the zero because we want to be increasing or sorry decreasing and we're going to push to 10. and now notice that 10 is the next maximum element of 40 on its right side so that's and 10 is directly above the 40 in our stack okay and then when we do this 57 well we actually have to pop all of these because uh 57 is greater than all of these so we want to be decreasing so we're going to pop all of them push 57 and because 57 is on the bottom of our stack that means that 57 is actually the greatest element up to this point okay um so that's how you find your next maximums is you need to well let's look at that so you would need to actually take things from the bottom of the stack this would be our maximum this would be the next maximum and then this would be the next maximum amount of 52 and this would be the next maximum after 40. so uh we and we need to also be able to do this for the minimums um but it's exactly the same thing you just use an increasing stack i don't really want to go through the whole example but just trust that uh if a decreasing stack finds the next maximum and i showed you how to do it just now then if we use an increasing stack so let's just do it let's just do it really really quick like i'm not going to go through the whole thing but an increasing stacking i'd push the 30 i'd push the 55 and this is notice that 55 this so this is our minimum so far 30 and because 55 is on top this is our next minimum element if we were to like delete the 30 and then when we pushed the those one up to 20 next to get rid of both of these let's pop both push 20 then push the 52 and if we want to push the 40 we'd have to pop the 52 push the 40 and notice that 40 is the next minimum element after 20. so like if we were to get rid of uh everything on the left side here then 40 would be the next minimum element uh now when i say next minimum it's just like if this was if 20 is the minimum if we were to delete the 20 then the first minimum if we just look to the right side of of 20 up to this point then 40 is the next would be the next minimum element assuming that we deleted everything out here okay let's code this out so i'm gonna create a couple link lists to represent the stacks and i'm using linked lists and not actual stacks because um we want to be able to remove from the bottom of the stack because remember the bottom of the stacks have our next maximum minimum elements so we'll start with the decreasing stack equals new linked list and this would hold because it's decreasing our max element is on the bottom we'll just say max element on bottom and this so this finds the next max element okay and then this is the same thing for the minimum so we want to do the increasing stack and now because it's increasing the minimum element is on the bottom and this finds the next minimum element okay and now we want to what we want okay we need to create a variable to keep track of our longest sub array that we've encountered so far this is just like a mac a global max variable and we're going to return longest at some point okay and then we're going to loop through our uh our nums array so i is also noun.length plus plus i and then we're going to uh we want to add the number that we're currently at so we want to add numbers i we want it let's let's just do the decreasing stack first so eventually we wanted to be able to say decreasing stack dot add last and the last element is going to represent the top of my stack okay so i'm going to try to push this onto my stack but before i push it i need to make sure that i'm not breaking the decreasing property in this decreasing stack so i'm going to do what i'm going to do is i'm going to say if while the stack isn't empty this actually needs to be decreasing stack so while decreasing stack is not empty and decreasing stack dot oh and actually oh sorry one one last thing i don't actually want to push the values i want to uh push the indexes and i can always grab the values from the indexes right because i can always when i pop out the index i'll just index into the nums array okay and that's generally just more useful than pushing in the actual values but anyway uh so while the decreasing stack is not empty and decreasing stack dot get last so this is the top of the stack this is the index of the top of the stack we're going to say nums okay is okay so this is decreasing so five four three and let's say i want to push in uh i don't know a seven well i can't push a seven because if this needs to be decreasing so uh we're going to check is this value here so is nums of to get last so if it's less than then we want to so even if it was a then we want to so even if it was a duplicate we could just get rid of the duplicate we could just get rid of the duplicate and just put in our three in duplicate and just put in our three in there there it's a it doesn't matter but uh it's a it doesn't matter but uh so if nums educational stack get last if so if nums educational stack get last if it's less than or equal to um our nums at i yeah then so essentially this breaks our decreasing stock property then we want to say decreasing stack dot remove last so this is the this would be the pop okay and then finally after we remove all the elements that break our property then we're going to add the element into our stack okay so now what we want to do is keep is compare this nums i uh to the maximum element in our decreasing stack so and we actually have to make a while do this in a while loop because um remember we we have to keep comparing it to the next maximum and the next maximum to see if like if that keeps breaking our limit when we take the difference of it so we're looking for the difference so all math.abs of nums i minus the decreasing stack dot uh get burst so remember so get first is the bottom of the stack and that holds our maximum element so if the difference between our current value and the maximum maximum value if this is greater than the limit then we want to pop or we want to we want to remove and we want to move our window size and we want to move our window size one past that so let me one past that so let me do decreasing stack dot remove first do decreasing stack dot remove first and and we're gonna say int let's keep track of we're gonna say int let's keep track of our window size or sorry our start or our window size or sorry our start or window start window start and we can actually put that we should put this outside so the start of our window is just going to we're going to start at the very beginning so windows start at zero and this needs to be window start equals decreasing stack remove first so this will be the index of that maximum element oh and i actually need to do sorry i forget so this is an index right of the maximum element so i need to do nums here okay so if the difference between our current value and the maximum value is greater than the limit then remove that maximum value and then we got to move one past our we got to move our windows the start of our window one past this this is going to be uh remove first plus one okay so now i think we are almost done so uh and now we need to update uh longest so into longest equals one plus um the window start or we need to do i minus the window cool so i is our current is where our cool so i is our current is where our current like if we let me just type out current like if we let me just type out some numbers here some numbers here okay okay let's do that um so if let's say we're let's do that um so if let's say we're on the seven here on the seven here then i would currently be here then i would currently be here and let's say my window start is i don't and let's say my window start is i don't know right let's say it's here at the know right let's say it's here at the very beginning so this is index zero very beginning so this is index zero well if i is index two so i equals two well if i is index two so i equals two in this case in this case then then uh two minus zero uh two minus zero would be two but i need to add one would be two but i need to add one because we actually have three elements because we actually have three elements here right in this little array so here right in this little array so that's why i add one here that's why i add one here um um okay so uh okay so uh and i'm saying that my window start and i'm saying that my window start would be zero in this case would be zero in this case okay okay okay so um okay so um now now so we did the maximums we didn't do the so we did the maximums we didn't do the minimums minimums but the code is literally going to be but the code is literally going to be exactly the same exactly the same so what i'm going to do the only thing so what i'm going to do the only thing that changes like when we do our that changes like when we do our increasing stack the only thing that's increasing stack the only thing that's going to change is this guy right here going to change is this guy right here this little condition because instead of this little condition because instead of uh less than or equal it'll be greater uh less than or equal it'll be greater equal running for an increasing stack equal running for an increasing stack so um so um [Music] [Music] what i'm going to do is i'm just gonna what i'm going to do is i'm just gonna literally copy and paste this into a literally copy and paste this into a helper method and uh yeah so let's helper method and uh yeah so let's actually create that really quick so actually create that really quick so private um private um int and we'll call this get window int and we'll call this get window get get windows start i think that's get get windows start i think that's good and we're going to pass in good and we're going to pass in our our stack and we're going to pass in on the nums array we'll pass in the index that we're so this i we're gonna pass this in it's because we're trying to add it push into our stack and we'll pass in what else should i pass in oh the limit yeah we need the limit too okay so let's just literally copy and paste and okay so like how are we actually and okay so like how are we actually going to handle like changing this going to handle like changing this condition based on whether it's like a condition based on whether it's like a decreasing factor or increasing stack decreasing factor or increasing stack well what we're going to do is we're well what we're going to do is we're going to create a going to create a a by function which is just like a a by function which is just like a callback function callback function and and these two integers here that's just these two integers here that's just going to be going to be these two integers here these two integers here and i need to pass in the thing that and i need to pass in the thing that we're returning or we're turning a we're returning or we're turning a bullion right because when we we're just bullion right because when we we're just going to do this little check and then going to do this little check and then we're going to return a boolean we're going to return a boolean and we're going to it puts on another and we're going to it puts on another line it's getting long line it's getting long so we're going to call this let's call so we're going to call this let's call it compare it compare all right and then what we'll do is all right and then what we'll do is we'll do compare we'll do compare dot apply okay and okay and i'm going to go ahead and i'm going to go ahead and so i'm going to rename this to just so i'm going to rename this to just stack and since it's no longer just stack and since it's no longer just a d this could represent the decrease in a d this could represent the decrease in stack or the increasing stack stack or the increasing stack all right all right so let me see what else we have to do so so let me see what else we have to do so okay so now we just got to call this so okay so now we just got to call this so get windows start get windows start let's copy paste that let's copy paste that pass in pass in our decreasing stack our decreasing stack and for the and for the just remove all the types and then for the compare part we just have to do um i'll just type it right here so a comma b it's for decreasing stack it was less than or equal so a less than or equal to b and then we'll pass in the limit at the end okay so now we're going to say windows start equals the maximum of where we currently are and whatever we whatever we uh if so if this forced us to move past anything then um this maximum will so uh get windows start uh windows start so uh get windows start uh windows start okay cool and then we would do the same okay cool and then we would do the same thing for the increasing stacks we could thing for the increasing stacks we could just copy paste that okay and i actually need to return windows start down here oh this is my spacing's all off when i copied and pasted it okay so inch oh my god window start equals zero and so windows start gets over in right here and then we'll just return okay uh i think we are good let's just okay uh i think we are good let's just run this oh what am i doing longest needs to oh what am i doing longest needs to equal equal math.max of longest because this might math.max of longest because this might not be our longest sub array anymore not be our longest sub array anymore after we update the window sorry after we update the window sorry okay okay oh i didn't update the condition right oh i didn't update the condition right here so this all this all that changes here so this all this all that changes that this needs to be greater or equal that this needs to be greater or equal now okay cool so let's submit it all right so uh that's how you do this problem this is of n time i know it looks like it's o of n squared because of like these inside while loops but you just have to think of what's actually happening um we only push every element in the stat every element in nums gets pushed to both stacks one time and every element only gets popped at most once from those stacks so that's why it ends up just being o of n and the space would be o event as well | 2024-03-21 01:30:10 | 1,438 | LeetCode 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit |
|
SDMLgUJSdcQ | Hello hello everybody welcome to my channel it's all the problem in freedom of problem in freedom of characters to implement his team chapter characters to implement his team chapter class carlos slim check kar witch gets relief class carlos slim check kar witch gets relief but switzerland constructor in but switzerland constructor in data structure will give words and various methoded data structure will give words and various methoded witch will get neither patient nor notification witch will get neither patient nor notification glass virgin oldest glass virgin oldest glass virgin oldest spirit of the world in the giver is the example will be constructed and will be the chief and will get the correct video actor will be id porn tell anything our history like constructive said happy check is it content Do But No Do But No Do But No Return Soon After Midnight Subscribe 2009 Return Soon After Midnight Subscribe 2009 Half Ninth ABCD ABCD Noobs Straight Note Half Ninth ABCD ABCD Noobs Straight Note Straight Reserve Which Seamed To Return With Straight Reserve Which Seamed To Return With Boys And Subscribe Button To 2017 English Boys And Subscribe Button To 2017 English Letters Video Please Ujjain Letters Video Please Ujjain Who Who So How Will Solve Problem Who Who So How Will Solve Problem Solve And Subscribe In Your Mind Will Solve And Subscribe In Your Mind Will Solve And Subscribe In Your Mind Will All the World in One of the Tarzan One Time Which She Will To Report Subscribe Directly So Let's After Getting His Will Power Come Set and Notes How Will Generate All the Worlds First Step All Will Start From the end of the builder on which explanation ladies vs super villain is the Thursday civil war or Thursday civil war or with whip will do the words from correct correct correct correct with whip will do the words from correct correct correct correct and implementation and implementation of solution is of solution is Airtel Distributor for Keeping the Airtel Distributor for Keeping the Places of the World in the Sense of More to Places of the World in the Sense of More to the Meaning of the Word From - 120 subscribe this video give Person Shamil Virvar on the Places of the World Can We Make Sure That War Subscribe Get accepted Get accepted Get accepted 100 servi pattern first automatically half 100 servi pattern first automatically half minute and subscribe to the amazing minute and subscribe to the amazing problem is that straight problem is that straight turn off nk l sorry third Indians after turn off nk l sorry third Indians after getting no isi builder normal bhed from getting no isi builder normal bhed from cd deluxe starting of the self made this cd deluxe starting of the self made this year will have to search the year will have to search the year will have to search the subscribe thank you for creating the subscribe thank you for creating the tribes from normal life and they will tribes from normal life and they will drop it from r soul will look like this ki and will create denotes from which will address vijay disbursed dip node and will have seen address vijay disbursed dip node and will have seen node in node in node in Meet Dance Makeup Person Video Similarly After World Must Subscribe Channel Main To Sari It's Not Be Arriving In That Choudhary Is Special Person Word From That Choudhary Is Special Person Word From Quote SVR Reverse Verses Try Not Quote SVR Reverse Verses Try Not Quote SVR Reverse Verses Try Not searching straight pattern egg bcd lead key and little abcd crops search so what will oo will check for this others are in the video then subscribe to the amazing learn from this video all will return from books from evil Return Return Return is straight forward is straight forward century of forms proven try will work to so let's century of forms proven try will work to so let's implement this I have implemented with abe implement this I have implemented with abe security map data structure and security map data structure and boys subscribe this video please subscribe and up the stop this is the best way to make the thing subscribe Thursday try thing Not elected call route nobody will Not elected call route nobody will release references in mostly new history release references in mostly new history builder builder who alarm in the morning route is new who alarm in the morning route is new 's creatures not so after nationalization be 's creatures not so after nationalization be happy and all the words in incomplete word in happy and all the words in incomplete word in words and withdraw into subscribe for the words and withdraw into subscribe for the first of all they will strive to search first of all they will strive to search first of all they will strive to search World Will Start From A Ki Prai Lord Which Related Not Vanish From Drought And Will Defend Itself From Depend Of Acid - Awal Ki And This Is Great Daily 120 Phase Notification Aa Ki Rajputs Notice Not Equal To Na And Decree Aa Ki Rajputs Notice Not Equal To Na And Decree I Want Every Time You Will I Want Every Time You Will I Want Every Time You Will subscribe to subscribe to yes brother so will check in our tribes have yes brother so will check in our tribes have any next day of character any next day of character 220 will check this God notice note channel and 220 will check this God notice note channel and evolve with oo evolve with oo a return from a great salute a return from a great salute nickel swift otherwise will continue nickel swift otherwise will continue nickel swift otherwise will continue Looking Into All Characters Also Processes 200 Where Is The Okay Isht We 200 Where Is The Okay Isht We Aap Ko Maaf Badu * Condition [ __ ] Condition Aap Ko Maaf Badu * Condition [ __ ] Condition President C August President C August Alarm Set Compiled And Were Wait Submit Alarm Set Compiled And Were Wait Submit Scored A I Connect Is Characters 120 MLAs Solution to my channel to my channel to my channel press bell icon to get notification thanks press bell icon to get notification thanks for watching the | 2024-03-25 15:26:25 | 1,032 | stream of characters leetcode | leetcode 1032 | brute force | reverse word trie |
|
vsl_Lh_fhAE | written an array of the intersection so what the question says is that given two what the question says is that given two arrays and we just need to return the arrays and we just need to return the intersection of elements of both the intersection of elements of both the eyes and the condition given is each eyes and the condition given is each element in the result must appear as element in the result must appear as many as times if chosen both the arrays many as times if chosen both the arrays and you may return the result in any and you may return the result in any order that means see in this example you order that means see in this example you could say 1 2 2 1 and 2 2 and we could could say 1 2 2 1 and 2 2 and we could say that two element is occurring in the say that two element is occurring in the in both arrays and this Two element is in both arrays and this Two element is occurring twice in both directions so occurring twice in both directions so the output must contain as previous the output must contain as previous times are an element appeared in both times are an element appeared in both the arrays and you may return the result the arrays and you may return the result in any order so if you go to the second in any order so if you go to the second example 495 it is rfuc example 495 it is rfuc false the lines present yeah four is false the lines present yeah four is present so since the 9 and 4 are present present so since the 9 and 4 are present in the array one only once we return 94 in the array one only once we return 94 from direct to also only once because from direct to also only once because it's an intersection of two arrays and it's an intersection of two arrays and Phi is not acting and are array two so Phi is not acting and are array two so you don't output that and we order at you don't output that and we order at which you return the output like you can which you return the output like you can either return either return for both will be accepted that's what for both will be accepted that's what they have told so what is the approach they have told so what is the approach to solve this problem is we will take to solve this problem is we will take the example first and for this array it would be 4 comma 4 then a comma 9 comma a so once you start the array now we have to since we have to written an array right into section of two arrays let's define a new array called Ras and equal to minimum of equal to minimum of uh uh length of two arrays so that resulted length of two arrays so that resulted length might be the minimum of array of length might be the minimum of array of two array settings it can be three two array settings it can be three the resultant rlm can be in this case it the resultant rlm can be in this case it can be three or two or one also so any can be three or two or one also so any of this so the max will want to be in of this so the max will want to be in that case the minimum of length of two that case the minimum of length of two areas that is one areas that is one we write here so I have to handle these we write here so I have to handle these conditions we will see later conditions we will see later next coming to next coming to um um let's say if uh to handle this condition let's say if uh to handle this condition means what let's say the array 1 has 4 means what let's say the array 1 has 4 and 4 comma 5. and 4 comma 5. right so in this case Okay other has right so in this case Okay other has four five and nine right in here you four five and nine right in here you could say you need not to have the could say you need not to have the fourth Market in the existing array I fourth Market in the existing array I can explain the case so in this example can explain the case so in this example four nine five four four eight nine nine four nine five four four eight nine nine four is present in second another yeah four is present in second another yeah it is an intersection then 5 is not it is an intersection then 5 is not present then coming to nine yeah nine is present then coming to nine yeah nine is four command n must be the output ER four command n must be the output ER nine comma four nine comma four anything is acceptable if you like if anything is acceptable if you like if you see the length of this resulting you see the length of this resulting array now it is 2. array now it is 2. but fear initially assigned the length but fear initially assigned the length of the resultant error equal to minimum of the resultant error equal to minimum of length of both the arrays that is of length of both the arrays that is three so but the resultant data has three so but the resultant data has length two so the resultant array will length two so the resultant array will be either 4 comma n comma zero be either 4 comma n comma zero or nine comma four comma zero because it or nine comma four comma zero because it has only two elements which we inserted has only two elements which we inserted so the third element would be so the third element would be uh MP that is zero it will be uh MP that is zero it will be represented as zero to handle this represented as zero to handle this function what we do is we will have a function what we do is we will have a count of this number of elements in the count of this number of elements in the resultant array so till while resultant array so till while development only we will declare a new development only we will declare a new Oracle result Oracle result so the result array will have the length so the result array will have the length the number of counts of the Elements the number of counts of the Elements which we interconnected to the which we interconnected to the horizontal array that will be let's see horizontal array that will be let's see k k so the New Order initial S and we run so the New Order initial S and we run the while loop for the result and add the while loop for the result and add the corresponding values to the the corresponding values to the resultant we uh we run the fall for the resultant we uh we run the fall for the RAS array and add the corresponding RAS array and add the corresponding elements to the result of it till the elements to the result of it till the count which we have in this case it is count which we have in this case it is two so that is how we handle this case two so that is how we handle this case so we're going to do this now so we're going to do this now we have sorted the arrays right now we have sorted the arrays right now let's say I is pointing here and J is let's say I is pointing here and J is pointing here pointing here so if I is equal to J We Run The Y Loop so if I is equal to J We Run The Y Loop until the either available Okay so in this case we check whether I is equal to equal to J if I is equal to equal to G we just need to add this that will be nothing but res of K let's say case initially equal to 0 so rules of K plus this we can write because once you assign a value to the gate position then the next element you come to the K plus plus position so that's why we use right R is of K plus this will perform nothing but at first will be initial as RDS of K and then it will increment K plus plus so that I and now if both are equal then you increment both I and J now so increment both I and G for the next iteration so once you increment both I and J now we check whether this element is equal to equal to this element this Phi is equal to 4 no so if they still want point that you have to implement so get to know that you could see here the iron unit of second is 4 and the other unit of 5 is uh first uh first are S5 so if You observe five is lesser than uh greater than four that means 4 is this is scope this is scope to get the file number in the secondary to get the file number in the secondary because it might be the next element because it might be the next element also right after the five appears after also right after the five appears after four so that's why we have to check the four so that's why we have to check the condition if the other element doesn't condition if the other element doesn't match if nums of I is not equal match if nums of I is not equal functions here then you check if functions here then you check if nums of J nums of J whatever is present here 4 that is whatever is present here 4 that is lesser than answer five if that is the case as I said after 4 you need to get 5 right there is a scope to get it so in that case you just import J plus plus you have here so you have here so and J question eight you have Phi and a and J question eight you have Phi and a see now is the way possible to cut Phi see now is the way possible to cut Phi in the secondary mode because 8 is in the secondary mode because 8 is already greater than 5 and we are sorted already greater than 5 and we are sorted that so that is about things you need that so that is about things you need not to check this connection in this not to check this connection in this case the L is part will contained that case the L is part will contained that is nothing but I plus plus is nothing but I plus plus in this case the first thing we will in this case the first thing we will have a scope to get a to the first step have a scope to get a to the first step right so right so if uh secondary element is smaller than if uh secondary element is smaller than the possible unit then there will be a the possible unit then there will be a scope to get the scope to get the first other element in the second array first other element in the second array element so we increment the pointer J element so we increment the pointer J Plus Plus if the faster element is smaller than if the faster element is smaller than the secondary element in this case 5 is the secondary element in this case 5 is lesser than a then this 8 might appear lesser than a then this 8 might appear somewhere next to Phi in the first that somewhere next to Phi in the first that is a possible in that case the increment is a possible in that case the increment I so we do I plus plus are equal so you add them to the res of K plus will be equal to nums of I so once this is done again you increment I plus plus and J plus s now now at this time you could see similarly arrays similarly arrays or sort of nulls to so once you solve or sort of nulls to so once you solve the both the arrays the both the arrays now we now we okay after all these cases as I said you okay after all these cases as I said you have four comma 9 as a resultant but the have four comma 9 as a resultant but the resultant array areas not resulting resultant array areas not resulting researl length is three actually so the researl length is three actually so the last element would be zero in such case last element would be zero in such case friends to avoid this condition we have friends to avoid this condition we have K value pointing together k equal to 1 K value pointing together k equal to 1 right right because we do K plus plus here so K was because we do K plus plus here so K was 0 initially when you added for K will 0 initially when you added for K will become one thank you so next you add again 90 will become two so you run the while a for Loop k equal to 0 sorry or yeah some other element M or l for or for I units positive sorry I'm just okay so for I equal to 0 and I lesser than K because I will be 2 this time so either 0 and comma one position that will have four comma so that should be added to the one more called resulting result so this Okay so the results position we add four comma right so while I equals 0 I lesser than K and I plus plus result of I r e s of K oh not okay yeah that's it usually we are going to initialize res usually we are going to initialize res equal to length was three but we equal to length was three but we obtained res only two elements as four obtained res only two elements as four common area intersection we didn't common area intersection we didn't include five we couldn't get 5 right include five we couldn't get 5 right this 5 was not included in the this 5 was not included in the intersection array so that's why there intersection array so that's why there is a length reduced to one so in this is a length reduced to one so in this case uh the output array was like four case uh the output array was like four comma 9 comma zero which she will get it comma 9 comma zero which she will get it we need only four commonly for that we we need only four commonly for that we declare one more array result and tilde declare one more array result and tilde State position we run the follow and we State position we run the follow and we add this elements to the result array add this elements to the result array and the result array and to escape in and the result array and to escape in this case not the mean of 2 r s this case not the mean of 2 r s so so now we'll now we'll declare array called Ras equal to U in of the sorry the entirely is equal to new int off so now why we select length is dot mean of length of Tourism is one dot length common comes to the left right so now in k equal to 0 to keep track of the elements in the resn that is resulted so now print I equal to 0 comma J is also equal to 0.2 I is pointed to one running and J is going to another so why less than nums coin dot length so when you have this so when you have this you check if nums of I is equal to equal you check if nums of I is equal to equal to nums 2 of J to nums 2 of J is one of I sorry very sorry if they are equal then you add that to the resultant that is res of K plus this is equal to sums 1 of I it can be comes to of J also so r s of K plus what will do it will initialize the RCs of K vary first then implement the K value by 1. so after this edge condition oh okay after this we Implement I and J both so I plus plus and J plus plus because we have found the result matching eliminating both that so else conditions will be in the else part we need to check now this temperature array one length is smaller or array two like this smaller if nums 2 of J is smaller than nums 1 of I in that case increment J plus s because so that is one case home so that is one case home foreign so at last after all these cases now uh declare a new array so in result equal to new end of K this time the length will be equal to K because as I said see we have the Define the minimum length equal to and the two others right so in the system won't contain the minimum length of industry or two arrests so it might be lesser than that for this case we declare a new array so for and I equal to 0 I lesser than K and I plus plus result of I equal to r e s of I that's it so at last written the is there any mistake this m should be Capital math yeah and this should be numbers too okay variable I is already defined in okay variable I is already defined in method intersection oh yeah that's why method intersection oh yeah that's why we will use the other something else is it successfully submitted if you is it successfully submitted if you haven't readers please drop it in the haven't readers please drop it in the comment section we'll come up with comment section we'll come up with another video next session and please another video next session and please subscribe for more such videos and keep subscribe for more such videos and keep learning thank you | 2024-03-24 11:14:59 | 350 | LeetCode 350 : Intersection of Two Arrays II || EASY || JAVA || Detailed Solution |
|
zEjGUK5oZ1k | all right so let's talk about the increasing triple sub sequence so you increasing triple sub sequence so you are giving integer real numbers you have are giving integer real numbers you have to return true if you can fulfill the to return true if you can fulfill the constraint constraint and this question is pretty and this question is pretty straightforward you can use in a brutal straightforward you can use in a brutal force but i don't recommend that brutal force but i don't recommend that brutal force is pretty straightforward ijk force is pretty straightforward ijk right right and then you check every single index and then you check every single index all the possible combination all the possible combination and then you starting moving your k and then you starting moving your k first and then if you cannot find out first and then if you cannot find out the increasing subsequence then you move the increasing subsequence then you move you move your j you move your j and starting the same idea right and and starting the same idea right and then if you cannot find it then you move then if you cannot find it then you move again again right then you cannot find again then you will move your eye right so this is pretty much it right the problem is why you need to find out if there is the all the fun time complexity and then all of one for the space and in this one this is into a tube right it traverse every single one of the possible possibilities and then to find out the increasing triple subsequence so this is not good so how do you actually get the most efficient way so i'm going to just give you my solution and this solution is pretty it's pretty good and it's insane like i don't think about it and someone i know so i will have a meanwhile that means you set to the max by default value and then i will have a pointer for my norms and then i will have to check i will have to check if my num is less than equal to mean one if this is true i'm going to update my mean one to num this is first if statement and then if this is true i update if this is false i point to my lc statement for the nouns it's actually less than equal less than equal to mean two if this is true i update my min two to know right so uh in this in this idea right you probably know this you find out the inclusion two element only two right now and if you want to find out the third one then you are just using an else and then you will say return true right here this is because what you check your first one the first if statement and the number is less than equal to mean one right and then you and then you don't execute this if statement then you go on the next if statement numbs two i mean sorry nums is less than equal to mean two so you cannot find it right so you don't execute right then you know this is the third biggest the third smallest i mean the third smallest value inside an amplitude so your return should so this is a pretty much idea but i have to just walk through just walk through this algorithm with you so i will say mean 1 equal to max min 2 and here's my num and here's my num alright alright my number's pointer so again my number's pointer so again if norms if norms is less angle to mean one is less angle to mean one i update my max i update my max up in my mean one up in my mean one all right if this is true update i mean all right if this is true update i mean one two two right so there's a reason one two two right so there's a reason why you use uh why you're using uh why you use uh why you're using uh lesson info i mean lesson info i mean be more be more accurate why you use equal this is accurate why you use equal this is because if you have one one one one because if you have one one one one they are not actually they are not they are not actually they are not actually uh increasing subsequence they actually uh increasing subsequence they are actually on the same level so you are actually on the same level so you want to use an equal sign to keep want to use an equal sign to keep updating your current smallness right updating your current smallness right so like the so like the same integer is not allowed right same integer is not allowed right and then and then uh you're going to go on your next uh you're going to go on your next pointer pointer follow numbs follow numbs and then you see the first if statement and then you see the first if statement mean one mean one number is the mean one then update number is the mean one then update to one right to one right again move your pointer again move your pointer to five and then you see okay this time mean one is what it's less than num right so you don't you don't update but the number is one less than mean two so you update five then move your pointer to zero right now this is get updated now you change another pointer four right and this is four last one six last one six so you check your first if statement all so you check your first if statement all right noms right noms that's angle to mean one is this true or that's angle to mean one is this true or no no this is six this is zero this is false this is six this is zero this is false right so you go on the next one right so you go on the next one is numbs is numbs less than equal to less than equal to mean two mean two no this is six this is four right so you no this is six this is four right so you go on the third one which is else go on the third one which is else now you return true right now you return true right so you find out the increasing order so you find out the increasing order based on the comparison right based on the comparison right and this is not called uh this is not and this is not called uh this is not coincident the if you find out if you coincident the if you find out if you change the number change the number for zero for zero you you are still going to return to you you are still going to return to why why one one two two six i mean one four six sorry one four six i mean one four six sorry one four six this is older six this is older and even though like and even though like uh uh i mean even though the logic look pretty i mean even though the logic look pretty complicated but it's just correct complicated but it's just correct so in mean so in mean equal to integer dot equal to integer dot max value comma integer net stock right and then using the comparison if num and then using the comparison if num let's go to mean one third uh third uh third smallest i think third smallest i think and then i have to recompose at the end and then i have to recompose at the end so this is why you have to keep keep so this is why you have to keep keep track of the current smallest the second track of the current smallest the second smallest and then the third smallest smallest and then the third smallest right so right so let me run it let me run it right so uh this is a solution so full right so uh this is a solution so full of time this is time all of them right of time this is time all of them right for the space this is space for the space this is space i mean constant sorry so constant i mean constant sorry so constant followers space all of them for the time followers space all of them for the time and this is the solution and i will see and this is the solution and i will see you next time bye | 2024-03-24 10:46:35 | 334 | LeetCode 334 | Increasing Triplet Subsequence | Comparison | Java |
|
s6nManxW_aU | That show, Hello friends, Tech's new video and 175, today is a very special day because we have to steal, not actually, etc., through this question, this is the not actually, etc., through this question, this is the house road and this is Google's question house road and this is Google's question and Google has made such a good question and Google has made such a good question that it is fun to see this question. that it is fun to see this question. that it is fun to see this question. mean, I will teach you the basic of diner programming. Okay, so we have that problem. What else has to be done is that you have to steal from the houses. Now we can steal as much as we can Do it, if you have decided Do it, if you have decided Do it, if you have decided then message me that means we all are getting ₹ 1 then message me that means we all are getting ₹ 1 for ₹ 2. This is the issue, otherwise you for ₹ 2. This is the issue, otherwise you could have stolen all the groups but did could have stolen all the groups but did not give the condition that Edison should be hot and should not give the condition that Edison should be hot and should not be adjacent to him. not be adjacent to him. not be adjacent to him. here then friends you can't do it, if you can't do it with two cars, you can't do it with three or you can't do it with one, okay, there should not be Edison people, so you have to maximize the stolen goods, okay, then The more it is, the better it is, The more it is, the better it is, The more it is, the better it is, like here I steal Vansh Bhanwari, this like here I steal Vansh Bhanwari, this can also be done, can also be done, steal the vehicles that come to it and steal the vehicles that do it, steal the vehicles that come to it and steal the vehicles that do it, but that is less, meaning it but that is less, meaning it should not happen that no matter how much you should not happen that no matter how much you should not happen that no matter how much you care of this, then we will try a lot, let's get to that, let's should be here, just pay attention to this, if we should be here, just pay attention to this, if we start, then start, then anyone, anyone, if you have caught the forest, then after we all if you have caught the forest, then after we all From side to side, From side to side, you can also go towards side, these you can also go towards side, these lines are fine as per your wish, if you lines are fine as per your wish, if you move from side to side, then there can be no problem, then when move from side to side, then there can be no problem, then when water option comes, then we go to the same option, water option comes, then we go to the same option, then we see that from side to side then we see that from side to side then we see that from side to side is bigger, three comes from here, it is complete from here, so why I, this has become our answer, one thing we understand is that if we catch something from here, if we Those who will be caught, it's Those who will be caught, it's Those who will be caught, it's okay if we only okay if we only look at you, then you are in look at you, then you are in front of us, whichever maximum front of us, whichever maximum suits you, when people look at us and suits you, when people look at us and off, then what are we doing here, off, then what are we doing here, who should do this, tell us about this relationship, okay. who should do this, tell us about this relationship, okay. who should do this, tell us about this relationship, okay. maximum, one of each will be closed, but the rest of Bachchan's is fine, that is, whoever we are, we will stop his height plus, from whose two till the end, we will be We will We will We will see from A to N, all the positions are there, see from A to N, all the positions are there, okay, either I name these two, it will be okay, either I name these two, it will be our maximum that we can rob from Le our maximum that we can rob from Le Ban and even watchers, Ban and even watchers, see the difference, there is no problem, okay see the difference, there is no problem, okay either. either. either. this, do not remove the middle one, then further reduce our relationship in this way, this relationship will work. Okay, so this thing has to be kept in mind in DP, if we can tell I have understood from this I have understood from this I have understood from this that our logic is that if it is 1231, then that our logic is that if it is 1231, then okay, now I can message you, okay, now I can message you, create this problem and then create this problem and then after that, we go from behind and ask the question. Okay, after that, we go from behind and ask the question. Okay, if there are living beings here to see before the front to if there are living beings here to see before the front to understand. understand. understand. we are right at the starting point here, so I have one option, so choose one, I have written it right there, okay now I have also made this wall, you have accepted that I have come to the wall, now let me If I have the If I have the If I have the option to choose one then I will option to choose one then I will talk from the side. I will talk for Rs. 2. Okay, you find the talk from the side. I will talk for Rs. 2. Okay, you find the discussion on Churna Two Three interesting discussion on Churna Two Three interesting because now we have reached Three, so we have because now we have reached Three, so we have two types of questions here. two types of questions here. Force. Force. Force. point to create so what will we do if someone uses it because we will feel the difference of forgery and if it reaches our own then we will have to see that we cannot take the exempted one, we can take the free one. After that, which of these two is the two, then the tubeless 180 is free, isn't it free, or we use one of them, then we use two, then after being young and tied, neither will I have So definitely you So definitely you So definitely you will do something else, then ultimately after going there, will do something else, then ultimately after going there, I understand one thing that there is so much I understand one thing that there is so much trouble that we are having trouble seeing everyone, when trouble that we are having trouble seeing everyone, when we came here, we had this from the plate, we came here, we had this from the plate, then the tea here is like Kishore. then the tea here is like Kishore. then the tea here is like Kishore. look at the previous two value, then we just have to keep in mind that the previous two value has to be caught and our answer will be Nimesh Maxima. It is okay that ultimately the results that come are coming by special judges and if you want to We know We know We know that it is better than doing one plus two, let that it is better than doing one plus two, let us do something else, okay, so this is our us do something else, okay, so this is our simple method, its code is also similar, so now simple method, its code is also similar, so now we have understood what we will do, we we have understood what we will do, we accept it if we need the previous values. accept it if we need the previous values. That Robber Near Auto is what it is 0 If That Robber Near Auto is what it is 0 If we find anti in it then we will stitch our we find anti in it then we will stitch our stomach and believe something like this stomach and believe something like this that R1 is r2 and this is their value so for that R1 is r2 and this is their value so for any norms I have handed over our temporary patience to any norms I have handed over our temporary patience to here. here. here. moving forward with one value, we will take the temperature evening, we will take the maximum, and it is theirs, we should leave the rally between R1 and America and do not want to catch the adjustment, so those who will Tubelight was Tubelight was Tubelight was born in this country, that police station was Jaisalmer and the copy was born in this country, that police station was Jaisalmer and the copy was told that you keep it away, it told that you keep it away, it is 4 crores by adding these three, otherwise whatever will go ultimately will go to is 4 crores by adding these three, otherwise whatever will go ultimately will go to our tempo, and while doing this, our tempo, and while doing this, our potato will be the our potato will be the same in the list when it is finalized. same in the list when it is finalized. same in the list when it is finalized. idiot, how simple it is to be explained, if logic should come then enter then always convince him and in Bloody Mary, you are giving with me, it was a good problem, it is such dynamic, lots of contacts will come, so like the Do Do Do n't forget to subscribe the channel, how are you watching n't forget to subscribe the channel, how are you watching in the tagged with family video. | 2024-03-21 14:34:46 | 198 | Leetcode 198. House Robber. Python (Dynamic Programming Best Example ) |
|
exvE4-JUfFs | welcome to september's leeco challenge today's problem is reverse only letters today's problem is reverse only letters given a string s reverse the string given a string s reverse the string according to the following rules according to the following rules all the characters that are not english all the characters that are not english letters remain in the same position all letters remain in the same position all the english letters lowercase or the english letters lowercase or uppercase should be reversed uppercase should be reversed normally when we reverse a string we normally when we reverse a string we have a two pointer solution we have one have a two pointer solution we have one pointing to the left and one point to pointing to the left and one point to the right and what we'll do is swap the the right and what we'll do is swap the two and then increment the left pointer two and then increment the left pointer one and then decrement the right pointer one and then decrement the right pointer one but here we only want to reverse one but here we only want to reverse letters letters so so all we need to do is put some sort of all we need to do is put some sort of condition condition to either increment our left pointer all to either increment our left pointer all the way up until we see a letter or the way up until we see a letter or decrement our right pointer all the way decrement our right pointer all the way up until we see a letter and we have to up until we see a letter and we have to make sure that the left and right make sure that the left and right pointers don't cross pointers don't cross so let's initialize first our left and so let's initialize first our left and right pointers to be zero and length of right pointers to be zero and length of s s next i'm going to convert our string to next i'm going to convert our string to a list to make swapping easy a list to make swapping easy and normally when we do a reverse and normally when we do a reverse algorithm we say while l is less than r algorithm we say while l is less than r let's swap our letters s of l let's swap our letters s of l sr equals s of sr equals s of r r s of l s of l and then we and then we increment our left pointer and decrement increment our left pointer and decrement our right pointer right our right pointer right but we're gonna have to have an extra but we're gonna have to have an extra condition here we'll say while condition here we'll say while uh uh s of l s of l we're going to use the is alpha function we're going to say while it's not an alphabet letter we are going to increment this left pointer but we also need to make sure the left and right pointers don't cross so we'll do this and all we have to do now is the same but we'll be decrementing instead but we'll be decrementing instead finally we turn the finally we turn the s s lit uh string we'll do a string join and that should be it so let's make sure okay it didn't work okay i have to do a minus one for the okay so that looks like it's working and accept it so time complexity is of n and space complexity would be the same because we have we're creating this into yep that's it i don't think there's yep that's it i don't think there's anything i'd love to say so thanks for anything i'd love to say so thanks for watching my channel remember do not watching my channel remember do not trust me i know nothing | 2024-03-25 10:56:48 | 917 | Leetcode - Reverse Only Letters (Python) |
|
t8p5FS6flw8 | Hello friends, welcome to the new video, question number 84 is the list of DS question number 84 is the list of DS rectangle in histogram, Arya's rectangle in histogram, Arya's question is tax question, other question is tax question, other category is your DP energy question, you category is your DP energy question, you guys will get the interview with us guys will get the interview with us on Google Facebook Amazon, let's start. on Google Facebook Amazon, let's start. on Google Facebook Amazon, let's start. question is that you have been given an interior, basically the height has been known, you have to make a histogram using that height and from the histogram you have to find the largest rectangle, which is the largest rectangle being formed and finally you have to find the area of that rectangle. So you will see this program, you have created this interior using one, you are looking at the diagram in front and which of these is the largest rectangle being formed, many rectangles are being formed, you will see that the largest rectangle is being formed, Take and two Take and two Take and two units below the width, then it is 5.22 because units below the width, then it is 5.22 because 2 blogs and five units, if we 2 blogs and five units, if we consider the height of both, then we can consider the area of this rectangle as 10 units, consider the height of both, then we can consider the area of this rectangle as 10 units, so first of all we so first of all we make this program, we make this program, we took out the largest rectangle in it and we used it. took out the largest rectangle in it and we used it. understand it in a little detail. Let's start with the large rectangle in understand it in a little detail. Let's start with the large rectangle in histogram. In the question, we are given an integer of height. And that leg is given to given an integer of height. And that leg is given to you to create a histogram using the interior height you to create a histogram using the interior height and that program. and that program. and that program. tell the area of the largest rectangle, then do not get confused now, now let us see how we can make a histogram by using this height increase a are, so first let's make a histogram. Okay, so you will see that Let's make Let's make Let's make height two, okay, then height one, okay, height two, okay, then height one, okay, then height five, then height six, then height then height five, then height six, then height two, and then our height is three, so you two, and then our height is three, so you will see these tears, we have given the height, will see these tears, we have given the height, we have made a histogram of height, now what to extract we have made a histogram of height, now what to extract now. now. now. where the largest rectangle is being formed and return its area, so basically you will see that many rectangles are being formed and we will also see some examples and then we will see which one is being formed the largest and First let's look at some small First let's look at some small First let's look at some small rectangles, what can we get in it, I can rectangles, what can we get in it, I can see a rectangle, see a rectangle, what is the height of this rectangle, the height is what is the height of this rectangle, the height is looking at it, it is two, what is its method, it is a looking at it, it is two, what is its method, it is a single block, so its is with one and its single block, so its is with one and its area is area is area is area, so into one, okay, and what will we keep in it, I live in Adams and you guys will know what are rectangles, so this time, let's make a slightly bigger rectangle, It is also It is also It is also being made, okay, what is the height in this rectangle, all these features have one height and you will see that the height all these features have one height and you will see that the height is one and what is its width, you is one and what is its width, you will see that it has a height from 6 blocks, so 6 will see that it has a height from 6 blocks, so 6 breads. breads. breads. six, your area will be six, okay and any rectangle can be formed, let's try a rectangle, this is also being formed, what is the height in it, these two which are plus, the height in both is So So So you will see that if there are two blocks then its west will be you will see that if there are two blocks then its west will be our two so its area is our two so its area is ours basically you will see that 512 two ours basically you will see that 512 two is our area tan and apart from me is our area tan and apart from me this is the largest rectangle being formed this is the largest rectangle being formed in our example and its area tan in our example and its area tan returns us. returns us. returns us. then I do not think that a bigger rectangle can be made than this. Okay, so in this question, we have to find the area and you must have seen that we have been given, we have been given the height, where is the problem coming, the problem is It is coming in and we have to find the It is coming in and we have to find the It is coming in and we have to find the area. Okay, we have to find the area and the height has been given to area. Okay, we have to find the area and the height has been given to you, so if we work a little hard to you, so if we work a little hard to find the width, then we can do this question. So find the width, then we can do this question. So now whatever concept we now whatever concept we understand, basically our focus will be that we have to understand, basically our focus will be that we have to find the width. find the width. find the width. and see how we can find out the width. Let's take some examples and in this I am sitting in my block with a height of one and that one and I am seeing how far I can stretch to the right. And there can be deadly tightness in the chapter and basically you see my position, I am with my height one, which is my index, the second induction which is ours, we are sitting on it and we will see to what extent we can test it on the right and left. We got every position to see how far the wid could go We sucked our height one and saw how far this stretch could go So we got the idea that these could be classic We are We are We are sitting at our height five and at height five, if we go to the left then basically our French is not working. If we go to the right, there left then basically our French is not working. If we go to the right, there is an A of six length, then it will stretch to the right, then is an A of six length, then it will stretch to the right, then we will know that our we will know that our width is two and where we are sitting. width is two and where we are sitting. width is two and where we are sitting. sitting at our height five, so from there you can see where we can go left and how far we can go right and let's see the example, where are you sitting this time, what are you sitting on the second last index app His height is also two, okay His height is also two, okay His height is also two, okay and he is on the left, your three positions and he is on the left, your three positions are left, tractor thief and on the right, you have are left, tractor thief and on the right, you have access to one more question, so basically if access to one more question, so basically if you look at each position, what can you find out, you look at each position, what can you find out, at each position, if you look at the left. at each position, if you look at the left. at each position, if you look at the left. touch and the right boundary and the left ventricle is the left ventricle, so you will get the height and height. You know the height is your two. Basically we have taken out the with, so how will we calculate. Let's start with the. We have to calculate with, let's take an example. Index five, let's take the index and we have our value feedback and this is our index two, so from here we will see that on the left there is no stretch happening anywhere else on the right, we track one position forward, okay and These are These are These are some of our indexes, so what we have to do is some of our indexes, so what we have to do is we have to see left ventricle and right we have to see left ventricle and right ventricle. ventricle. How to get a good sweater. You have to see How to get a good sweater. You have to see that the five can stretch to the left till the point that the five can stretch to the left till the point where something greater than 585 is where something greater than 585 is found on the left and the five on the right. found on the left and the five on the right. found on the left and the five on the right. can this be true, if the fiber is found bigger than the fiber on the right, it is fine and if it is found smaller, it cannot be stretched, then what do we have to do, you see, whichever is found smaller first on the left, If you find it If you find it If you find it small, take it Rawdi, then the small, take it Rawdi, then the left ventricle left ventricle is small on the left, I can see it on index one and if I is small on the left, I can see it on index one and if I go to the right, this is six feet two, then on the right, it is go to the right, this is six feet two, then on the right, it is small on index four, so if I small on index four, so if I see the left and right boundary, then I can see see the left and right boundary, then I can see see the left and right boundary, then I can see right boundary is the expomore where the smaller one is found first and the smaller one is on the left, index one, so my five can be stretched in between, I have taken these left and right boundaries, so now using the laptop by Find out Find out Find out that if you do - then you will see your free that if you do - then you will see your free coming but we have seen that I was left and coming but we have seen that I was left and right boundary so to balance right boundary so to balance we will have to do a little minus one, then we will have to do a little minus one, then exactly we will get our two blocks exactly we will get our two blocks because you have caught the left boundary and because you have caught the left boundary and because you have caught the left boundary and you have caught the right boundary, then to find the middle length, you have to do minus one once, then you will get its exact width. Okay, so in this way we can find the width and you have come to know that you So now let's start So now let's start So now let's start and see at each position and see at each position how we will calculate the with. Let's take the first position how we will calculate the with. Let's take the first position and at the first position we are going to do the same. We will calculate separately how we can stretch on the left and calculate separately how we can stretch on the left and how far we will reach on the right and how far we will reach on the right and how far we will reach on the right and and cannot be calculated together and then we will calculate our total and if you go to the court, then you know we will combine it for example, it is not difficult, it becomes very combine it for example, it is not difficult, it becomes very easy to implement and I will explain easy to implement and I will explain it in detail in the court. it in detail in the court. it in detail in the court. but right now we are just focusing on where is the stretch on the left side and the ear shape on the right side and do not want to get into technical terms like state etc. If we understand the details in the chord then let's just And let's And let's And let's see, the thief can come to the right see, the thief can come to the right and we will find all our boxes in the middle and we will find all our boxes in the middle and we will take out our belt, so and we will take out our belt, so first let's calculate the left, it first let's calculate the left, it cannot be calculated simultaneously, okay the left cannot be calculated simultaneously, okay the left will stretch till there. will stretch till there. will stretch till there. small but now if we go to the left, if you are sitting 0n extra then there is nothing on the left otherwise you can consider it small. Hey, if you go out then basically we will go before zero, then there is a minus one index, If you don't find it then If you don't find it then If you don't find it then you you will select the left boundary right there on the hair, we have to will select the left boundary right there on the hair, we have to select something left behind, where we are select something left behind, where we are sitting, we cannot consider it as love there right boundary, sitting, we cannot consider it as love there right boundary, so even if that is the first position, so even if that is the first position, then left front is you. then left front is you. then left front is you. minus one is fine and we are not taking out the right boundary right now. Now let's move ahead. The next number is one. What is its left laundry, meaning where are you getting the small one in the left, till then it can be our actual. If you go to the left then it is Ours is not small and if you go before two, then if you Ours is not small and if you go before two, then if you Ours is not small and if you go before two, then if you go out of the key, then go out of the key, then we will have to consider minus one as the left boundary. we will have to consider minus one as the left boundary. Okay, let's come to the next number. The next number is the Okay, let's come to the next number. The next number is the electronic of five five. How far electronic of five five. How far can 572 be smaller than 5 can 572 be smaller than 5 in the left? in the left? in the left? from there it will stop being straight, that loop will be laundry, so before 5 you will go, there is one and that is small and one is our index at one, so we have written one here and we are doing this Basically we have to Basically we have to Basically we have to save the index or right-left index, save the index or right-left index, then you will also get problem with it. Okay, then you will also get problem with it. Okay, don't get confused in this. We are don't get confused in this. We are doing inductive. Let's move ahead. The number is doing inductive. Let's move ahead. The number is our six. Six is Lu. our six. Six is Lu. How far can we reach, if in the left. How far can we reach, if in the left. How far can we reach, if in the left. something smaller then it will stop being straight, that will be our lace for entry on the left, you will go five, if it is small, then the left grinder for heights is our two, index two heights, go up, go forward, How How How far will the test go, you have to see, small one will far will the test go, you have to see, small one will go to the left, it is not small and you will go to the left, it is not small and you will go to the left, five is not small and you will go to the left, one is our small one, go to the left, five is not small and you will go to the left, one is our small one, so our left so our left boundary is the index 54, which is our two to have a. boundary is the index 54, which is our two to have a. We have found out where. We have found out where. We have found out where. end, okay and right now we are not seeing the stretch on the right, let's move ahead number 3 is free to the left, till what is possible, if something small is found on the left, it will stop being straight, To is getting, you are small, to is To is getting, you are small, to is To is getting, you are small, to is on the index for, so for our free height, the on the index for, so for our free height, the left boundary of which is where we left boundary of which is where we can consider this tree, okay, now let's can consider this tree, okay, now let's look at the right truth, okay and start from the first number, the look at the right truth, okay and start from the first number, the first number is yours. first number is yours. first number is yours. they are in the right angle, you will see, take this one in the chord, we play it a little in reverse, but for the sake of understanding, I am starting from the first position, now we see which one is smaller on the right, so we have the Let's start from the last position, Let's start from the last position, Let's start from the last position, but here I am doing an interest first, so where we get but here I am doing an interest first, so where we get Chota on the right, Chota on the right, our straight will stop, so if there our straight will stop, so if there is one to the right of Two, then Two cannot be stretched further, is one to the right of Two, then Two cannot be stretched further, its index of in and one. its index of in and one. its index of in and one. made, then write it here, okay, now the next number is one, one is right, how far can it be true, one will go to the right, five has stretch, and you will go to the right, this can be stretched, and you will go to the right, There can be a big stretch and you will There can be a big stretch and you will There can be a big stretch and you will go to the right for three. There can be a stretch here too go to the right for three. There can be a stretch here too and you will go to the right. If you go out of Anti Zara, and you will go to the right. If you go out of Anti Zara, then we have not found any small one. then we have not found any small one. Our height one Our height one can be tight till the end right. So can be tight till the end right. So can be tight till the end right. So what will we write? Nothing small was found, Minty, that you came out earlier. On the left, you wrote your minus one. Here, if you come out, you have to write six because your integer index is up to five, so You will write six You will write six You will write six because we got height one, ours kept getting stretched, because we got height one, ours kept getting stretched, nothing small was found. Let's come to the next number. The nothing small was found. Let's come to the next number. The next number is five. next number is five. How far can it be true in fibroid? You will go fibroid, there can be a How far can it be true in fibroid? You will go fibroid, there can be a stretch in six and you stretch in six and you will go right, two is small here. will go right, two is small here. will go right, two is small here. possible then two candidates are for then write for on the next number that six six how far can it be true the next number two cannot be small at this stage index of two write for f4 come on the next number now the height of our two The height can be a mistake The height can be a mistake The height can be a mistake because it is the right method and if we find any small jar, we because it is the right method and if we find any small jar, we will close it there but the right method will close it there but the right method is it can be stretched and in the right you have the is it can be stretched and in the right you have the interior. If you go out, then our interior. If you go out, then our height can reach till the end of 21 cm, height can reach till the end of 21 cm, then come out. then come out. then come out. boundary, we will have to take six because we have to take some left and right dongri. Okay, the last number three is free. How far can we stretch? From three, we will go to the right and we will go out. Hey interior applicants, It It It became a bit tricky left and right and became a bit tricky left and right and I had told you how to calculate the width I had told you how to calculate the width for every position. for every position. You know the height. Which height You know the height. Which height can be tested to what extent in the left and right. It can be tested to what extent in the left and right. It is a simple formula. is a simple formula. Apply it and you will easily remove the fast. We have Apply it and you will easily remove the fast. We have calculated the height, we have calculated the height, we have given the entries about it and we can easily calculate the area, given the entries about it and we can easily calculate the area, so we just have to focus on so we just have to focus on how we will calculate the width. Now let's come how we will calculate the width. Now let's come to the cord and tax implement it. to the cord and tax implement it. We will understand in details and we will We will understand in details and we will also do the final calculations in the court. So we will start the area also do the final calculations in the court. So we will start the area and come to the court, we will and come to the court, we will check the court. We will do the same in the court check the court. We will do the same in the court as we saw in the diagrams by finding as we saw in the diagrams by finding out the main focuses or with and then out the main focuses or with and then a line or two. a line or two. a line or two. out the area. The giver in the question has given the interior height and we have seen every height till which height is the fatal stretch on the left and we can say thief on the right, so a We used to go to the We used to go to the We used to go to the height and see what height and see what rectangles are being formed. We will find out the area of all the rectangles, rectangles are being formed. We will find out the area of all the rectangles, which will be the largest area, we will return the which will be the largest area, we will return the biggest rectangle to the Lokayukta, biggest rectangle to the Lokayukta, but the main focus will be on but the main focus will be on how the width has been calculated. Finding the area will be how the width has been calculated. Finding the area will be of one or two lines. of one or two lines. of one or two lines. what did you see in the diagram, you did not draw the left boundary and made the right boundary. Okay, so let's do the same in the court. I will draw the left boundary and make the right boundary. Okay, let's copy And let's make the right one. And let's make the right one. And let's make the right one. Okay, Okay, okay. And you saw that the left and okay. And you saw that the left and right boundary was drawn and using it right boundary was drawn and using it you had calculated our fast at every point. you had calculated our fast at every point. So let's make the height of one person also. So let's make the height of one person also. Okay. Okay. Okay. right dongri is coming out and by calculating the width you will fail about the interior. Okay, then we will get the height and width, so we can get the single line code by multiplying all our rectangles, patience, okay and I said. We will use the technique of giving left and right boundaries and folding it, so basically if you do not use check then it will become very complicated and if you use step then the simplest way is what is starch? So let us make this pack and We will understand how these are failing due to tagged, we will We will understand how these are failing due to tagged, we will We will understand how these are failing due to tagged, we will get help from the track, okay, get help from the track, okay, okay, and in the left, okay, and in the left, very basically, did we mince the boundary, did we index very basically, did we mince the boundary, did we index left induct, where did we reach the intersection, right left induct, where did we reach the intersection, right index - what did we do by index - what did we do by removing the boundary. removing the boundary. removing the boundary. so first let us understand, then we will start, let's take an example, this is our example, okay, so this is our example, what do we have to do, We have to We have to We have to fill, okay, let's fill, okay, let's make the top and first make the make the top and first make the foil, which one will be on the right then okay, so this foil, which one will be on the right then okay, so this left interior will be our fill and left interior will be our fill and we will use the step in this, we will do this, am I we will use the step in this, we will do this, am I making an extra one, why not write in the court? making an extra one, why not write in the court? making an extra one, why not write in the court? making it because I want to do it, I don't want to install it, I will show it to you with numbers so that you do n't get confused, and also I am making the index by taking 2 inches, I will put the number also, I will put it in one, so as you want to understand, understand it No, it's okay and we No, it's okay and we No, it's okay and we will do it. What should we do basically? We have to frill the will do it. What should we do basically? We have to frill the left boundary of left boundary of ours and then hit the ride ours and then hit the ride entry to feel it and go out with it, entry to feel it and go out with it, then to remove the weight, then to remove the weight, we will have to walk, we will talk about the complete entries. we will have to walk, we will talk about the complete entries. You will have to run the loot, okay so first let's write You will have to run the loot, okay so first let's write this this and at every position you have to see the left boundary and at every position you have to see the left boundary and the right boundary. Okay, and the right boundary. Okay, so this distance is being calculated but so this distance is being calculated but basically it should be that I remove this for the left. basically it should be that I remove this for the left. First I will take this leader of the left, First I will take this leader of the left, okay and after that I will copy this, okay and after that I will copy this, I will say this for the right, okay I will say this for the right, okay and we will feel the track from the stand, it will take a little and we will feel the track from the stand, it will take a little help, how will the scalp be placed in it, help, how will the scalp be placed in it, that Arthur, you will paint the first position above, you that Arthur, you will paint the first position above, you know. know. know. then it is 200 index, so ours is on zero index. Okay, so there is something small in the two to the left. We have to see what is small in the two to the left, there basically a will stop, so tuition is If it is not small, then the left If it is not small, then the left If it is not small, then the left boundary will be our interior. If we boundary will be our interior. If we go out, then the left boundary will go out, then the left boundary will be our minus one as we saw in the diagram. be our minus one as we saw in the diagram. Okay, so the left front will be ours. So, Okay, so the left front will be ours. So, in the beginning, we say that if in the beginning, we say that if your step is in the camp. your step is in the camp. your step is in the camp. can support it in such a way that if you eat the stock then you can close the left boundary, okay, there is no problem in this and as soon as you Do Do Do n't put the number, you have to put it intact. n't put the number, you have to put it intact. I am also showing you by putting the number. We will put ascended in the pot. There is no need to put so much double. So whatever is its index key. Okay, now we will move ahead. We will put ascended in the pot. There is no need to put so much double. So whatever is its index key. Okay, now we will move ahead. Now we will come. Our next number is Now we will come. Our next number is How far is the stretch going from one to the left? If there How far is the stretch going from one to the left? If there is a bigger number on the left then this will continue to be true is a bigger number on the left then this will continue to be true because you will see that it because you will see that it can be made inside the toe also. Then it is possible that if there is a can be made inside the toe also. Then it is possible that if there is a bigger number on the left then one would be your bigger number on the left then one would be your stretch. stretch. stretch. okay, so we have to find the left boundary and the current data of the boundary will not maintain our step. So if I tell you that the SP of one is half, then it is okay if it is small as long as it is small. That left mustache will continue to grow, it will grow like Gulf country, if you are removed, then it will continue to be your space. Okay, so as long as yours is small, that means two, this one is yours, as long as it is small, that loop will match, How will you do the account? If How will you do the account? If How will you do the account? If your account is broken then you will compare it with the tax. your account is broken then you will compare it with the tax. Okay, you will write tag dot pick Okay, you will write tag dot pick because no number was given in this test. because no number was given in this test. This tag is our index. So This tag is our index. So here you will take out the contact from stat at peak here you will take out the contact from stat at peak and our one. and our one. and our one. we compared one with two. If yours is small then keep sketching because one will be your feel. It is okay in the rectangle. Keep stretching and okay then keep Clear this track, Clear this track, Clear this track, Josh is getting so stretched, Josh is getting so stretched, clear the step because the clear the step because the letter P will hold the boundary of the left, letter P will hold the boundary of the left, where will the laundry of the left go and stop, where will the laundry of the left go and stop, okay check, maintain the data and keep doing it, keep doing it, okay check, maintain the data and keep doing it, keep doing it, so we got the left so we got the left key. key. key. and if this entire track gets empty then you know that - it will be made in actual, here if it gets completely empty then we will close again - but if it is This index would have This index would have This index would have been 082 and our one stretch by chance would been 082 and our one stretch by chance would not have been finished, we would have caught from the stag that we had not have been finished, we would have caught from the stag that we had entered this club, if one was entered this club, if one was not vacant then we would have written the balance, you would have picked up the left not vacant then we would have written the balance, you would have picked up the left boundary, we would have picked up from this tax, boundary, we would have picked up from this tax, you would have picked up whatever stock is in the future. you would have picked up whatever stock is in the future. you would have picked up whatever stock is in the future. okay, this is the index and this number was not there, so I used the index to find this number and you have an index here, if it is jhali - if it is not happening, then That one will be on That one will be on That one will be on your leg boundary. Okay, and he your leg boundary. Okay, and he doesn't understand the concept. If you look back a little, doesn't understand the concept. If you look back a little, we will keep doing it in this manner we will keep doing it in this manner and then what we are going to do is like we will be and then what we are going to do is like we will be facing forward, this is our well which was already empty facing forward, this is our well which was already empty so we will add our number. so we will add our number. We will do this in the take. We have discussed that the way we We will do this in the take. We have discussed that the way we do movies, now we have five main points, so do movies, now we have five main points, so we have added the index and whatever number is in the set, we have added the index and whatever number is in the set, so in the last here you also have to do this so in the last here you also have to do this before starting the process. before starting the process. before starting the process. missed is to add in this. Next number is our five and decide that maintains the data. Okay, so basically what you will do now, now you will come here in your loop, you will see that five is your small The stock is empty, The stock is empty, The stock is empty, we are not feeling it. The track is we are not feeling it. The track is not even empty, it is not feeling crisp. not even empty, it is not feeling crisp. Now you will see that if you put the pick of the step, Now you will see that if you put the pick of the step, then the number in the pick of this track is then the number in the pick of this track is one and the index of this number is Now we will put the spider in some tags before becoming the moong Now we will put the spider in some tags before becoming the moong and put its index two and put its index two in the strat. Okay and we will come to six and we will in the strat. Okay and we will come to six and we will learn, we will see that ours learn, we will see that ours will be small so left. will be small so left. will be small so left. our six is small or not, urban bodies, if the first condition fails then only the step is done - you had put one, but the pick of the week, put it in the back of the stock, your how to induction number five and October. Total two, come and move ahead, I told you before moving ahead, let's do statement TV. Okay, that was the last step. Let's put it in the track. Let's do the number. Let's put it in the set. Now we have moved ahead. But you have to watch it. If the phone is smaller than 6 then vacate this track. If If the phone is smaller than 6 then vacate this track. If If the phone is smaller than 6 then vacate this track. If your phone is smaller than 5, vacate this track. The your phone is smaller than 5, vacate this track. The phone is ok. We had seen this. Keep emptying it from phone is ok. We had seen this. Keep emptying it from so that so that you can catch the left boundaries of yours. You are not small, this is better than one. you can catch the left boundaries of yours. You are not small, this is better than one. We have come to one. We have come to one. We have come to one. are not half small, then toe cannot be touched till the back, okay, so we have made this first empty, now come down, it was empty, by August, it would have been completely empty, then we would have put minus one, If there is anything left, then whatever If there is anything left, then whatever If there is anything left, then whatever index is there in the pick of this track, index is there in the pick of this track, put it here. If there is one in the pick of the stock, then we will put it here. If there is one in the pick of the stock, then we will put one here put one here that before proceeding further, we make an entry, put that before proceeding further, we make an entry, put our number in the track and our number in the track and this index this index this index our four, okay now we see that ours is smaller than the number behind, not the number behind, the number in the stock, but the smaller one is not ours, so I will The stock is The stock is The stock is not empty either, otherwise let's put minus one. not empty either, otherwise let's put minus one. Now put whatever induction in the pick of this track. Now put whatever induction in the pick of this track. Basically the index in the take care pick Basically the index in the take care pick is our four, so you will is our four, so you will come to your left boundary and put it here. In come to your left boundary and put it here. In this way, on your left. this way, on your left. this way, on your left. and you can also create a right boundary using this. If you copy this code and use the same concept, you can also create a bride entry and I think you can understand by yourself what to do with this minor change. Let me tell you that you have to run it a little in reverse. Okay, you will run the loop in reverse and do it in this. Will we run it in this way and will do I - - and will see from the last position. If there is a step at the last position, then this time we will This time we took six obstacles, meaning This time we took six obstacles, meaning This time we took six obstacles, meaning we had gone to the right about our interior. we had gone to the right about our interior. In the last, we had In the last, we had our ant going up to index five, so we will our ant going up to index five, so we will feel like the diagram we saw feel like the diagram we saw and the rest of the code will not change, the code is yours. and the rest of the code will not change, the code is yours. and the rest of the code will not change, the code is yours. SIM will remain, you just have to write it and ride it and you write it in this way, we, I, you, and there are minor conditions in it and I would like to change, whenever you check in the tech, One more condition was to be seen One more condition was to be seen One more condition was to be seen whether your tech is empty or not. whether your tech is empty or not. In MP state we never check, so In MP state we never check, so it was to be seen that this condition should run till our note MTO. If it was to be seen that this condition should run till our note MTO. If these tags are never checked, these tags are never checked, then one more condition was imposed. then one more condition was imposed. And when you have used the first one, then And when you have used the first one, then clear the text because we need clear the text because we need friends' take for Rawdi, so friends' take for Rawdi, so clear this track also and you can remove the right and clear this track also and you can remove the right and left boundaries using the same logic. left boundaries using the same logic. Now what to do? Now what to do? You have found out the area. Okay, You have found out the area. Okay, how will you find out the area? So how will you find out the area? So next we have found the boundary for the area. So to find out the with, let's next we have found the boundary for the area. So to find out the with, let's run the loot once more. Okay, there is run the loot once more. Okay, there is not much else, we not much else, we will hit a little shortcut in the court. Now there will be more in the lap of two lines. will hit a little shortcut in the court. Now there will be more in the lap of two lines. will hit a little shortcut in the court. Now there will be more in the lap of two lines. finish then how will they go through every point? What did I tell you? What did we do to go through every point? We did it from right to left. Okay, we went through every point and I So that in order to have a little balance, So that in order to have a little balance, So that in order to have a little balance, our right and left sides our right and left sides were stretched, so to balance, we had to do were stretched, so to balance, we had to do minus one, only then we minus one, only then we will know exactly how many blocks we have. Okay, now find out the will know exactly how many blocks we have. Okay, now find out the area, how will the egg come out at every point area, how will the egg come out at every point or else? or else? that whatever area you will calculate, keep calculating it that whatever area you will calculate, keep calculating it here and whatever is the maximum, it will here and whatever is the maximum, it will start, then how will you start, then how will you calculate the area, what should not be done to calculate the area basically, calculate the area, what should not be done to calculate the area basically, we need to know the height of each of our points. we need to know the height of each of our points. At that height you have to At that height you have to multiply it with this simple and mix and whatever is the multiply it with this simple and mix and whatever is the maximum it will start maximum it will start because we have run the function of map.com because we have run the function of map.com and finally return the area. and finally return the area. I think the work will be done. Let's return the I think the work will be done. Let's return the area. area. I should compile this, I think the I should compile this, I think the code is done, so I think last, this will code is done, so I think last, this will work directly for us, we will have to pick it quickly, work directly for us, we will have to pick it quickly, and this will become our and this will become our zero, this will be I plus plus, let's zero, this will be I plus plus, let's see this once. see this once. see this once. and let's cut it. Let's compile it, submit it and see that it is being compile it, submit it and see that it is being looted. We will have to make a change in the cord. We have written this loop You have to You have to You have to pop till it stretches on the left pop till it stretches on the left and you have to pause here and you have to pause here till it stretches and on the right we will see that if this type of thing continues till it stretches and on the right we will see that if this type of thing continues then basically there are while loops then basically there are while loops because there is no single condition where it will happen. because there is no single condition where it will happen. Till then, if we have to do it then we Till then, if we have to do it then we cannot write it in this loop and now let us compile it once cannot write it in this loop and now let us compile it once and submit it and check that it is and submit it and check that it is getting set. After submitting, let us see that getting set. After submitting, let us see that our code is also being successfully submitted. You You You can go to about section and mix Google set, can go to about section and mix Google set, you can see in the shape which you can see in the shape which video of interview questions I have made, which list video of interview questions I have made, which list question type video should I make, category, you question type video should I make, category, you can do voice search, channel related news, which can do voice search, channel related news, which video is going to come next, all video is going to come next, all You will get updates in this video. You will get updates in this video. Thank you very much for watching this video. Jai ho kar do ajay ko | 2024-03-20 12:32:31 | 84 | Largest Rectangle in Histogram (Leetcode 84) - Hard |
|
FoLSpCsQ0rA | guys hope you're doing 3r today's question is range some query immutable question is range some query immutable it's an easy question on gate code and it's an easy question on gate code and involves an emic programming as one of involves an emic programming as one of the possible solutions and I thought it the possible solutions and I thought it would be a good one to have on the list would be a good one to have on the list so the question says given an integer so the question says given an integer array nums array nums find the sum of the elements between find the sum of the elements between indices I and J I less than equal to J indices I and J I less than equal to J inclusive okay so I and G would be inclusive okay so I and G would be inclusive when it says that find the sum inclusive when it says that find the sum of elements between I and J right for of elements between I and J right for example given is this array and the sum example given is this array and the sum range 0 comma 2 so it means that 0 1 & 2 range 0 comma 2 so it means that 0 1 & 2 so the sum of these elements 3 0 and so the sum of these elements 3 0 and minus 2 which is 1 is the expected minus 2 which is 1 is the expected output and similarly the other values so output and similarly the other values so you may assume that the array does not you may assume that the array does not change change there are many calls to some rate there are many calls to some rate function so it means that this will be function so it means that this will be called again and again on this array called again and again on this array right the important thing to understand right the important thing to understand here is just this that there will be here is just this that there will be more frequent calls and at the first more frequent calls and at the first look it looks like a very very simple look it looks like a very very simple problem because whenever you get this problem because whenever you get this you can just run a for loop from that you can just run a for loop from that particular index to the J index from I particular index to the J index from I to J just some of the elements and to J just some of the elements and return the answer but it would take U of return the answer but it would take U of n complexity for each some range all n complexity for each some range all right so um let's just have a look at right so um let's just have a look at the various methods because this is an the various methods because this is an unsorted array so whatever approaches we unsorted array so whatever approaches we can use to solve questions on unsorted can use to solve questions on unsorted array and think about an approach where array and think about an approach where you can improve the solution from just you can improve the solution from just doing an oh F n for each some range one doing an oh F n for each some range one so please pause the video have a look so please pause the video have a look and come back so I think here it's quite clear that we need to think about how we can do it dynamically right because finding the sum between any two indices is basically more about you know a problem which we can divide into subproblems and have our handy results right such that we can just use those results without traversing the area again and again and be able to find the answer so we'll be using dynamic programming here and what I think we should do as a part of the solution is to four so basically for each index in the area right what we need to do is that we need to find the sum of all the elements in the array before that index right so for example in this array 4-2 there are no elements before it so it would be zero four zero there is minus two so it would be minus 2 4 3 so I've just written that down here yeah so so 4 minus 2 it would be zero four zero it's minus 2 4 3 it's sum of these two so again minus 2 4 minus 5 it is sum of all these three elements so 1 4 2 it's the sum of the elements before and so on right so now here as you can see that since the output that we are trying to create needs to have one element extra you would need to use a dynamic programming array of one size bigger right and why we need to do that is because the question states that we need to find the sum of the elements between the indices inclusive now if you don't do this basically when we if we store so so whenever you have to find for example some range 0 comma 2 right we would know that @dp of three we have a value which is the sum of all elements before three that is 0 to 2 right and at zero we would know that it has the value of all the elements sum of elements before zero which is of course nothing zero so we will just subtract that so for example if you see here if the question says 0 comma 2 we will go for DP of 3 which will have 1 1 - this will give us the and someone if you see 2 comma 5 so 4 5 will have to go 5 plus 1 6 so minus 3 minus 2 right - so which is minus 2 so minus 3 minus minus 2 which will give us minus 1 right so that's how we will be able to derive our results in row of one complexity we would have to do this process just once prepare the dynamic programming area because our area will not change and then you can just use it to get these values like that so let's just get started with the solution and it will become much more clear okay so as I said that we need to have an extra element in the DP array right I'll just create so now here in problems like these when you have two functions right and one of them is being called again and again you need to declare your collection or array whatever you are using outside of both the functions so that they are accessible in both of them so what we will do is that we just do this for the time being because we don't know the size of nums so that's why we cannot like initialize it we can only declare it effect and then here we will and plus one okay and since we will and plus one okay and since we will always know that DP of zero would be always know that DP of zero would be zero because there are no elements zero because there are no elements before zero so we just do that okay now before zero so we just do that okay now let's start the for loop so we start let's start the for loop so we start from one okay I less than equal to n from one okay I less than equal to n because we have n plus 1 elements in DPW because we have n plus 1 elements in DPW populate right and then I plus plus okay populate right and then I plus plus okay so now DP of I okay so the value of DP so now DP of I okay so the value of DP of I should be what so you need to think of I should be what so you need to think of it as a sub problem because if I am of it as a sub problem because if I am at 3 right and I want to if I am at 3 right and I want to if I am populating DP of 3 I want to populate it populating DP of 3 I want to populate it with the sum of elements of 0 comma 2 with the sum of elements of 0 comma 2 and I know that D P of 0 1 right which and I know that D P of 0 1 right which is here that contains the sum of is here that contains the sum of elements before 0 right so it contains elements before 0 right so it contains minus 2 so if I want to get this sum minus 2 so if I want to get this sum I'll just add 0 plus DP of this index I'll just add 0 plus DP of this index and that would go into this index right and that would go into this index right so so the DP of I minus 1 plus nums of I so so the DP of I minus 1 plus nums of I minus 1 right so DP of I minus 1 minus 1 right so DP of I minus 1 contains the sum of all the elements contains the sum of all the elements before I before I minus 1 and we add before I before I minus 1 and we add nums of I minus 1 to it which gives us nums of I minus 1 to it which gives us the sum of all the elements before I the sum of all the elements before I write so we just have to do this okay write so we just have to do this okay now if I minus 1 right you just have to now if I minus 1 right you just have to do this and yeah that's what that's also do this and yeah that's what that's also here and then in some range what we need here and then in some range what we need to do is that to do is that to return now you've been given GI and to return now you've been given GI and as I'm saying that the next BP element as I'm saying that the next BP element right so J if J is the index DP of J right so J if J is the index DP of J plus 1 will have the sum of all elements plus 1 will have the sum of all elements before J so what we do is that DP of before J so what we do is that DP of we'll take J plus 1 right because this we'll take J plus 1 right because this is the value of all the elements summed is the value of all the elements summed up before before J plus 1 right so it up before before J plus 1 right so it includes G as well now and we subtract includes G as well now and we subtract TP of I from it right so yeah this TP of I from it right so yeah this should work should work let's see okay let's submit it fine so as you can see that we were able to do it with just so you can mention that to the interviewer that nuns of early vote yes definitely take oh of n time complexity but the some the some the the method that from where we want to find the son that will take off one each time and this this complexity would be O of n as well because we are using a DP array of the same size so I hope you guys find this video helpful if you do please like share and subscribe keep coding and take | 2024-03-24 10:02:00 | 303 | LeetCode 303. Range Sum Query - Immutable [Algorithm + Code Explained ] |
|
CHmxwrmChtI | Hello Hi Friends Welcome Back Today We Are Going To Solve Tourist Co Problems A Going To Solve Tourist Co Problems A So Lets Start With The First Co So Lets Start With The First Co Problem 1446 Which Coating Actor Problem 1446 Which Coating Actor Now We Start Looking Into The Details Of The Now We Start Looking Into The Details Of The Problems And Their Solutions Is Meant To Problems And Their Solutions Is Meant To Mention Data My Channel Dedicated To Mention Data My Channel Dedicated To Help People Work Preparing for Coding Help People Work Preparing for Coding Interviews and Java Interview Samay Channel Has a Variety of Interviews and Java Interview Samay Channel Has a Variety of Problems Which Should Problems Which Should and Explained in Java Attempts of Different Varieties Light and Explained in Java Attempts of Different Varieties Light Dynamic Dynamic Programming Languages Problems Programming Languages Problems Binary Search Tree Is Graph Problems Binary Search Tree Is Graph Problems Deficiencies as Well as Spring Related Deficiencies as Well as Spring Related Interview Questions and Law Too Interview Questions and Law Too Frequently Frequently Frequently Questions Will Show A Few Of Preparations For Any Like Interviews Please subscribe this Channel Name 200 Lipstick Look Into This Problem The Power Of Spring Is The Maximum Length Of Not Entirely Something Which Contains Only One Unique Character During Its For For For example you have given its president senior example you have given its president senior character moral repeating this only one can give different character moral repeating this only one can give different characters and varied characters and varied to senior leaders have to return to the power to senior leaders have to return to the power of the thing so let's move and share and we will of the thing so let's move and share and we will discuss how they are going to solve this discuss how they are going to solve this problem problem problem twelve wealth and where seen switch on switch on meeting character bank account will increase in cases pay not repeating character account will get 300 seats for example account variables non so British one side se hui aa First First First Character Prayer Requests for This Character Prayer Requests for This Character Venter Character Nine Character Character Venter Character Nine Character Account Will Be Sworn in the Beginning Should Account Will Be Sworn in the Beginning Should Start with CD Sanseri Is Not Will Always Be Sworn in Start with CD Sanseri Is Not Will Always Be Sworn in with Previous Character It is Not with Previous Character It is Not Equal to a Shovel Dhundhala is the Account One is Always Equal to a Shovel Dhundhala is the Account One is Always Busy in His Life in the Busy in His Life in the Busy in His Life in the Team Previous Character And Will Go To Subscribe Now To Track Of Maximum Track Of Maximum Subscribe To Subscribe To Go To The Character Go To The Character Is Not Equal To Basically Dare Not Give Will Is Not Equal To Basically Dare Not Give Will Really Dose Really Dose Subscribe Will Go To The And Sunao Subscribe Will Go To The And Sunao Account Welcome To And Vigor To Country Account Welcome To And Vigor To Country Account Welcome To And Vigor To Country Control Vikram Free Life Due To Increment Account By Seeing Previous Character And When Doing Good Deeds Not Equal To Its Previous Character Seen So I Will Reach Initial Pure Account Deficit Which Occurs Loop Footwear Ka Test Match Vikas Hui Will Go Hui Will Go Hui Will Go To Duty Should E Capsule Keep To Duty Should E Capsule Keep In Preventing Account From One To Three In Preventing Account From One To Three Four Vs Four Vs Payment Yudh Rich Food Additive Would You Have Found Payment Yudh Rich Food Additive Would You Have Found For Consecutive Days Back To Her Cont Isko For Consecutive Days Back To Her Cont Isko And Max With Updated From Three And Max With Updated From Three To Four Wickets For You Have Singh Maximum To Four Wickets For You Have Singh Maximum Not Not Not VISIT CHARACTER THE DIFFERENT LIKE AND SHARE IF YOU WILL NOT WARY INITIAL DISCOUNT WORK PRO JUST RIGHT HERE ELECTION ACCOUNT IF SAMSUNG MAXIMUM ACCOUNT WHICH HAVE SCREENSHOT THIS FOR ELECTION KI ANY NOW A GO TO DESH TIGHT [MUSIC] 1234 Election Our Account Will Be Compiled For Five Minutes So Now With Five Years Account And Will Increment Our Maths 258 Developed 1520 We Will Put Forward Them A Current Affair We And After That Can We Go And Visit Duty Subha jaanu Subha jaanu Subha jaanu good account s one hour maximum good account s one hour maximum account assigned this five types and after death at jain urvi account assigned this five types and after death at jain urvi visit series different and visit series different and jewelery and standardized wave with differences jewelery and standardized wave with differences define this wiki previous define this wiki previous lives in vikas vihar different size different than lives in vikas vihar different size different than 200 will release account one so let 200 will release account one so let you listen you listen you listen To Front For Distic Special Song How To Return 501 Service Five 1,000 More Answers And You Can See There Fight With Answers For This Is The Back To Your Going To Solve This Problem So Latest Look Into The Implementation Any Problem Solve Back Create One Solve Back Create One Solve Back Create One Max and Account Variables Both Are One in Max and Account Variables Both Are One in the Beginning and Were Getting Through the the Beginning and Were Getting Through the Eyes Character of the Scream ACIT Switch Eyes Character of the Scream ACIT Switch Character Very Interesting and Wear Character Very Interesting and Wear Checking If-But Characters Matching Previous Character Checking If-But Characters Matching Previous Character Will Start from Character 1512 Always Will Start from Character 1512 Always See the Previous Character See the Previous Character See the Previous Character Fennel Matching Will Increase Your Account And Give Necessary Evil Updater Maximum Maximum Maximum Maximum Very Nice To Meet You Come Late Say Like 100 When Ever Visit See Right The Base Camp Till Character Meanwhile War Reinstalling Account One And Because Nau Target This Target This Target This Account Family Tree 12123 And This Is Like This Account Family Tree 12123 And This Is Like This But They Are Doing Her And Death And Were Going To Return Max But They Are Doing Her And Death And Were Going To Return Max Website So Let's Website So Let's Take A Look At The Same Example Tattoo Respect Take A Look At The Same Example Tattoo Respect Short Hair So Let's Get Started Now Short Hair So Let's Get Started Now Swift Arrangement They Are During Sir Swift Arrangement They Are During Sir Software Testing Software Testing Software Testing and Test How is Set Behavior Friend Mix and That Oil Test Cases for Passing Nature Can See You Are Getting All Correct Answers Including 511 511 506 and Doing During Correct Answers Shoulders and Submit Our in in Software Testing Hundred Percent Software Testing Hundred Percent Performance Hand Performance Hand Performance Hand memory of activities is very good and the time complexity of noise pollution is very attractive through the string all the character should be time complexity and decide who care for you to time complexity for this solution is more towards in For the solution is For the solution is For the solution is order of one died because they are not using order of one died because they are not using any candidate for data structure flight map any candidate for data structure flight map link glycerin that you are using link glycerin that you are using simple two variables too cute and sorry simple two variables too cute and sorry for the best complexities for the best complexities 5420 one problems later to you want to discuss 5420 one problems later to you want to discuss and the regional problem and the regional problem and the regional problem The Problem Let's Go Through The Description For Doing Good Example 100th Problem Is Loot Ko 2016 Kunwar String Contents All For Your Report Subscribe Knowledge - Settings And At Integral's Return Through Every Binary Code Of Length Quiz And Sub Screen Of S Otherwise Return Forms Type So let's take this example if hair oil can explain what is the problem in solar system insulated given to us and a pioneering spirit and have to find out if all the size two subscribe sure and size two minor this trick are there in this subscribe to Means How Will Find Its subscribe to Means How Will Find Its subscribe to Means How Will Find Its Size Two Minor Stringers He Size Two Minor Stringers He 108 Rasikan 108 Rasikan 2013 Dates 2013 Dates 104 3085 By Two Basically Force Wing 104 3085 By Two Basically Force Wing Are Basis For Total Fostering Are Basis For Total Fostering That Former Minor String To Have To Make Her That Former Minor String To Have To Make Her And All Of Distic President When And All Of Distic President When Skin Tear Se Present Skin Tear Se Present Skin Tear Se Present man good 20 201 vision on this project roman reigns shiromani also present clear day 120 is president clear if subscribe and one one is president senior vice president share so all these force wing are present in the given figure Where we are going to take to solve this problem is what we will do is Where we are going to take to solve this problem is what we will do is merge greater heights and right hand side of things and will take from beginning will go and will get a string of five to the right fennel example I will will maths science two Given String And So Will Go Given String And So Will Go Given String And So Will Go On And Hui I Pin Function Of On And Hui I Pin Function Of Being Also This Is Dynasty Day I Will Put Being Also This Is Dynasty Day I Will Put Into The Satanic Verses Will Put Into * Into The Satanic Verses Will Put Into * Left Left After Great I Will Take Another Sub Screen After Great I Will Take Another Sub Screen Of Science Twelfth Science's Basically West Of Science Twelfth Science's Basically West Indies And Mothers Indies And Mothers 110 110 110 Link Most 2012 That And Again Will Dhanush Cuttle Tour Interesting By Handing Proper 1010 Wicked Handing Proper 1010 Wicked Tree And The Shadow Of The Rise Of Which Tree And The Shadow Of The Rise Of Which State Is Equal To Three To Power To Right Character Power To Basically Lights And Rector Power Of Gift To Men Stud A True Power To Get A Gift To Give 124 Subah Surat That Is The Size Of Dresses For President Means The Best All The Tool Binary Code Or President Abs Hindi For This Is Not Going To Implement The That That That British tourist previous so ₹2 death in case of bakhari arrest to in s up to difficult tourist brajdham in combination with 1548 tourist husband jeth 100 likes basically a's For For For you will find in gift used to give free will find you will find in gift used to give free will find tourist through which get tourist through which get details for you will find to arrested for which aspect details for you will find to arrested for which aspect email light sweet crude email light sweet crude let's take a look at the implementation based and let's take a look at the implementation based and created history of string year result and the created history of string year result and the created created created Going To Straight Through This Distic Right The Number All Characters Interesting But We're Going To Add Into The Sellout's Length Spring Tide A Grand Duke 200 Life Into You Will Create To Land Unite All Shaadi Student Student Student Shaadi Student Student Student Shaadi Student Student Student Distic And They Will Keep Distic And They Will Keep Adding Friends * Set Taste You Can See You Year Adding Friends * Set Taste You Can See You Year Creating A Year When Using Spring Creating A Year When Using Spring Function And Were Passing Noida Plus's Doing Function And Were Passing Noida Plus's Doing Great Souls In Captivity Great Souls In Captivity That Ever Hero Plus To Student Available 2014 That Ever Hero Plus To Student Available 2014 Plus To Date Of Plus To Date Of Plus To Date Of Sites For The And We Are Going To Make Your Data Is Equal To Two Wheelers Maths Power Function Tourist's Right Tourist's Holiday Dinner For Example In This Is It Is Tourist To Ride Solar Geyser All The For 0080 0080 0080 Tight So Let's Go Ahead And The Late Say Reduce Example Force One Morning Shoot Proof Servi The Software Getting Through Right A Software Getting Through Right A I Today Late Chest Password Negative I Today Late Chest Password Negative Specified Changes One Should Be False Because Now Will Not Have To Specified Changes One Should Be False Because Now Will Not Have To Wander Springs Apps Wander Springs Apps Apps Apps Apps Who Hair Also It's True Only Because They Are Too That Sudheesh First First To Letters Paris That Sudheesh First First To Letters Paris Hair And Destroy You Follow Hair And Destroy You Follow 0 Getting Hair 10112 Yaar Getting Air Balloon 0 Getting Hair 10112 Yaar Getting Air Balloon Yaar Getting Air Tight And 102 Yaar Getting Yaar Getting Air Tight And 102 Yaar Getting Here Here Here Intermediate Man 108 Questions Distinct Of Witch This Too Andher Is Not Recorded 105 So Let's Sexual Tuesday To You Want To Test Ride Specific Less Which Is Points And Listen Tips For Decades No 1210 And Listen Tips For Decades No 1210 Stream So Lets and Solution is Working Stream So Lets and Solution is Working Fine So Lets 51 Sector-12 of Test Has Cleared All Fine So Lets 51 Sector-12 of Test Has Cleared All Ise Examples Hai Ki Hai To Aam Kadi Clear Examples True True True Clear Examples True True True for Ones for Ones Proven True False for Solar Coming Rate Proven True False for Solar Coming Rate Fixed Through Modi System Software and Will Fixed Through Modi System Software and Will Change its Form and Submit Dress Code 200 Good-Good Accepted by List Court 42% Only Performance and Fifty Seven Per Cent in the Memory Usage Which is Cent for This is the Way Can Solve or Check Per String Content of All the Records Size Night With The Help Of Scent And Night With The Help Of Scent And Night With The Help Of Scent And Vision User Substring Method So They Can Get All The Vision User Substring Method So They Can Get All The Sub Screenshots Size Of Basically Sub Screenshots Size Of Basically From The Given String Tie And They Will Put From The Given String Tie And They Will Put Into The Set And You Want To Make Website Is Into The Set And You Want To Make Website Is Equal To Tourist Tower Basic Latest Equal To Tourist Tower Basic Latest And Updated And Updated And Updated Problem Yes If You Have Told You Check My Channel Play List Play List Code And Solutions Fixed Nine Letters And Emphasize them Java Problems Of Interviews In Big Companies Like Amazon Apple Google Facebook Yahoo And Microsoft And So Many Rate Forehead With Problems Forehead With Problems Forehead With Problems App Consists Variety Of Problems Like App Consists Variety Of Problems Like Dynamic Programming Languages Dynamic Programming Languages Related Problems Related Interview Questions Related Problems Related Interview Questions Daily Graph Problems Binary Search Tree Daily Graph Problems Binary Search Tree Problems Finally Search Related Problems Finally Search Related Problems Logical Base Problems As Well Problems Logical Base Problems As Well S Lord Of Telephone Recruitment Last S Lord Of Telephone Recruitment Last Interview Questions Also Late So Please Interview Questions Also Late So Please Request Check The Playlist On Request Check The Playlist On Request Check The Playlist On like this video and if you find this video helpful please subscribe and liked your subscription is really important totke channel vikas that is the videos can go and reach to more people de can also watch these videos and get benefited wildest interview preparation for please The Channel thanks for The Channel thanks for The Channel thanks for watching this video | 2024-03-21 02:51:58 | 1,461 | Leetcode 1461 Check If a String Contains All Binary Codes of Size K & 1446 Consecutive Characters |
|
eMIlsGbt4no | hey everyone in this video let's take a look at question 208 Implement try only look at question 208 Implement try only code this is part of our blind 75 list code this is part of our blind 75 list of questions so let's begin of questions so let's begin in this question a try or a prefix tree in this question a try or a prefix tree is a tree data structure used to is a tree data structure used to efficiently store and retrieve keys in a efficiently store and retrieve keys in a data set of strings there are various data set of strings there are various applications of this data structure such applications of this data structure such as autocomplete and spell checker you as autocomplete and spell checker you want to implement the try class where want to implement the try class where try initializes the try object insert try initializes the try object insert will take in a word and insert it into will take in a word and insert it into our data structure then search we'll go our data structure then search we'll go ahead and return true if this word is ahead and return true if this word is part of our try part of our data part of our try part of our data structure and starts with well again structure and starts with well again taking a prefix and return true if there taking a prefix and return true if there is a previously inserted string word is a previously inserted string word that has the prefix prefix and false that has the prefix prefix and false otherwise so what does this mean otherwise so what does this mean essentially so let's take a look maybe essentially so let's take a look maybe we have the following words so let's say we have the following words so let's say we have the following words we have the we have the following words we have the word cats dog cat and then Dot word cats dog cat and then Dot try data structure might look something try data structure might look something like this and if you kind of think about like this and if you kind of think about it we can represent this in terms of a it we can represent this in terms of a tree and they actually want this to tree and they actually want this to because it's a tree data structure and because it's a tree data structure and so maybe this over here this is like one so maybe this over here this is like one node right maybe we can call this like a node right maybe we can call this like a try node or something and so what do we try node or something and so what do we notice well a try node has a value right notice well a try node has a value right you can see that all of these have you can see that all of these have values this value is a c this value is a values this value is a c this value is a d what else does it have well it has d what else does it have well it has like children right it has like what it like children right it has like what it points to it has like its left child it points to it has like its left child it has the right child but if you've got to has the right child but if you've got to think about it instead of just left and think about it instead of just left and right we can have a maximum like 26 right we can have a maximum like 26 children right because there's 26 children right because there's 26 alphabets 26 letters in the alphabet so alphabets 26 letters in the alphabet so for example for cats over here you can for example for cats over here you can see here we kind of have like a root see here we kind of have like a root which is like this node over here then which is like this node over here then we have C actually the root child which we have C actually the root child which is a c here A C node and that has a is a c here A C node and that has a child for a and then we go to a T and child for a and then we go to a T and then we go to an S you can see similarly then we go to an S you can see similarly we also have catch right cat is just we also have catch right cat is just this and then c a t we also have dog and this and then c a t we also have dog and Dot notice that for dog and Dot after Dot notice that for dog and Dot after the O over here we actually have two the O over here we actually have two children right we have one for the G children right we have one for the G and one for the T and so our insert and one for the T and so our insert function will essentially take in a word function will essentially take in a word and insert it into our data structure and insert it into our data structure here our search should somehow go here our search should somehow go through this tree and return true if we through this tree and return true if we have a word right so maybe let's say I have a word right so maybe let's say I search for the word cat then I should search for the word cat then I should actually return true here because cat is actually return true here because cat is part of the word and then starts with part of the word and then starts with it's basically just going to return true it's basically just going to return true if there is a string that we can form in if there is a string that we can form in the try such that it matches the prefix the try such that it matches the prefix so for example maybe I have just the so for example maybe I have just the prefix of D or maybe like d o you can prefix of D or maybe like d o you can see that we can form like a continuous see that we can form like a continuous string here and so we would return true string here and so we would return true in that case but for something like DOA in that case but for something like DOA well there's no a over here right well there's no a over here right there's no h out over here so we can't there's no h out over here so we can't really form that so we'll return false really form that so we'll return false there so there's many different ways to there so there's many different ways to do this right there's one way in which do this right there's one way in which like we actually create the individual like we actually create the individual nodes here so you would have like a nodes here so you would have like a actual class over here for the nodes and actual class over here for the nodes and then the class would have like maybe then the class would have like maybe something like um you know class like something like um you know class like node and then the class would have like node and then the class would have like a value and like a value and like um you know like array of children so um you know like array of children so this is one away but this is actually this is one away but this is actually not the way that I want to do this in not the way that I want to do this in Python it's actually it actually becomes Python it's actually it actually becomes very simple because if you think about very simple because if you think about it a node we can kind of represent this it a node we can kind of represent this in terms of a dictionary right so what in terms of a dictionary right so what do I kind of mean by that well let's say do I kind of mean by that well let's say over here like this initial root over over here like this initial root over here we can say root is just like an here we can say root is just like an empty dictionary something like this empty dictionary something like this right and let's say I want to insert the right and let's say I want to insert the word cat okay so what would I do well word cat okay so what would I do well this dictionary over here is going to this dictionary over here is going to essentially contain all of my children essentially contain all of my children if you think of it that way so right now if you think of it that way so right now I have no children so right now I just I have no children so right now I just have this one root here I have no have this one root here I have no children and then when I insert a c what children and then when I insert a c what am I going to have well when I insert a am I going to have well when I insert a c then I can have something like this I c then I can have something like this I can have that my dictionary becomes C can have that my dictionary becomes C and C in itself actually is its own and C in itself actually is its own dictionary so you can think of C in dictionary so you can think of C in itself is something like this so maybe itself is something like this so maybe there's other Keys over here but C in there's other Keys over here but C in itself itself is this entire thing here and so if you is this entire thing here and so if you think about a c think about a c C Child is This one over here the a over C Child is This one over here the a over here so really what this would kind of here so really what this would kind of look like is if I go ahead and remove look like is if I go ahead and remove this this it would kind of look something like it would kind of look something like this so we would have from the root we this so we would have from the root we would have a child C and then C would would have a child C and then C would also be a dictionary which has its own also be a dictionary which has its own children here we have a children of a children here we have a children of a and then a is its own dictionary which and then a is its own dictionary which has a child of T and then T is its own has a child of T and then T is its own dictionary which has a child of s and dictionary which has a child of s and then s actually doesn't have any then s actually doesn't have any children at all and so you can kind of children at all and so you can kind of think of it like this so we're doing the think of it like this so we're doing the same thing but we're just representing same thing but we're just representing it in terms of a dictionary we're not it in terms of a dictionary we're not creating new nodes over here and so you creating new nodes over here and so you can actually imagine here right so maybe can actually imagine here right so maybe instead of just the a you can see that instead of just the a you can see that the root here also has like a d right so the root here also has like a d right so here we would have like d also points to here we would have like d also points to its own child over here and then D its own child over here and then D points like a o points like a o which points to a g and a t Etc so which points to a g and a t Etc so hopefully you're understanding the the hopefully you're understanding the the point here that I'm trying to make but point here that I'm trying to make but essentially we can represent this in essentially we can represent this in terms of a dictionary instead of a node terms of a dictionary instead of a node and so doing that actually simplifies and so doing that actually simplifies our approach quite a bit and so there's our approach quite a bit and so there's just two more questions to answer right just two more questions to answer right how do I know whether I've whether I how do I know whether I've whether I have like a word like I can search for a have like a word like I can search for a word and how do I know that I start with word and how do I know that I start with the word well let's start with the the word well let's start with the starts with first right so if I ask you starts with first right so if I ask you like um you know do I have like maybe like um you know do I have like maybe starts with c a well or maybe all I starts with c a well or maybe all I really need to do is like I just need to really need to do is like I just need to go through the the string right and then go through the the string right and then I need to check okay does c exist Okay C I need to check okay does c exist Okay C does exist now I'm going to look for the does exist now I'm going to look for the a is there a inside the children of C a is there a inside the children of C yes there is so we can we can conclude yes there is so we can we can conclude that there this is a this is a valid that there this is a this is a valid like prefix if there isn't if it was like prefix if there isn't if it was something like C and then D for example something like C and then D for example um or in in this case like it wouldn't um or in in this case like it wouldn't work right actually I realized I put D work right actually I realized I put D over here over here um so D should not be here so actually um so D should not be here so actually if I wish to kind of draw this entire if I wish to kind of draw this entire thing again what it would kind of be thing again what it would kind of be like would C would point to a would like would C would point to a would point to T would point to S and all of point to T would point to S and all of these would have like their own children these would have like their own children like this but in addition to this in like this but in addition to this in addition to this we would also have like addition to this we would also have like d here and then D would point to O would d here and then D would point to O would point to G point to G and then also point to T and then also point to T Etc so that's like another way this is Etc so that's like another way this is the better way of representing it so the better way of representing it so basically if we're looking for something basically if we're looking for something like c a i can check if like C A is a like c a i can check if like C A is a string and in this case I can see that string and in this case I can see that it is it is so that answers that question the next so that answers that question the next question is and guess the final one is question is and guess the final one is like how do we realize the search right like how do we realize the search right like how do I know that a string exists like how do I know that a string exists inside of the search and I can't just inside of the search and I can't just follow the same approach here right follow the same approach here right because for example if you put like C A because for example if you put like C A well C A definitely exists but the well C A definitely exists but the string doesn't end here right the string string doesn't end here right the string actually goes to cat and actually cats actually goes to cat and actually cats and so the way we we want to do this is and so the way we we want to do this is like we want one way to like figure out like we want one way to like figure out that you know this is like the end of a that you know this is like the end of a word right and really if you maybe think word right and really if you maybe think of it in terms of a node maybe we can of it in terms of a node maybe we can have something like um end and then this have something like um end and then this would be like a Boolean right so this would be like a Boolean right so this would either be like true and false would either be like true and false indicating that at this node a string indicating that at this node a string has completed and so we can actually do has completed and so we can actually do the same thing over here essentially the same thing over here essentially what we could do is maybe every time a what we could do is maybe every time a string completes we can add like end as string completes we can add like end as true over here so end as true and so true over here so end as true and so what this would kind of look like if you what this would kind of look like if you think about it is if we had this entire think about it is if we had this entire thing here thing here so let's take a look if you have this so let's take a look if you have this entire thing here I'm going to skip over entire thing here I'm going to skip over the D just look at the C and then just the D just look at the C and then just look at the A and then just look at the look at the A and then just look at the T So T will have its own children and T So T will have its own children and then like you know there there can be then like you know there there can be more things over here but as part of the more things over here but as part of the children maybe we can have something children maybe we can have something like end and then we set it equal to like end and then we set it equal to true we know that the child will only be true we know that the child will only be like one letter at a time right so we're like one letter at a time right so we're completely allowed to add this but we completely allowed to add this but we can notice here that the cat over here can notice here that the cat over here if we have this scenario then this is a if we have this scenario then this is a true case like this is true case like this is um this is a case in which a word ends um this is a case in which a word ends so let's take a look at how we can do so let's take a look at how we can do this in the code to better understand this in the code to better understand and so it's actually completely very and so it's actually completely very simple on how we do this especially in simple on how we do this especially in Python so let's take a look so the first Python so let's take a look so the first thing we need is we need like our root thing we need is we need like our root right and I think I'll just call this right and I think I'll just call this children children so I'll call these children and it needs so I'll call these children and it needs to be a dictionary and I'm using self to be a dictionary and I'm using self because I need to refer to it everywhere because I need to refer to it everywhere so first thing I can do for insert let's so first thing I can do for insert let's start off with insert I can do c is start off with insert I can do c is equal to self.children and then when I'm equal to self.children and then when I'm inserting what do I need to do with my inserting what do I need to do with my word is something like bat for example word is something like bat for example then I need to go through each letter so then I need to go through each letter so for w in word then I need to essentially for w in word then I need to essentially create like the the nodes which in this create like the the nodes which in this case it's a dictionary right so I can case it's a dictionary right so I can actually check I can check that if W not actually check I can check that if W not in C then C at w is equal to an empty in C then C at w is equal to an empty dictionary so all this is doing is that dictionary so all this is doing is that if like initially when we have an empty if like initially when we have an empty empty dictionary this one we can see empty dictionary this one we can see that we don't have like a b here so that we don't have like a b here so we're going to create a child B and that we're going to create a child B and that will also have like its own children so will also have like its own children so what this is essentially doing is like what this is essentially doing is like from this node over here if you think from this node over here if you think about it from this node all it's doing about it from this node all it's doing is that it's creating like a b over here is that it's creating like a b over here for the bat that's what it's doing and for the bat that's what it's doing and then what I'm doing so if this is not then what I'm doing so if this is not the case then what do I want to do well the case then what do I want to do well now I want to move forward right now I now I want to move forward right now I want to consider the a over here but in want to consider the a over here but in order for me in order for me to consider order for me in order for me to consider the a I need to essentially move like my the a I need to essentially move like my C variable here into the the B's C variable here into the the B's children if you think about it right so children if you think about it right so I can do c is equal to C at w and so I can do c is equal to C at w and so what this will essentially do is c will what this will essentially do is c will initially start off over here so this is initially start off over here so this is like our pointer to the root and now my like our pointer to the root and now my root pointer will be over here and so I root pointer will be over here and so I can look inside of like these children can look inside of like these children to see if there's a A or whatever we can to see if there's a A or whatever we can see in this case there's not going to be see in this case there's not going to be anything so this will continue to Loop anything so this will continue to Loop and then at the very end at the very end and then at the very end at the very end what's going to happen at the very end what's going to happen at the very end we'll have our T and then C will be like we'll have our T and then C will be like T is child right so it would be T is child right so it would be something like this so have B and then something like this so have B and then we'll have an A over here we'll have an A over here and then we will have a t over here and then we will have a t over here and now c will be on like these children and now c will be on like these children which there are none right so c will be which there are none right so c will be like this empty dictionary here so what like this empty dictionary here so what I can do now is actually once it's I can do now is actually once it's complete I can do something like C at complete I can do something like C at end is equal to true so all I'm doing end is equal to true so all I'm doing here is I'm just saying that okay one of here is I'm just saying that okay one of the children let me have the value here the children let me have the value here set to end set to end and I'll just make it equal to true so that's all I'm doing over here okay so if you think of it in terms of that that's all we really need to do here and then search becomes very easy because all you need to do in search is again we'll go through the children and so we'll go through the word itself and then if we can actually check this right so if we can check actually if W naught in C then automatically we can return first right because we know we're missing a letter but if it is then we're going to keep going till the end right and then what I want to do is I want to return end in c because if you think about it maybe I enter the word like ca right well C A definitely exists but you can see there isn't an end over here there isn't to end the end only exists as cat and cats and so that's why we have this scenario here and then the start to it is actually even easier than that all we have to do is again we'll look at the children and then again we'll go through the prefix and so I can actually again just check if W not in C then I know that this prefix is not valid right so then I can return false and then otherwise I will just Advance my pointer again and then in the end I can just return true right because I know that I haven't returned false so far so in the end I'm going to be on any one of the children I might be on the C I might be on the a I might be on the T or the S but I know that this is a valid prefix so this is all there is to this question and so if we go ahead and run it we can see that it works this is the O of n type algorithm where the insert and the read and the all of the operations are o of N and so you can think of this as like a very easy approach to solve this question | 2024-03-22 10:04:26 | 208 | Implement Trie (Prefix Tree) - Leetcode 208 - Python |
|
C3XhnAAy4Wo | hello YouTube this is another Nikko problem for integer placement giving a problem for integer placement giving a positive integer positive integer positive integer positive integer starting from 1 to integer no max value starting from 1 to integer no max value you can the operation that follows if n you can the operation that follows if n is even replaced me in divided by 2 it is even replaced me in divided by 2 it is odd you can't replace n with either n is odd you can't replace n with either n plus 1 or M minus 1 so the max value of plus 1 or M minus 1 so the max value of integer is odd if we add 1 there were integer is odd if we add 1 there were both flow so we need to deal with that both flow so we need to deal with that what is the minimum number of our what is the minimum number of our placement and editor for and to become placement and editor for and to become one okay for this problem when you see one okay for this problem when you see this kind of structure either or either this kind of structure either or either these or either than you should think of these or either than you should think of TFS problem also you can use in dynamic TFS problem also you can use in dynamic programming either going to we just use programming either going to we just use DFS so here there is no kaneki need to DFS so here there is no kaneki need to tell me is because n is always positive tell me is because n is always positive so we just return the advice and here we so we just return the advice and here we run TSS so there is a logic if and run TSS so there is a logic if and encoding and we directly written the encoding and we directly written the euro good for one it's the result also euro good for one it's the result also while there's no replacements needed if while there's no replacements needed if equal to 2 in this case agree written equal to 2 in this case agree written well we just the 2 divided by 2 that is well we just the 2 divided by 2 that is 1 for others if in module 2 is 0 in this 1 for others if in module 2 is 0 in this case we return 1 plus the SS in divide case we return 1 plus the SS in divide that you else we need to do is else that you else we need to do is else easting easting else if n is odd number but if any else if n is odd number but if any in teacher taught max value in this case in teacher taught max value in this case we could written just and and we want we could written just and and we want the minimum number of replacements what the minimum number of replacements what do we need to do we could just either do we need to do we could just either give it a manual and plasma either give it a manual and plasma either really or and just in / - or it's just really or and just in / - or it's just an even number and no the maximum value an even number and no the maximum value and when we need to do it in one class and when we need to do it in one class math stopped me math stopped me yes last a minus 1 y SS n plus 1 since yes last a minus 1 y SS n plus 1 since that's it here this is the special that's it here this is the special Connell case we need to deal with Connell case we need to deal with because in his heart and in his a because in his heart and in his a maximum value of integer if we ever maximum value of integer if we ever there were just overflow so in that case there were just overflow so in that case we need to be there here you can just we need to be there here you can just input DFS m minus 1 or n plus 1 this is input DFS m minus 1 or n plus 1 this is a key and for the Loma odd number then a key and for the Loma odd number then we just my gfs in management EF at n we just my gfs in management EF at n plus 1 we just choose the minimal one so plus 1 we just choose the minimal one so yeah miss Ronco suits me okay guys that worked you can also use dynamic programming that's basically mostly the same process let me know if you have a better solution | 2024-03-24 12:16:16 | 397 | LeetCode - Integer Replacement |
|
NEDZft8ceQo | okay hi guys today we are going to solve a hi guys today we are going to solve a very interesting problem very interesting problem from lead code it's a medium problem and from lead code it's a medium problem and the problem statement is the problem statement is binary tree level order traversal so binary tree level order traversal so let me go through the statement and then let me go through the statement and then let's try to explain the problem to all let's try to explain the problem to all of you of you so the problem statement is given the so the problem statement is given the root of a binary tree root of a binary tree written the level order traversal of its written the level order traversal of its node value node value that is from left to right level by that is from left to right level by level level so as all we know what is the level of so as all we know what is the level of the traversal the traversal but those guys who don't know about but those guys who don't know about level order traversal level order traversal let me explain the level of draw let me explain the level of draw traversal is that traversal is that we have to traverse the tree from the we have to traverse the tree from the root root by level by level and each level we have by level by level and each level we have to to print or give the output from left to print or give the output from left to right or in this case right or in this case in level order 0 there is only one node in level order 0 there is only one node so we give so we give 3 then in level 2 there are two nodes 9 3 then in level 2 there are two nodes 9 and 20 so we move and 20 so we move left to right which is 1920 and again left to right which is 1920 and again from from level two there are two nodes level two there are two nodes 15 and 7 so we move from 15 and then 15 and 7 so we move from 15 and then seven seven so input is this and we have to give the so input is this and we have to give the output output in a matrix and each row in a matrix and each row will correspond to each level so in this will correspond to each level so in this case case the first row is 3 then second row is 9 the first row is 3 then second row is 9 20 20 third row is 15 7 okay so it's a very third row is 15 7 okay so it's a very standard problem a very good problem standard problem a very good problem so how to solve this problem so so how to solve this problem so as we know we can do level of traversal as we know we can do level of traversal on a on a tree using bfs what is bfs it is called tree using bfs what is bfs it is called breadth first search breadth first search so one way to solve this problem is that so one way to solve this problem is that we will start from we will start from root and we will use some data structure root and we will use some data structure which is cube and we will put this node which is cube and we will put this node into our queue into our queue and then explore its children so it's and then explore its children so it's children children 9 and 20 then we will put it 9 and 20 then we will put it into the queue 1920 and we pop three into the queue 1920 and we pop three and these in the order we and these in the order we push so this will work from left to push so this will work from left to right right and we will put and this is the second and we will put and this is the second first level right first level right because 3 is level 0 so we will put into because 3 is level 0 so we will put into our matrix in another row our matrix in another row and then we will check for children of and then we will check for children of 9 we will push and we will 9 we will push and we will pop 9 from the queue and pop 9 from the queue and and so forth and so on okay so let's try and so forth and so on okay so let's try to to also we have to keep track of the levels also we have to keep track of the levels right yeah yeah right yeah yeah so that's why i'm popping all the node so that's why i'm popping all the node and we have to and we have to uh keep trace of the level which we are uh keep trace of the level which we are traversing or which we are exploring traversing or which we are exploring okay okay so let's try to solve this problem so so let's try to solve this problem so let's say if let's say if the root is null right the root is null right if this is the case then we will return if this is the case then we will return nothing okay okay now we have to return a matrix this is the output you can say also this is the output you can say also we required a queue it is of type we required a queue it is of type tree node and let's call it nodes that we want to explore okay now nodes dot push will be the root so we are pushing our root into the queue and also we need another let's call it front also we need another let's call it front also we need another we have to track trace basically which we have to track trace basically which level we are level we are exploring so let's make a 1d exploring so let's make a 1d vector and this is called level vector and this is called level okay so what kind of variable and what okay so what kind of variable and what kind of data structure kind of data structure needed we define and now let's try to needed we define and now let's try to solve this problem solve this problem so we will like level i think uh why do so we will like level i think uh why do we need a vector we need a vector named level we need like for storing all named level we need like for storing all the the uh nodes in a particular level right uh nodes in a particular level right yeah yeah that's why yeah yeah that's why okay so we will try to pop okay so we will try to pop until the queue is empty right until the queue is empty right while exploring so we will say while exploring so we will say node dot empty now we will first try to what is the size of that node right okay now what is the typo size equals to the line 28 int size equals two nodes dot size in the line 28 28 yeah sorry yeah which is the size of the we have to while we are pushing we have to while we are pushing all the uh node we have to explore all the uh node we have to explore from backward right so let's say if i from backward right so let's say if i push push let's say if i push 9920 so let's say if i push 9920 so on the top of the queue this will be 20 on the top of the queue this will be 20 but first while exploring the children but first while exploring the children of of this level we have to explore nine so we this level we have to explore nine so we have to reverse because uh in case of uh have to reverse because uh in case of uh in case of a queue we do first come in case of a queue we do first come first serve right yeah so we will pick first serve right yeah so we will pick that item the nine first why are you doing this reverse uh why are you doing this reverse uh because because in this case let's say i push the in this case let's say i push the children children 1920 right so what is on our top 20 1920 right so what is on our top 20 but when we are doing the bfs on the but when we are doing the bfs on the next level we have to explore the next level we have to explore the children of nine children of nine but it is on bottom right so we have to but it is on bottom right so we have to reverse that reverse that okay like uh you cannot pop okay like uh you cannot pop from the front in c plus plus from the front in c plus plus no no no uh so when i like no no no uh so when i like uh suppose if i do it on java then i can uh suppose if i do it on java then i can like uh use the q like uh use the q data structure and i can pull the data structure and i can pull the elements from the elements from the front actually we are going to use front actually we are going to use it so that's also same for c it so that's also same for c for what i am saying that so while for what i am saying that so while exploring the children of theory exploring the children of theory right so which nine in twenty so first right so which nine in twenty so first we push we push nine and then twenty so on the top yes nine and then twenty so on the top yes which node is there it is twenty right which node is there it is twenty right and we stopped three in the beginning so and we stopped three in the beginning so now we have to now we have to explore the children of this level nodes explore the children of this level nodes so what are the nodes in this level it so what are the nodes in this level it is nine and twenty is nine and twenty so what we have to do from left to right so what we have to do from left to right right so on the top is twenty so right so on the top is twenty so but we have to do to start from nine so but we have to do to start from nine so we cannot access we cannot access nine directly right so that's why i have nine directly right so that's why i have to to reverse the queue reverse the queue and that's the reason i mean yeah that's and that's the reason i mean yeah that's uh that's what i was saying uh that's what i was saying like in java we can just uh take the like in java we can just uh take the element nine element nine from the front okay okay okay i got your point okay so we here we pop the root right push back the value of its children into the vector right these are children in the left these are children in the left then we will also push into the queue and if there is a node in the right of the tree then we will also push into the queue so because we have to explore these nodes so i think this is done also yeah we have to put the levels in our output yes so this is all the notes in the given so this is all the notes in the given level and i'm just pushing level and i'm just pushing into my vector of vector which is the into my vector of vector which is the matrix right and also i have to remove matrix right and also i have to remove all the all the elements in the in that level now elements in the in that level now because i have to explore the another because i have to explore the another level and level and this will do all the job so what let me this will do all the job so what let me go go uh do it through the code uh do it through the code so it will first push three so it will first push three then q is not empty then this will then q is not empty then this will define define all these things it will reverse then it all these things it will reverse then it will push its will push its children here into the queue and are children here into the queue and are in also into the level right because i in also into the level right because i have to have to okay so yes this will push okay so yes this will push 9 and 20 into the level and also 9 and 20 into the level and also into the queue because i have to now into the queue because i have to now explore explore its children's level their children yes its children's level their children yes yes when it is done yes when it is done then i will push my level into the then i will push my level into the vector vector and then we will clear the level because and then we will clear the level because now there is no need to three because we now there is no need to three because we explore three explore three then this will do for nine and this will then this will do for nine and this will do for do for twenty so there's no children of nine so twenty so there's no children of nine so this will do nothing this will do nothing here because here we are checking right here because here we are checking right and for 28 this will do and that will and for 28 this will do and that will do the job well all the notes are do the job well all the notes are explored explored because there is the empty condition in because there is the empty condition in the the end i will simply end i will simply return my vector back to all the level return my vector back to all the level let's try to in the line 41 semicolon uh let me try let me explore the code because this time i want to [Music] | 2024-03-21 10:00:44 | 102 | LeetCode Problem 102. Binary Tree Level Order Traversal #codingLife |
|
e1irnRo4lgg | hey guys welcome back to the channel so this channel every data science is all this channel every data science is all about trying to learn the different about trying to learn the different concepts involved in data science by concepts involved in data science by practicing a lot of questions in this practicing a lot of questions in this video i am going to solve this question video i am going to solve this question on lead code regarding fixed names in on lead code regarding fixed names in the table and try to walk you through the table and try to walk you through how we can develop solutions to such how we can develop solutions to such problems the difficulty level of this problems the difficulty level of this question is easy okay so let's jump question is easy okay so let's jump right in we are given a table called right in we are given a table called users with two different columns user id users with two different columns user id and name and these being their data and name and these being their data types user id is the primary key for types user id is the primary key for this table this table contains the id this table this table contains the id and the name of the user the name and the name of the user the name consists of only lowercase and uppercase consists of only lowercase and uppercase characters characters we are asked to write a sql query to fix we are asked to write a sql query to fix the name so that only the first the name so that only the first character is uppercase and the rest are character is uppercase and the rest are lowercase lowercase the order of the results should be the order of the results should be sorted by user id in ascending order sorted by user id in ascending order okay let's go to this example right so okay let's go to this example right so for example here we have two different for example here we have two different users alice and bob and this is the way users alice and bob and this is the way their names are written right their names are written right what we need to do is we need to what we need to do is we need to capitalize the first letter and rest capitalize the first letter and rest everything is small so a should be everything is small so a should be capital and l i c e should be small capital and l i c e should be small right same for bob and that is going to right same for bob and that is going to be the output be the output now you might think that there might be now you might think that there might be a inbuilt function in mysql which can do a inbuilt function in mysql which can do that but unfortunately there isn't so we that but unfortunately there isn't so we know there is a function called upper know there is a function called upper which capitalizes every letter of the which capitalizes every letter of the string or there is a function called string or there is a function called lower which converts every letter of the lower which converts every letter of the column to lowercase but to convert the column to lowercase but to convert the first letter to uppercase and rest to first letter to uppercase and rest to lowercase we don't have anything that lowercase we don't have anything that comes ready-made in mysql comes ready-made in mysql but if you know python there is a but if you know python there is a function called capitalize in python function called capitalize in python which does the exact same thing so there which does the exact same thing so there is an inbuilt function in python but not is an inbuilt function in python but not in mysql so how do we do it in mysql so how do we do it so so the logic here would be the logic here would be we can for each of these strings in the we can for each of these strings in the name column right we can break the names name column right we can break the names into two parts the first letter and into two parts the first letter and remaining everything else we can remaining everything else we can capitalize the first letter capitalize the first letter then then convert the remaining letters into convert the remaining letters into lowercase and then we can add them or lowercase and then we can add them or concat them right so let's employ the concat them right so let's employ the strategy so strategy so from this table from this table called called users users what we are going to do is since we need what we are going to do is since we need to return to our your two columns user to return to our your two columns user id and name so let's return id and name so let's return user id user id and we need to and we need to make the name in such a way that you make the name in such a way that you know it satisfies what question is know it satisfies what question is asking us so asking us so what we do is the first thing we need what we do is the first thing we need the first the first letter right so first letter from the letter right so first letter from the name column so we use the function name column so we use the function called substring called substring so sub so sub string string from what is the source so substrings from what is the source so substrings syntax is the source syntax is the source where you you know want the take you where you you know want the take you want to take the substring from then want to take the substring from then comma the starting position and then comma the starting position and then comma the length from that starting comma the length from that starting position right so your source is the position right so your source is the name column right so we write name name column right so we write name then the starting position is one so then the starting position is one so remember this is one not zero right this remember this is one not zero right this is index one is index one so index one and what is the length one so index one and what is the length one right so because start from there and right so because start from there and only keep uh only keep uh one position from that right one position from that right so so one one so this is going to give us the first so this is going to give us the first letter of every name right and what do letter of every name right and what do we need to do we need to capitalize this we need to do we need to capitalize this so we write upper so we write upper and and this right so this will capitalize the this right so this will capitalize the first letter first letter then what we need to do is for then what we need to do is for everything else right so that is start everything else right so that is start from index 2 and then go to till the end from index 2 and then go to till the end so so comma comma sub sub string string again same name column but start from again same name column but start from two and go till all the way to the end two and go till all the way to the end right so all the way to the right end is right so all the way to the right end is either you leave this blank or another either you leave this blank or another way or more logical way of thinking is way or more logical way of thinking is that that the entire length of this so if you see the entire length of this so if you see this is one two three four and five this is one two three four and five right so start from two and go to right so start from two and go to five so if you take what is the length five so if you take what is the length of this of this name column for alice 5 and you subtract name column for alice 5 and you subtract 1 so you reach 4 right so start from 2 1 so you reach 4 right so start from 2 and then 1 2 3 4 and then 1 2 3 4 right so you can write length of the name column and then subtract 1. so this is going to reach till the end right so now once you have that what do we need to do for all these after the first index should be in lower case so we write lower and then all this comes in parenthesis and now we have the upper part as well as the lower part so what we will do we will just use the concat function so concat this entire thing right and the alias should be name so we write as name and since this needs to be ordered by user id in ascending order we write order by user id okay so this looks good let me go ahead and run this okay so this is accepted our output is same as expected output let me go ahead and submit it to see if it passes all the test cases so this passes all the test cases and this is how we do it again very easy question the only thing that you need to know is there is no inbuilt function in mysql which can do this so you have to use the inbuilt functions upper and lower in a way that you are able to you know capitalize the first letter and everything else should be in lower case and what you can do is you can split that into two parts capitalize the first part make the second part lower case and then concat them so i hope this video was useful let me know if you know any other solution or a more efficient solution to do this and until then i will see you guys in | 2024-03-20 10:31:40 | 1,667 | LeetCode 1667 Interview SQL Question with Detailed Explanation | Practice SQL |
|
3kU7VYcmffU | hello guys welcome to algorithms made easy my name is richard and today we easy my name is richard and today we will be discussing the question maximum will be discussing the question maximum profit in job scheduling in this profit in job scheduling in this question we have n jobs where every job question we have n jobs where every job is scheduled to be done from start time is scheduled to be done from start time to end time obtaining a profit to end time obtaining a profit now we are given the start and the end now we are given the start and the end time and the profit in the arrays and we time and the profit in the arrays and we need to return the maximum profit that need to return the maximum profit that we can make such that no two job in the we can make such that no two job in the subset will overlap the time range now subset will overlap the time range now there is a condition given to us that if there is a condition given to us that if we choose a job that ends at time x we we choose a job that ends at time x we can start the another job that start at can start the another job that start at time time so in the first example we can see that so in the first example we can see that the first job ends at the first job ends at time three so we can start off the time three so we can start off the fourth job right at that point of time fourth job right at that point of time and so we are getting the maximum profit and so we are getting the maximum profit which is 120 and similarly in the rest which is 120 and similarly in the rest of the examples of the examples so now let's see what the question is so now let's see what the question is all about and what are the ways that we all about and what are the ways that we can use in order to solve this can use in order to solve this particular problem now this is the start particular problem now this is the start and and the profit arrays given to us in and and the profit arrays given to us in the first example the first example and this is how the diagrammatically it and this is how the diagrammatically it will look like will look like and as we know that the answer to this and as we know that the answer to this problem is we use these two particular problem is we use these two particular jobs and we see that jobs and we see that these two jobs do not overlap when the these two jobs do not overlap when the first job ends at three the next job first job ends at three the next job starts at three starts at three the total profit in this case becomes the total profit in this case becomes 120 which is 50 plus 70. doing it 120 which is 50 plus 70. doing it manually is not a difficult task now we manually is not a difficult task now we need to come up with an approach where need to come up with an approach where we can solve this programmatically we can solve this programmatically so so let's see that we have two times given let's see that we have two times given to us to us in this particular problem that is the in this particular problem that is the start time and the end time start time and the end time and we can use either of the two in and we can use either of the two in order to find out what will be the order to find out what will be the result so let's first discuss how we can result so let's first discuss how we can solve this using the start time so solve this using the start time so suppose we have one job with us suppose we have one job with us and then we have another job now these and then we have another job now these two jobs do not overlap and we can use two jobs do not overlap and we can use both of these jobs in order to find out both of these jobs in order to find out what will be the maximum profit so what will be the maximum profit so let's focus our attention only on the let's focus our attention only on the first job right now we can have two first job right now we can have two scenarios for any of the job present to scenarios for any of the job present to us it can either be selected or it can us it can either be selected or it can either be rejected either be rejected if the particular job is selected that if the particular job is selected that means this job with the profit 50 is means this job with the profit 50 is selected in that case the profit would selected in that case the profit would become 50 plus the profit after or become 50 plus the profit after or equals to the end time which is 3 in equals to the end time which is 3 in this case the rest of the profit this case the rest of the profit after this end equals to 3 plus the after this end equals to 3 plus the current profit 50 would become the current profit 50 would become the profit that we can get if we start at profit that we can get if we start at one and similarly if we do not select one and similarly if we do not select this particular job this particular job then the profit then the profit at this particular job would be equal to at this particular job would be equal to profit after one that means profit after one that means at least starting with time equals to 2 at least starting with time equals to 2 and that way we can find out the profit and that way we can find out the profit we will find out the maximum of all we will find out the maximum of all these profits for all the jobs and then these profits for all the jobs and then we can return the maximum amount of we can return the maximum amount of these these so if we write that down into so if we write that down into a set of instructions a set of instructions we first sort the jobs with the start we first sort the jobs with the start time because as we will be going time because as we will be going sequentially from every job to the other sequentially from every job to the other job job we would need the start time smallest to we would need the start time smallest to be processed earlier than the start time be processed earlier than the start time which is at the end of the job which is at the end of the job scheduling scheduling now for every job there are two now for every job there are two scenarios either it is selected or it is scenarios either it is selected or it is rejected if it is selected the profit rejected if it is selected the profit becomes profit of i plus next job after becomes profit of i plus next job after the end else the profit becomes next job the end else the profit becomes next job after start plus one now the max of the after start plus one now the max of the two profits will become the profit two profits will become the profit starting with this particular job we can starting with this particular job we can store that somewhere we will talk about store that somewhere we will talk about how we can store it and everything and how we can store it and everything and the third point is we find out the max the third point is we find out the max of all the these jobs and return what of all the these jobs and return what will the maxim that we are getting so will the maxim that we are getting so now let's now let's turn our attention to how we can solve turn our attention to how we can solve this using end time this using end time so in the case of end time we again have so in the case of end time we again have two jobs two jobs let's suppose that we have already let's suppose that we have already computed the result for the first job computed the result for the first job and now we are on the second job this is and now we are on the second job this is just to make things easier just to make things easier and the second job in this case is and the second job in this case is either selected or not selected similar either selected or not selected similar to what we did in the start time to what we did in the start time so if the job is selected then the so if the job is selected then the profit becomes 40 plus the profit before profit becomes 40 plus the profit before or equals to 5 and if this job is not or equals to 5 and if this job is not selected then the profit becomes profit selected then the profit becomes profit before 10 before 10 because we are not selecting this job because we are not selecting this job and any job ending at and any job ending at 9 can be used to compute the profit and 9 can be used to compute the profit and if we write down into if we write down into the statements it will still be the same the statements it will still be the same things just change a little bit in the things just change a little bit in the case of a selected and not selected in case of a selected and not selected in this particular video we would be this particular video we would be looking at how we can solve this using looking at how we can solve this using end time you can always apply the same end time you can always apply the same solution for the start time as well so solution for the start time as well so let's start with the end time and this let's start with the end time and this is the input that we had at the start is the input that we had at the start now in this case the start and the end now in this case the start and the end time both are sorted so we can call it time both are sorted so we can call it as an special input but that won't be as an special input but that won't be the case for other input there may be the case for other input there may be jumbled now that the end time is sorted jumbled now that the end time is sorted we'll start off with the first we'll start off with the first job that we had with the start is one job that we had with the start is one end is three and the profit is 50. end is three and the profit is 50. now we are seeing that at time three now we are seeing that at time three what is the maximum profit that we can what is the maximum profit that we can get get so at time 3 if we select this so at time 3 if we select this particular job the maximum profit that particular job the maximum profit that we can get is 50 plus all the jobs we can get is 50 plus all the jobs ending at n equals to 0 or ending at n equals to 0 or any job that is ending with n equals to any job that is ending with n equals to 2 and we take the max of the two values 2 and we take the max of the two values so we see that we do need so we see that we do need one value wherein we store that what is one value wherein we store that what is the maximum profit up till that the maximum profit up till that particular particular time time we will be storing the highest values in we will be storing the highest values in this map this map so at the end time 0 the profit will be so at the end time 0 the profit will be 0 and in this case 0 and in this case we find out that the profit 50 plus 0 we find out that the profit 50 plus 0 becomes 50 becomes 50 and so at the end time 3 the maximum and so at the end time 3 the maximum value or the maximum profit that we can value or the maximum profit that we can get get is 50 and we'll store that into this is 50 and we'll store that into this map that we have created now let's move map that we have created now let's move to the second job in the second job we to the second job in the second job we have the start is to end is 4 and the have the start is to end is 4 and the profit is 10 so profit is 10 so we again search for we again search for the job the job which has a maximum profit which ends at which has a maximum profit which ends at at most one so at most one so at most one up till that we have n time at most one up till that we have n time is zero and the profit is zero so zero is zero and the profit is zero so zero plus ten the max profit till four plus ten the max profit till four becomes ten becomes ten because we cannot use the job one in because we cannot use the job one in this case as these two are overlapping this case as these two are overlapping because the first job is not ending because the first job is not ending before 2. once we have that value that before 2. once we have that value that the profit is maximum equals to 10 at the profit is maximum equals to 10 at the time 4 the time 4 we see that can we put that value into we see that can we put that value into the map we cannot put this value into the map we cannot put this value into the map because there is a higher value the map because there is a higher value residing in the map right now so the end residing in the map right now so the end time is 3 and the time is 3 and the profit is 50 that will be the maximum profit is 50 that will be the maximum value now let's move to the third job in value now let's move to the third job in this case the start is 3 and is 5 and this case the start is 3 and is 5 and the profit is 40 we try to find out any the profit is 40 we try to find out any job job that ends at 3 and we find out that the that ends at 3 and we find out that the job exists which is 50 so we the maximum job exists which is 50 so we the maximum profit becomes in this case 50 plus 40 profit becomes in this case 50 plus 40 which is 90. so we do add that value which is 90. so we do add that value into the map which is 5 comma 90. into the map which is 5 comma 90. similarly we move to the last job and similarly we move to the last job and here we check any job that is ending at here we check any job that is ending at 3 we find out there is a job that ends 3 we find out there is a job that ends at 3 which is 50 the maximum profit in at 3 which is 50 the maximum profit in this case become 120 which is higher this case become 120 which is higher than the last value present in this map than the last value present in this map or the highest value present in the map or the highest value present in the map so we put this value 6 comma 120 and so we put this value 6 comma 120 and this value this value 6 comma 120 6 comma 120 being the highest value in the map is being the highest value in the map is the value that is the highest profit the value that is the highest profit that we can make from this particular that we can make from this particular set of inputs when we apply this logic set of inputs when we apply this logic we will be able to figure out the result we will be able to figure out the result it will be much more clear when we code it will be much more clear when we code this particular approach so now it's this particular approach so now it's time to code this time to code this so we'll first start off with creating so we'll first start off with creating the data the data out of the start time and time and out of the start time and time and profit so that we do have all the data profit so that we do have all the data in one space in one space so so the simplest method to use that data is the simplest method to use that data is to create a 2d array so there will be n elements where n will be start time dot length once we have that we can put all the data into this jobs now that our data is complete we had two now that our data is complete we had two approaches we can either go with the approaches we can either go with the start time or the end time now in this start time or the end time now in this case we will go with the end time so we case we will go with the end time so we need to sort this array based on end need to sort this array based on end time so we'll use the inbuilt arrays dot time so we'll use the inbuilt arrays dot sort for that sorting this jobs array we sort for that sorting this jobs array we will be using a custom comparator and will be using a custom comparator and the second value of this array is the the second value of this array is the end time end time so we will sort according to that so we will sort according to that ascending order once the array is sorted ascending order once the array is sorted we need to find out for every job if it we need to find out for every job if it is selected is selected what is the maximum profit what is the maximum profit if it is not selected then what is the if it is not selected then what is the maximum profit so we need to store those maximum profit so we need to store those values into somewhere so that we can use values into somewhere so that we can use the previous value like we saw that we the previous value like we saw that we used a map and in this question we would used a map and in this question we would need a map need a map wherein we can find out the value which wherein we can find out the value which is less or equals to is less or equals to the particular the particular start time start time so which map provides that functionality so which map provides that functionality so tree map does gives us that so tree map does gives us that functionality wherein we can find out functionality wherein we can find out the keys which are less than the the keys which are less than the particular key provided because particular key provided because 3 map as we all know 3 map as we all know has all its keys in sorted order has all its keys in sorted order searching any value in a key map takes searching any value in a key map takes log and time as it uses binary search log and time as it uses binary search internally so we would have a tree map internally so we would have a tree map and we know that and we know that at the n times zero the maximum profit at the n times zero the maximum profit that we can get is zero so that is the that we can get is zero so that is the base base value that we need to put in this map value that we need to put in this map which is zero comma zero which is zero comma zero now now for every job that we have we need to for every job that we have we need to perform some functionality now herein we perform some functionality now herein we need to find out a value or the profit need to find out a value or the profit that we get now this value is if this that we get now this value is if this particular job is selected then what particular job is selected then what will be the profit so the profit in this will be the profit so the profit in this case would be as we all know the profit case would be as we all know the profit of this particular job and the of this particular job and the maximum profit that we can get before maximum profit that we can get before the start of this particular job so we the start of this particular job so we need to find out what is that value need to find out what is that value so we need to find out the key if so we need to find out the key if existing existing in this particular dp map so we need to in this particular dp map so we need to find out the highest value that is lower find out the highest value that is lower or equals to the given provided start or equals to the given provided start time so to find out that value we have a time so to find out that value we have a method for that which is called floor method for that which is called floor entry so we will use that entry so we will use that we provide the start time over here and we provide the start time over here and we then get its value which is get value we then get its value which is get value now as you know we need to put this val now as you know we need to put this val into our map only if into our map only if it is a value greater than the existing it is a value greater than the existing value we have already sorted all the end value we have already sorted all the end times and now we are going in the times and now we are going in the sequential order so every key that we sequential order so every key that we put into the map will be put in at the put into the map will be put in at the end of the map end of the map so if this current value is greater than so if this current value is greater than that and value we need to put this new that and value we need to put this new job end time with the profit into the job end time with the profit into the map so map so we do a check over here if the well is we do a check over here if the well is greater than greater than the dp dot last entry would get value the dp dot last entry would get value now these are some of the methods that now these are some of the methods that the the tree map provides us by itself you can tree map provides us by itself you can look them up and try to use them in your look them up and try to use them in your code it will really help you in speeding code it will really help you in speeding up your development once we have that we up your development once we have that we can put this value into the map at can put this value into the map at the end time the end time so so the job end the job end and we put in and we put in the val into this the val into this particular position particular position we saw that the last value is nothing we saw that the last value is nothing but the highest value that we can get but the highest value that we can get so this is the value so we can directly so this is the value so we can directly return dp.entry last entry dot get value return dp.entry last entry dot get value and that will do the work for us so the and that will do the work for us so the coding part is done as we are using a coding part is done as we are using a tree map we need not to take care of all tree map we need not to take care of all the searching and everything the tree the searching and everything the tree map does provide that in built we are map does provide that in built we are doing a sorting over here so that is n doing a sorting over here so that is n login login and then we are using for n elements and then we are using for n elements finding out the value is log n so that finding out the value is log n so that again becomes n log n so now let's try again becomes n log n so now let's try to run this code for all the sample test to run this code for all the sample test cases now let's run this so it runs successfully for all the sample test cases let's submit this so it got submitted successfully the time complexity in this case is n log n that we discussed well the space complexity is in because we're using a jobs array for that you can also solve this problem using start time the approach will remain pretty much the same do let us know your thoughts in the comments below thanks for watching this [Music] | 2024-03-19 12:00:51 | 1,235 | Maximum Profit in Job Scheduling | Live Coding with Explanation | Leetcode - 1235 |
|
8fT6Vzn_lFU | [Music] hey guys welcome back to another video hey guys welcome back to another video and today we're going to be solving the and today we're going to be solving the leakout question leakout question excel sheet column numbers so in this excel sheet column numbers so in this question we're given a column title as question we're given a column title as appeared in an excel sheet we respond appeared in an excel sheet we respond its corresponding column number its corresponding column number so what does this mean so let's say so what does this mean so let's say we're given the letter we're given the letter a and a corresponds to one and let's say a and a corresponds to one and let's say we're given the letter z we're given the letter z or z depending from where you're from uh or z depending from where you're from uh we have we have uh the it corresponds to the number 26 uh the it corresponds to the number 26 and now let's say we have a a right and now let's say we have a a right a a is going to correspond to 26 plus a a is going to correspond to 26 plus one one so then in this case we're going to have so then in this case we're going to have 27 27 and this is going to keep going until a and this is going to keep going until a b a b b a b a b a c a d all the way up to a z a b a c a d all the way up to a z and when we have a z we have a value of and when we have a z we have a value of 26 multiplied by 2 which is 52 26 multiplied by 2 which is 52 okay and then this is going to keep okay and then this is going to keep going so going so we could also have three uh digits sorry we could also have three uh digits sorry three letters three letters so we could have a a and a so we could have a a and a which is going to start off with the which is going to start off with the value of 53 value of 53 and it's gonna keep going on right and and it's gonna keep going on right and so this is what we have to do so this is what we have to do and if you look at this we kind of have and if you look at this we kind of have a pattern so a pattern so when we have just one letter right when when we have just one letter right when we have one space we have one space we have 26 possibilities we have 26 possibilities that can go into that one space so now that can go into that one space so now let's say we have two spaces right let's say we have two spaces right we so we have a space for two letters so we so we have a space for two letters so in this case in this case we have 26 possibilities to go over here we have 26 possibilities to go over here and we also have 26 possibilities to go and we also have 26 possibilities to go over here over here and to calculate what that is it's just and to calculate what that is it's just going to be 26 multiplied by 26 which is going to be 26 multiplied by 26 which is nothing but 26 squared nothing but 26 squared similarly just so you understand similarly just so you understand completely if we have completely if we have three uh letters then each of the letter three uh letters then each of the letter has a probability has 26 different has a probability has 26 different options that could go inside of that options that could go inside of that so another way to say that is the base so another way to say that is the base for this is 26 and we can use that for this is 26 and we can use that knowledge in order to calculate the knowledge in order to calculate the column number column number so let's just take a quick look at how so let's just take a quick look at how that looks like okay so let's start off that looks like okay so let's start off with with uh the letter a right pretty simple uh the letter a right pretty simple and when we go to the first place so how and when we go to the first place so how are we going to calculate this are we going to calculate this so we have a multiplied by whatever the so we have a multiplied by whatever the base is so in this case the base is 26 base is so in this case the base is 26 since there are 26 different since there are 26 different possibilities and since it's possibilities and since it's only one letter right so for the when only one letter right so for the when we're at the first we're at the first unit or letter we're going to go do 26 unit or letter we're going to go do 26 to the power of zero to the power of zero and what is the value of a going to be and what is the value of a going to be here a is the first letter so it's gonna here a is the first letter so it's gonna have a value of one have a value of one so we're gonna do one multiplied by 26 so we're gonna do one multiplied by 26 to the power of zero to the power of zero which equals to 1 and if you look over which equals to 1 and if you look over here that's our answer here that's our answer okay so now if we go to b it's going to okay so now if we go to b it's going to be the same thing be the same thing but instead of a value of a1 so let's but instead of a value of a1 so let's say this was b say this was b over here and so value of 1 this would over here and so value of 1 this would have a value of 2 have a value of 2 right so all right so let's now take a right so all right so let's now take a look at a look at a two letter excel uh column number a two letter excel uh column number a and b okay and so that's pretty simple and b okay and so that's pretty simple and we're going to start off with the and we're going to start off with the first letter so that's going to be b first letter so that's going to be b multiplied by 26 to the power of zero multiplied by 26 to the power of zero now we're going to go to the next letter now we're going to go to the next letter which is a and we can which is a and we can add that so a multiplied by 26 add that so a multiplied by 26 now we're gonna increase the power by now we're gonna increase the power by one so 26 to the power of one one so 26 to the power of one so in this case b is going to be nothing so in this case b is going to be nothing else but 2 else but 2 so 2 multiplied by 1 is 1 and plus so 2 multiplied by 1 is 1 and plus 1 multiplied by 26 is 26 and this equals 1 multiplied by 26 is 26 and this equals to 27. to 27. so i'm pretty sure you get it but let's so i'm pretty sure you get it but let's just do one final example just do one final example so let's say we have b z so let's say we have b z and c in this case it's going to be c and c in this case it's going to be c multiplied by 26 to the power of zero multiplied by 26 to the power of zero plus z multiplied by 26 to the power of plus z multiplied by 26 to the power of one one plus b multiplied by 26 to the power of plus b multiplied by 26 to the power of two and when you uh subtract when you two and when you uh subtract when you solve that you should get the answer solve that you should get the answer so i think it's pretty simple so now so i think it's pretty simple so now let's just look at how the code for this let's just look at how the code for this looks like looks like so before we get into a code i just want so before we get into a code i just want to show you a quick thing so to show you a quick thing so in order to write this we should in order to write this we should understand what the ord function does understand what the ord function does and all it does is you give it a letter and all it does is you give it a letter right in this case we're going to give right in this case we're going to give it a capital a and it's going to give it a capital a and it's going to give you the ascii value of that letter so in you the ascii value of that letter so in this case i'm pretty sure capital a this case i'm pretty sure capital a has an ascii value of 65 but has an ascii value of 65 but in our question we wanted uh so for in our question we wanted uh so for example for a we wanted one since it was example for a we wanted one since it was the first letter the first letter for b we wanted two and so on and so for b we wanted two and so on and so forth let's see how we can do that forth let's see how we can do that so let's say for example let's say we so let's say for example let's say we look at capital d look at capital d right so we have capital d here and has right so we have capital d here and has a value of 68. a value of 68. so what we're going to do over here is so what we're going to do over here is we're going to take whatever we're going to take whatever letter we want so let's say we want to letter we want so let's say we want to find the value of find the value of a capital d we're going to subtract that a capital d we're going to subtract that with a capital a so capital a since with a capital a so capital a since that's our first letter that's our first letter okay there we go so in this case we get okay there we go so in this case we get three but three but d is the fourth letter a b c and d so d is the fourth letter a b c and d so what we're going to do is we're going to what we're going to do is we're going to do that do that and we're going to add one to it so this and we're going to add one to it so this is what we're going to be using to find is what we're going to be using to find the value the value or the place of our letter and the fact or the place of our letter and the fact that all of our letters that all of our letters are capital and they're the same case uh are capital and they're the same case uh makes this a lot easier makes this a lot easier okay so now let's go to our lead code so okay so now let's go to our lead code so we're going to start off by initializing we're going to start off by initializing a variable called results and a variable called results and uh in the beginning it's just going to uh in the beginning it's just going to have a value of 0. have a value of 0. and this is what we're going to return and this is what we're going to return in the ending okay so now we're going to in the ending okay so now we're going to iterate through each of our characters iterate through each of our characters so for characters in s so for characters in s and first what we need to do is we need and first what we need to do is we need to find the ascii to find the ascii value for it so in order to do that value for it so in order to do that we're going to find do the same thing we're going to find do the same thing so when you first find the ascii value so when you first find the ascii value of of our character subtract that with the our character subtract that with the ascii value ascii value of capital a and then add one of capital a and then add one so we got our ascii value and let's just so we got our ascii value and let's just save it in the variable save it in the variable x and after we do that we're going to x and after we do that we're going to add add this to our results so our result is this to our results so our result is going to be results going to be results multiplied by 26 since 26 multiplied by 26 since 26 is our base and over here we're going to is our base and over here we're going to add add this variable over here so plus this variable over here so plus x okay and that should be it x okay and that should be it and we go outside of our for loop and and we go outside of our for loop and over here we return our result over here we return our result sorry return okay sorry return okay so let's submit our solution and as you can see our solution to get accepted and finally do let me know what you thought about the video and don't forget to like and subscribe | 2024-03-21 14:03:38 | 171 | Excel Sheet Column Number | Leet code 171 | Theory explained + Python code |
|
B9kF1YUgMOg | hello guys my name is Ursula and welcome back to my channel and today we are back to my channel and today we are going to solve a new lead code portion going to solve a new lead code portion that is Excel sheet column number so that is Excel sheet column number so question C is given a string column question C is given a string column title that represent the column title title that represent the column title sap as it appears in an Excel sheet sap as it appears in an Excel sheet written its corresponding volume number written its corresponding volume number so we have to written the column number so we have to written the column number its corresponding value here and we will its corresponding value here and we will be solving this question with the help be solving this question with the help of JavaScript so just before starting of JavaScript so just before starting solving this question guys subscribe to solving this question guys subscribe to the channel hit the like button press the channel hit the like button press the Bell icon button and bookmark the the Bell icon button and bookmark the playlist so that you can get the updates playlist so that you can get the updates from the channel so if you see here from the channel so if you see here column if column is equals to A we will column if column is equals to A we will return one so and if you do the coil return one so and if you do the coil number A B we will be returning 28 and z number A B we will be returning 28 and z y will return x701 so how we are going y will return x701 so how we are going to approach how we are getting such to approach how we are getting such values values so let me explain it to you with an so let me explain it to you with an example here if a example here if a we say we say a a 0 0 into 26 into 26 Plus C5 Plus okay okay so how we are getting one where zero so how we are getting one where zero that will also I will explain it to you that will also I will explain it to you then then B B is is this whole sum this whole sum this whole sum this whole sum multiplied by 26 multiplied by 26 plus 2 then how we are getting 2 that plus 2 then how we are getting 2 that will also explain it to you and now c will also explain it to you and now c will be will be if I take an example ABC later mentioned if I take an example ABC later mentioned oh we have a column number ABC oh we have a column number ABC and if we take an example we see and if we take an example we see so this whole so this whole some Builder was 28 and 28 into 26 some Builder was 28 and 28 into 26 plus 3. now we are getting three plus 3. now we are getting three let me also explain it to you so let us let me also explain it to you so let us understand so these are all asai values understand so these are all asai values so how we are approaching this the ACI so how we are approaching this the ACI values I will explain it to you so asei values I will explain it to you so asei numbers numbers ACI and if I go and scroll down here ACI and if I go and scroll down here here something images we can check and here something images we can check and explain it to you what they are explain it to you what they are um yeah so here I have got something here see see there it's starting for 60 from 64. so there it's starting for 60 from 64. so 64 understand it as a zero and 64 understand it as a zero and this is 65 a b c d so it's starting from this is 65 a b c d so it's starting from 65 to uh 65 to uh 90 so 60 from 90 we are getting all 90 so 60 from 90 we are getting all characters here for column number if we characters here for column number if we talk about so if you want the number talk about so if you want the number value how we will get we will minus 65 value how we will get we will minus 65 minus 64 will give us 1 60 if uh six minus 64 will give us 1 60 if uh six square minus 64 give us 267 minus 64 square minus 64 give us 267 minus 64 will give us three so if you want a will give us three so if you want a value of C we will subtract these two value of C we will subtract these two numbers numbers which two numbers we will subset 67 which two numbers we will subset 67 minus 64 will give us c 66 minus 64 give minus 64 will give us c 66 minus 64 give us B 65 minus 65 plus 65 minus 64 value us B 65 minus 65 plus 65 minus 64 value was a so this is how we are getting so was a so this is how we are getting so let's write instead of one let's write let's write instead of one let's write it it 65 65 minus 64. and instead of this 2 here instead write 66 minus 64. and here also instead of 3 let's write 67 minus 64. so that's make more sense and it's more logical to write these things here now let's start solving first of all I will create a variable let's function the sum is equals to 0 which is which is my integer and I will create a count here for let in which I will first of all I will putting a variable let I is equals to 0 and column column CEO and column dot length I plus plus now I will say that sum is equals to means this whole thing is equal to where is it's our initial value we have to return this also so let's return this also return some what in the loop Y what we will be doing here is we will just writing this whole thing into a formula so since this is starting from 0 as well so instead of uh 0 we can write some into because this is all wholesome so in 26 and and we will say column title Dot we will say column title Dot care code it at care code it at will give us what will give us the ACI will give us what will give us the ACI value of that particular value of that particular number number so so so for that and minus 64. so this will so for that and minus 64. so this will give us ACI value of any particular ith give us ACI value of any particular ith character like a it will give one 65 character like a it will give one 65 it will give us 65 which will give us 1 it will give us 65 which will give us 1 at the end ultimately so let's band it at the end ultimately so let's band it and check for an answer so we have got our answer here this was all in the question guys hope you have understood this question and if you have any doubt ask in the comment section and we have done this with the help JavaScript thank you guys for watching | 2024-03-21 14:04:08 | 171 | 171. Excel Sheet Column Number with JavaScript | Leetcode with JavaScript #youtube #javascript |
|
P5K_F_vHeJg | in this video I want to really explain the sliding window algorithm so let's the sliding window algorithm so let's take a look we're given a string s and take a look we're given a string s and we want to find the length of the we want to find the length of the longest substring without any repeating longest substring without any repeating characters so let's set both L and R to characters so let's set both L and R to be the beginning marking that our window be the beginning marking that our window is just the a to easily keep track of is just the a to easily keep track of the characters we have in the window we the characters we have in the window we will use a hash set for now just the will use a hash set for now just the letter of a so our window is valid so we letter of a so our window is valid so we want to move it forward which means want to move it forward which means moving R to the right so now is this in moving R to the right so now is this in our set well it's not in our set so we our set well it's not in our set so we can add it but it gets interesting here can add it but it gets interesting here as we try to move R forward and add this as we try to move R forward and add this to the window this current character is to the window this current character is in our set so we need to move L forward in our set so we need to move L forward removing its character from the set removing its character from the set until it's valid again move this window until it's valid again move this window forward we do that with b and we kick it forward we do that with b and we kick it out of the set and so we do it one more out of the set and so we do it one more time and then now this window is valid time and then now this window is valid again and we can put C back into this again and we can put C back into this set and keep the algorithm going until R set and keep the algorithm going until R is at the end of the string here is some is at the end of the string here is some example code in Python feel free to example code in Python feel free to screenshot this for later | 2024-03-18 10:28:42 | 3 | Sliding Window Algorithm Explained Clearly | Longest Substring Without Repeating Characters Leetcode |
|
1ImaQNKTVnw | hey everybody this is Larry I hit the like button hit the subscribe button let like button hit the subscribe button let me know how you're doing this problem me know how you're doing this problem I'm gonna stop alive right about now I'm gonna stop alive right about now alright when does it end we check if alright when does it end we check if word is valid after substitutions but word is valid after substitutions but giving the string ABC is valid for any giving the string ABC is valid for any valid string read we may split we in the valid string read we may split we in the two pieces x and y such that X plus y X two pieces x and y such that X plus y X concatenated with Y is equal to me X or concatenated with Y is equal to me X or Y may be empty then X plus ABC plus y is Y may be empty then X plus ABC plus y is also well there's a lot I don't manage also well there's a lot I don't manage to die from reading it but for example to die from reading it but for example of s is ABC then string by Australians of s is ABC then string by Australians ABC two pieces wait ABC two pieces wait let me read this again this doesn't know let me read this again this doesn't know but this is a mouthful we may split V but this is a mouthful we may split V into two pieces such that okay so it is into two pieces such that okay so it is just then okay so it's like a word just then okay so it's like a word wrapping itself kind of wrapping itself kind of [Music] can you do that infinite amount of time why is that to so many yeah okay I guess you get to kind of recursively on the definition of exclusive just try to understanding that is hard okay start the by string ABC then we insert other ABC between a bazooka hmm that is an interesting problem oh wait are these always ABC and ABC is the only valid string okay I did I think my prom with some of these LICO proms is that I always miss that part where that that some stuff is a constant way or like their constraints in a constant way and I sometimes miss tie-dyed oh like cheddar Eisen in my head before I realize okay I'm gonna send and it's 20,000 so so that means n square algorism I have a the naive algorithm would be a they are drying falgot Meza and square they are drying falgot Meza and square can I look how can I do better [Music] no it's just one I'm having the greedy is always just get ABC and remove them and then kind of see what happens but that means we remove one at a time like in the case where then it's going to end square ice and truce - ish well how can I do this faster the force is how can I do this faster the force is actually more interesting maybe so only actually more interesting maybe so only way it could be force is if the running way it could be force is if the running count of a b and c is not in worded count of a b and c is not in worded order I don't know that's an easy way to order I don't know that's an easy way to figure out like how I got this is a figure out like how I got this is a guess on my part to be honest I don't guess on my part to be honest I don't know bit of a hunch but I really don't know bit of a hunch but I really don't know if that's expected solution that's know if that's expected solution that's like how like how I don't know how you like how like how I don't know how you were able to kind of figure that out on were able to kind of figure that out on the spot but but basically my idea here the spot but but basically my idea here and looking at the true I didn't really and looking at the true I didn't really get a sense but again the floors I'm get a sense but again the floors I'm trying to confine like the in worst case trying to confine like the in worst case of where as false and I feel like the of where as false and I feel like the case technically force is as if they're case technically force is as if they're more C's that are happening before s and more C's that are happening before s and then kind of like in that in that way then kind of like in that in that way this can only be force if for a given this can only be force if for a given prefix of the string they're more C's prefix of the string they're more C's than B's or AIDS or more ABS than days than B's or AIDS or more ABS than days because in that case them is no matter because in that case them is no matter what they'll always be a C before one of what they'll always be a C before one of the B's and A's the B's and A's I think that's probably how I would I think that's probably how I would think about it I think you have and think about it I think you have and there's the show check that a B and C at there's the show check that a B and C at the end it's the same so so yeah let's the end it's the same so so yeah let's do that mmm we're giving us hot Kody on this [Music] [Music] you see I guess I could write a loop that this I guess I could write a loop that this is just three statements oops what was is just three statements oops what was best enough time Oh - there's another case where that's not true okay it's because ABC to start up here in this or but even if so now I'm thinking about this case where and I guess that's why this one has done with so many downloads where even if you have someone like this it still he goes to force so we have to think about that it's not strange it makes sense that because ABC is not in it but in this case ABC is in it and we stir for so what's our easy way to be hmm I say so every time you see a C it has because like here hmm well no that's how that's a good train to write mommy it's no but I mean I guess I said it that way no but I mean I guess I said it that way but this is also already is imprisoned but this is also already is imprisoned in this so I'm not saying anything new because you can also like from just probably you could just decrement all of them once you get a count oh I see how do I handle this case maybe CC is in a way that is like more natural so we just swap this this is accurate this is good right and just right now I don't need to anything that uh mmm do I have to be linear time where credit is in blood so I had not get in time because that's only other time that would fit and then what albums are there for that I do something like this that we also still the NPP sees me telling such a weird one hmm when you step off my plane juice yeah okay but it's still gonna be in season okay so we don't mean it this time we definitely need this but there's one more property that at least one more I'm also trying to do it obviously I'm also trying to do it obviously without actually simulating it because n without actually simulating it because n is your 20 case that's probably gonna be is your 20 case that's probably gonna be too slow well next is not true well it's ABC it's you know the other ways Arendt squares you know the other ways Arendt squares that is stuff that requires you to like that is stuff that requires you to like remove stuff or and square yeah okay well my friend I think this actually now we might smell a little bit of was it theory of computation or whatever class we're okay I mean you just use stack noka there now whenever you got a see you want to be able to pop off being a explicitly of the first two this will be confusing to me it's Dustin this will be confusing to me it's Dustin to the Typhoon's yes okay non stop pop and stack that pop now start up and see and then we just have to return the link of stack as you go sumo for empty matching hmm and also no car oh okay yeah my hmm to be honest this is wonder one of those times where I just didn't have all right I just didn't have a great intuition about it to be honest and I think in my mind I was how long did I know spending on this 17 minutes I think I got two so one thing that I do do when I stuck when I get stuck is that I will in my mind in numerate its kind of different type of algorithms and think about like hey if I use this does this work in this case that's right there yeah I guess a little bit about stone stacks but I think when I kind of describe the properties of this problem more and more and I guess in a way excuse me in a way the way that I was doing it before it accounting it's a little bit more like a queue where now it's more like a stack well it is a stack and I think the one wrong answer which is the abbc see let me kind of clarify that and down like thing I was trying to and having done one was this where this is force and this is true I was just trying to figure out how to differentiate between the two and stack was what I came up with in that yeah you know that you have to remove like the sub strain of ABCs and then yeah and then you kind of do it recursively in that way and I think I was kind of thinking about it in terms of when I keep on saying and square I was thinking about the stack in a way except for that was the recursive in implicit stack and also not optimal because you're trying a lot of unnecessary possibilities and here was kind of when and I have a linear time and linear space where when and I could do this in a greedy way way I see ABC I just you know we move it and and other properties that I was talking about where like if I see SC I want I need a sand bees to match and this is given more specific subset on that yeah oh well okay a cool problem I don't know it was okay I mean I actually don't think it's worth to down well there may be on the contest there's some issues as I'm going but uh yeah that's | 2024-03-25 13:04:21 | 1,003 | 1003. Check If Word Is Valid After Substitutions (Leetcode Medium) |
|
ZlpYzBuI604 | hello everyone so today we are going to do lead good daily challenge populating do lead good daily challenge populating next right pointers in each node next right pointers in each node so here we are given with a tree and we so here we are given with a tree and we are required to do something like this are required to do something like this which which if we get to our first level node means if we get to our first level node means a node which is at the first level a node which is at the first level then we are simply then we are simply simply simply we need to do is we need to insert a we need to do is we need to insert a null and simply point null and simply point that particular node towards null that particular node towards null because we are populating because we are populating the right pointers the right pointers of each level of our two so in that of each level of our two so in that sense we are doing like this so then sense we are doing like this so then when we reach at next level then two and when we reach at next level then two and three are there at the level so we need three are there at the level so we need to think that first node which is s to think that first node which is s then we need to populate this first node then we need to populate this first node or second level or second level and its right pointer we are required to and its right pointer we are required to populate so when right pointer is there populate so when right pointer is there for this particular civil for this particular civil simply simply simply simply populate it with the three means our populate it with the three means our right point will be pointing towards right point will be pointing towards this and then our three right pointer this and then our three right pointer will be simply pointing will be simply pointing towards null towards null basically not the right pointer as the basically not the right pointer as the as the question is mentioning it's as the question is mentioning it's simply simply required to populate the next pointer required to populate the next pointer this is the one which is in the this is the one which is in the structure of the tree structure of the tree because the right pointer of root would because the right pointer of root would be 3 and the right pointer of 2 would be be 3 and the right pointer of 2 would be 5 right control 3 would be 7 right but 5 right control 3 would be 7 right but we are required to populate the next we are required to populate the next pointer pointer so 1 to null this is the next pointer so 1 to null this is the next pointer which is being populated then two to which is being populated then two to three this is the next pointer which is three this is the next pointer which is being populated with three and three's being populated with three and three's next pointer is being populated with next pointer is being populated with none none then we are killed with four then fourth then we are killed with four then fourth next would be five and five next would be five and five next would be 7 and 7's next would be next would be 7 and 7's next would be null null so like this we are required to simply so like this we are required to simply populate the next pointer of each node populate the next pointer of each node towards the right towards the right but the thing is that how we are but the thing is that how we are required to do all this thing required to do all this thing in front of a question we can see that in front of a question we can see that it's all about doing level by level it's all about doing level by level right right so so from this like even if i say you that from this like even if i say you that we can go towards this depth and do we can go towards this depth and do these things then it would be much these things then it would be much costly for us to do so it's better to do costly for us to do so it's better to do it level by level only means when we are it level by level only means when we are having having uh okay before that let me also the uh okay before that let me also the constraints constraints constraints are simply that number of constraints are simply that number of nodes would be still six thousand right nodes would be still six thousand right but as it is a binary tree so these but as it is a binary tree so these things six thousand would be divided things six thousand would be divided also also even if it is a few three then also at even if it is a few three then also at next six thousand and null next six thousand and null towards each next pointer towards each next pointer that also works fine as even if we do a that also works fine as even if we do a nice manner and then nice manner and then the values of the nodes here the values the values of the nodes here the values of nodes are like um of nodes are like um not much taken into consideration not not much taken into consideration not much valuable for the question much valuable for the question so now comes the part that how we are so now comes the part that how we are required to do this question so we're required to do this question so we're doing this question the thing is doing this question the thing is that that we are simply required to populate the we are simply required to populate the next pointer with null or next pointer with null or the next node which we are having right the next node which we are having right so for doing that thing what we would be so for doing that thing what we would be doing doing we will do a level or traversal and push we will do a level or traversal and push each level each level nodes which are being there into the nodes which are being there into the cube cube means level one then level two then means level one then level two then level three level three so all the nodes which are being there so all the nodes which are being there at each level we would be pushing all at each level we would be pushing all those nodes into the queue right first those nodes into the queue right first thing we are required to do this thing we are required to do this now now this levels nodes are being pushed then this levels nodes are being pushed then we will simply push null to it because we will simply push null to it because at the end we are required to populate at the end we are required to populate it with null also right so whenever all it with null also right so whenever all the nodes of this particular level are the nodes of this particular level are being pushed into the queue and we are being pushed into the queue and we are also required to push null into this also required to push null into this particular cube particular cube and also one thing is that that we are and also one thing is that that we are also required to simply connect all also required to simply connect all these right so connecting all these these right so connecting all these means while we would be pushing all means while we would be pushing all these into the queue in mean time only these into the queue in mean time only when we are having that current node when we are having that current node with us with us what we'll do we'll do current next what we'll do we'll do current next equals to equals to whatever we are having in the front whatever we are having in the front means if our current node is 2 then we means if our current node is 2 then we will simply connect will simply connect this 2 with 3 this 2 with 3 this we are required to do and then this we are required to do and then we'll at the end when we see that yeah we'll at the end when we see that yeah now we don't have anything now we don't have anything into the queue or if we are having into the queue or if we are having but our last note has been pushed into but our last note has been pushed into the queue then we will simply push null the queue then we will simply push null to that to that and then and then we'll again do this particular we'll again do this particular right so we would be doing this question right so we would be doing this question like this like this so so yeah somehow i have yeah somehow i have quality to the intuition that how i quality to the intuition that how i would be required to do this question would be required to do this question now comes the next part about the time now comes the next part about the time complexity and space complexity so time complexity and space complexity so time complexity would be in our complexity would be in our order of height only order of height only where height could be from log n when it where height could be from log n when it is a density populated and it would be is a density populated and it would be log in and if it is a skew tree then it log in and if it is a skew tree then it would be n so we could say the time would be n so we could say the time complexity would be simply order of n complexity would be simply order of n and a space complexity and a space complexity because we are using q because we are using q and x max if it is a skew tree right if and x max if it is a skew tree right if a tree is something like this so all of a tree is something like this so all of them would be required to be pushed into them would be required to be pushed into the queue right so that's why space the queue right so that's why space complexity will be order of n again complexity will be order of n again so like this we are required to do this so like this we are required to do this question now let me walk you through the question now let me walk you through the code of this question code of this question the coding part so here is what i the way i was explaining let me split this particular code into parts and explain you now punch the pad doing dss right so for bff we are required with this queue that i am having now now first thing which we are required to check is that is our 3 mp or it is there so this is the basic if it is if root is not present that is if root equal equals to null then we are required to return nuls at that point only else we will simply push that root in the queue and also push the null because this particular first node it won't be having any other node with it right so with that only then simply push the null also right away so now comes the part of doing dss here so how we are doing dss here is that will check that if uh that means this is a standard bss only that if per q is not empty then we are do processing the nodes so we'll first take the first node from the queue pop it from the queue and now we'll start processing this node now we will check that if it is not null that is uh it is our root node itself or it is another node which we have pushed whichever node it is there will check that if it is not done so yeah a root no display which is not net so this thing we are required to do the thing which i was saying that while processing that node we will simply connect the next pointer of that current node with the one which is there at the front of a cube so this is what we would be doing and then if our current node do have a left node and also do have a right node means if it is having a left node then we'll simply push our current nodes left into the queue if it is having a right node then you will simply push a current node right into the queue so like this at this point one was simply popped out from the queue and now our cube would be having null with it right and also as it was having also it is now being connected because of this particular line this particular line it has been connected and also as other node was being processed so now our cube would be having null it would be having null and then it would be having 2 and 3 because these are the left and right nodes of our one so this is how our second level would be being pushed to the queue now connect the part means after this particular position it will be this point has been done right now it will check uh so now while loop would be there and looks like that is my q empty or not so yeah it is not empty so it will check for the current node now the current node would be simply equal to null because one was popped from the queue and now knowledge there so now null would be there now would be pass now it will check that is my current node is now not so yeah it is null so yes it is null and then our current node is being null then at that point one thing is there means while this while doing this question i just note test that uh because of this thing only we are able to push the null into it so when our current node is null right until that point all the nodes which were being there in the left in that level means the next level would have been pushed there we are able to check that if i said no we are able to check that if i said no this null right this null right and also our q is not empty because the and also our q is not empty because the null is staged for current element and null is staged for current element and at that moment current left and right at that moment current left and right would have been already pushed that would have been already pushed that doesn't mean which i was saying doesn't mean which i was saying thus we are required to push null for thus we are required to push null for those also those also because that level is filled so we are because that level is filled so we are required to now push null for this two required to now push null for this two and three so at that point so this and three so at that point so this particular point our q would be having particular point our q would be having two three and null so this would be the thing now our one level has been completed so again this while loop will go ahead and now at current node won't be null because now our current node would be having two as its as its value so now two other two children would be pushed into it right and then 2 is being popped then 3 would be our current note right so three children would be pushed into this particular and they tell them means when 2 would be done 3 would be done then this null would be again encountered but when this null would be again encountered till then the level third would be completely filled into a queue and we could easily then push null to it so this is how this question is eligible to push a null at each level because the bfs is being done in such a manner that whenever there is a node having some value other than null then surely we are required to push all the children of that node but if our present note is having null value so till then our next level nodes have been completely filled at that moment so we are required to push null for that particular level so this is how this question is being done with uh populating our left right side next point of within null and this uh this is all about this question if there's any doubt or anything we could simply comment that down and this was all for it | 2024-03-21 10:58:33 | 117 | 117. Populating Next Right Pointers in Each Node II || Leetcode Medium || Tree || Cpp |
|
IZMdNccsc-8 | hello guys welcome to another video in the series of coding or today we have the series of coding or today we have with us a problem that is called with us a problem that is called check if number is a sum of powers of check if number is a sum of powers of three so we are given an integer n and three so we are given an integer n and we have to return truth it is possible we have to return truth it is possible to represent n to represent n as the sum of distinct powers of three as the sum of distinct powers of three otherwise you have to return false otherwise you have to return false so when integer y is a power of three if so when integer y is a power of three if there exists an integer x such that y there exists an integer x such that y equal to three power x so let's try to equal to three power x so let's try to understand this so to understand and understand this so to understand and appreciate this appreciate this let's just quickly look at an example of let's just quickly look at an example of binary representation binary representation so that we can solve this problem so so that we can solve this problem so suppose we have to convert the number to suppose we have to convert the number to l to binary representation how do we do l to binary representation how do we do that that it's very simple right so first we make it's very simple right so first we make some some dashes so what do the 3 present these dashes so what do the 3 present these represent the weights represent the weights 2 power 0 2 power 1 2 power 2 and 2 2 power 0 2 power 1 2 power 2 and 2 power 3 power 3 so what do i mean by this so so what do i mean by this so let me also write to power 4 okay so 2 let me also write to power 4 okay so 2 power 0 is power 0 is 1 2 power 1 is 2 1 2 power 1 is 2 2 power 2 is 4 2 power 3 is 8 2 power 4 2 power 2 is 4 2 power 3 is 8 2 power 4 is is 16 right so i have these 16 right so i have these weights and using these weights i have weights and using these weights i have to try to make the number 12 how can i to try to make the number 12 how can i do that right do that right so what can i do i can pick up 8 so i so what can i do i can pick up 8 so i pick up 8 pick up 8 that means i put 1 here then i pick up 4 that means i put 1 here then i pick up 4 so i put another 1 here so i put another 1 here so when i pick up 8 so what i do is so when i pick up 8 so what i do is first time i picked up 8 i had to make first time i picked up 8 i had to make 12 so 12 so when i picked up 8 i made the sum when i picked up 8 i made the sum from 12 to 4 because now i have to make from 12 to 4 because now i have to make only 4 i have only 4 i have picked up 8 means i have made it i have picked up 8 means i have made it i have to just make 4 to just make 4 so now next time when i'm making 4 i do so now next time when i'm making 4 i do 4 minus 4 4 minus 4 and that gives 0 so now i have to make and that gives 0 so now i have to make no more and finally i get 0 that means i no more and finally i get 0 that means i made made whatever number i wanted to make so i i whatever number i wanted to make so i i put 0 0 for the remaining so this is the put 0 0 for the remaining so this is the binary representation binary representation and it is made up of these quantities and it is made up of these quantities right so 12 is nothing but 8 plus 4 right so 12 is nothing but 8 plus 4 or 12 is nothing but 2 power 3 plus 2 or 12 is nothing but 2 power 3 plus 2 power 2 power 2 so this is a binary representation right so this is a binary representation right let's take another example let's take another example to appreciate it okay so if i have to to appreciate it okay so if i have to make some number make some number like say 7 how do i do that so again like say 7 how do i do that so again 2 power 0 2 power 1 2 power 2 2 power 0 2 power 1 2 power 2 let me write okay so 2 power 0 is let me write okay so 2 power 0 is 1 2 power 1 s 2 2 power with 4 to power 1 2 power 1 s 2 2 power with 4 to power 3 is 8 3 is 8 so what i do i have to just pick up so what i do i have to just pick up weights right so now 8 is greater than 7 weights right so now 8 is greater than 7 so i need not consider these so i need not consider these because from 8 how can i make 7 because from 8 how can i make 7 so i need to make 7 so i'll make it up so i need to make 7 so i'll make it up by sum of smaller numbers only by sum of smaller numbers only so i take the biggest number 4 so 7 so i take the biggest number 4 so 7 minus 4 is 3 so first i pick up 4 minus 4 is 3 so first i pick up 4 that means now i have picked up 4 that means now i have picked up 4 okay and now only 3 is yet to be made okay and now only 3 is yet to be made so how can i make 3 so i pick up the so how can i make 3 so i pick up the next bigger number next bigger number 2 3 minus 2 is 1 2 3 minus 2 is 1 so i write 1 here then i i still have to so i write 1 here then i i still have to make 1 make 1 so i pick up the next biggest number 1 1 so i pick up the next biggest number 1 1 minus 1 is 0 so i make 0 minus 1 is 0 so i make 0 so that means i have made the possible so that means i have made the possible sum that i wanted to make sum that i wanted to make and i write 1 here so i have made up and i write 1 here so i have made up 7 using 4 plus 2 plus 1 7 using 4 plus 2 plus 1 so i made up 7 using basically just 2 so i made up 7 using basically just 2 power 2 power 2 plus 2 power 1 plus 2 power 0 plus 2 power 1 plus 2 power 0 okay so this is binary representation okay so this is binary representation why did this is because it's going to why did this is because it's going to help us solve this problem help us solve this problem so similarly uh we can you know we have so similarly uh we can you know we have to just represent in the to just represent in the base system of three in place of two now base system of three in place of two now okay we have to just do the same thing okay we have to just do the same thing okay let's consider this example it says okay let's consider this example it says we have to make 12 we have to make 12 but now instead of weights of powers of but now instead of weights of powers of two we have powers of three two we have powers of three so this is what is the question so so so this is what is the question so so let me write the same thing so 3 power 0 let me write the same thing so 3 power 0 is 1 is 1 3 power 1 is 3 3 power 2 is 9 3 power 3 3 power 1 is 3 3 power 2 is 9 3 power 3 is 27 is 27 okay so now let me start picking up okay so now let me start picking up weights 27 is greater than 12 so let me weights 27 is greater than 12 so let me ignore that so i will start picking up ignore that so i will start picking up weights from 9 weights from 9 so i pick up weights from 9 okay so now so i pick up weights from 9 okay so now i subtract 9 from 12 because i took 9 i subtract 9 from 12 because i took 9 from the sum from the sum now my sum is just 3 i have to just make now my sum is just 3 i have to just make 3 more so how can i make 3 more 3 more so how can i make 3 more i try to pick up the next weight so i i try to pick up the next weight so i have 3 minus 3 have 3 minus 3 and it gives 0 right so and it gives 0 right so i have already made 0 so i need not use i have already made 0 so i need not use other numbers other numbers so 12 is basically just 3 power 2 so 12 is basically just 3 power 2 plus 3 9 plus 3 is 12 plus 3 9 plus 3 is 12 so uh i can make 12 right because in the so uh i can make 12 right because in the end end i got this quantity as 0 okay let's take i got this quantity as 0 okay let's take some example uh where maybe we cannot some example uh where maybe we cannot make make okay let's consider some example like 17 okay let's consider some example like 17 so if it is 17 again we try to you know so if it is 17 again we try to you know take this example i write the weights take this example i write the weights 3 power 0 3 power 1 3 power 2 3 power 3 3 power 0 3 power 1 3 power 2 3 power 3 so 3 power 0 is 1 3 power 1 is 3 3 power so 3 power 0 is 1 3 power 1 is 3 3 power 2 is 9 3 power 2 is 9 3 power 3 is 27 and i try to pick up weights 3 is 27 and i try to pick up weights so say i need not take 27 because 27 is so say i need not take 27 because 27 is larger than 17 larger than 17 let me take 9 okay i take 9 so now let me take 9 okay i take 9 so now what is the remaining number that i have what is the remaining number that i have to make from 17 i've already to make from 17 i've already made 9 my sum is now 8 so i have to make made 9 my sum is now 8 so i have to make 8 let me see if i can make 8 okay 8 let me see if i can make 8 okay i've already picked up 9 so let me pick i've already picked up 9 so let me pick the next number so 8 minus 3 the next number so 8 minus 3 8 minus 3 is 5. so 8 minus 3 is 5. so i have used this 3 also ok now i have used this 3 also ok now next i can use the next number so 5 next i can use the next number so 5 minus 1 is 4 minus 1 is 4 now i am still short of 4 i have used up now i am still short of 4 i have used up all the numbers but i still couldn't all the numbers but i still couldn't make because my make because my final answer is not 0 because 4 is still final answer is not 0 because 4 is still remaining right so what i have done remaining right so what i have done i have tried to make 17 using i have tried to make 17 using 9 plus 3 plus 1 i've tried to use all 9 plus 3 plus 1 i've tried to use all the weights that i have but the weights the weights that i have but the weights that i have that i have are not able to give me 17. i am still are not able to give me 17. i am still falling short by falling short by 4 right so if this had been 0 if final 4 right so if this had been 0 if final crap in 0 means i would have been able crap in 0 means i would have been able to make to make the number 9 plus 3 is 12 10 plus 1 is the number 9 plus 3 is 12 10 plus 1 is 13 i am not able to make 17 13 i am not able to make 17 so this is uh what it is okay and let me so this is uh what it is okay and let me just consider one last example before just consider one last example before going to the code so let me try to make going to the code so let me try to make 30 30 okay so how can i make 30 let me just okay so how can i make 30 let me just write 3 power write 3 power 0 3 power 1 3 power 2 3 power 3 0 3 power 1 3 power 2 3 power 3 okay 3 power 4 will exceed 3 power 4 is okay 3 power 4 will exceed 3 power 4 is 81 81 so that will exceed let me write all so that will exceed let me write all other powers other powers so i need not use this because uh 81 is so i need not use this because uh 81 is larger than 30 i have to make 30 right larger than 30 i have to make 30 right so i pick up the uh largest weight so 30 so i pick up the uh largest weight so 30 30 minus 27 30 minus 27 is 30 30 minus 27 30 minus 27 is 30 okay so i have used up 27 okay so i have used up 27 and now i have to make only three right and now i have to make only three right so now i go to the so now i go to the next number so next number which is next number so next number which is in line such that i can make in line such that i can make 3 i have to just make 3 so i need not 3 i have to just make 3 so i need not take 9 because if i take 9 i will get take 9 because if i take 9 i will get negative negative number right so i will take 3 only i number right so i will take 3 only i will take a number which is smaller than will take a number which is smaller than the sum so now sum is 3 i have to make 3 the sum so now sum is 3 i have to make 3 3 minus 3 is 0 so i finally reach 0 3 minus 3 is 0 so i finally reach 0 that means i have used so if it was the that means i have used so if it was the 3 system this would have been the 3 system this would have been the representation representation if it was the base system of 3 this if it was the base system of 3 this would have been the representation just would have been the representation just like we write binary like we write binary and we have just used these two and we have just used these two quantities so 30 is just 27 quantities so 30 is just 27 plus 3 so 30 is just 3 power 3 plus 3 so 30 is just 3 power 3 plus 3 power 1 so i have been plus 3 power 1 so i have been successfully successfully been able to make 30 because finally i been able to make 30 because finally i am getting 0 that means i have consumed am getting 0 that means i have consumed the weights required to make the the weights required to make the number which i wanted to make so now let number which i wanted to make so now let me write the code of this the code of it me write the code of this the code of it is is should be simple because if you have should be simple because if you have understood logic understood logic it's a three line code so if n is less it's a three line code so if n is less than equal to 10 power 7 is given than equal to 10 power 7 is given so what we will do so we cannot have a so what we will do so we cannot have a number which is greater than 10 power 7 number which is greater than 10 power 7 so what we will do so what we will do we will take power of 3 which is smaller we will take power of 3 which is smaller than this particular quantity because than this particular quantity because you need to subtract the powers of 3 you need to subtract the powers of 3 from this from this number n so we will take the power of 3 number n so we will take the power of 3 which is just closest to this which is just closest to this but smaller than this so we will start but smaller than this so we will start from that so that is 14 so 10 from that so that is 14 so 10 3 power 14 will be your just closest to 3 power 14 will be your just closest to this 10 power 7 so i will start from 14 this 10 power 7 so i will start from 14 so for in i equal to 14 so for in i equal to 14 i greater than equal to 0 i minus minus i greater than equal to 0 i minus minus okay so basically i is just the powers okay so basically i is just the powers that i am going to take so it will be that i am going to take so it will be clear once i write this okay clear once i write this okay so let me write number so into number is so let me write number so into number is equal to power equal to power of 3 power i so power of 3 of 3 power i so power of 3 comma i just gives 3 power i okay so comma i just gives 3 power i okay so in this case when we consider 30 so we in this case when we consider 30 so we are just are just you know initially what we will do is we you know initially what we will do is we are starting from i equal to 14 but uh are starting from i equal to 14 but uh those quantities will anyway be larger those quantities will anyway be larger right so we will start from right so we will start from 3 power 3 only in this case so i will be 3 power 3 only in this case so i will be 3 first i will be 3 3 first i will be 3 so you will get 3 power 3 so you will so you will get 3 power 3 so you will get 3 power get 3 power or 3 okay which is 27 now what you have or 3 okay which is 27 now what you have to do is to do is you have to subtract 27 from n you have to subtract 27 from n okay so if n minus x is greater than okay so if n minus x is greater than equal to 0 that means if you are equal to 0 that means if you are successfully able to subtract successfully able to subtract so i mean number n minus number so if so i mean number n minus number so if you are successfully able to subtract you are successfully able to subtract this number this number from our n okay if n minus from our n okay if n minus number is greater than equal to 0 for number is greater than equal to 0 for example in this case example in this case when i becomes equal to 3 then when i becomes equal to 3 then you will be able to subtract 27 from 30 you will be able to subtract 27 from 30 if n is 30 30 minus 27 if n is 30 30 minus 27 will be equal to uh 3 will be equal to uh 3 right so you will be able to subtract so right so you will be able to subtract so this is n this is this is n this is a n or o or which is number a n or o or which is number n minus number okay and if that is so n minus number okay and if that is so fine then what you lose n minus fine then what you lose n minus equal to number so what i'm doing then equal to number so what i'm doing then i'm subtracting it so now my number i'm subtracting it so now my number which was 30 which was 30 now number becomes 30 minus 27 right so now number becomes 30 minus 27 right so my number becomes my number becomes 3 because i have already made 27 3 because i have already made 27 successfully successfully from 30 30 was the number that i wanted from 30 30 was the number that i wanted to make 30 was n 30 was the sum that i to make 30 was n 30 was the sum that i wanted to make so from 30 i subtracted wanted to make so from 30 i subtracted 27 i need to make only three 27 i need to make only three so i reduced my number by okay so i so i reduced my number by okay so i reduce my n reduce my n by number so this this variable is by number so this this variable is confusing but uh confusing but uh i hope that logic is clear so i hope that logic is clear so ah this becomes equal to 3 so now my n ah this becomes equal to 3 so now my n has taken the value of 3 has taken the value of 3 okay now if any time n becomes equal to okay now if any time n becomes equal to 0 0 right so next time what will happen is right so next time what will happen is next time in this iteration i will next time in this iteration i will become equal to 2 become equal to 2 okay when i becomes equal to 2 so okay when i becomes equal to 2 so so let me write i becomes equal to 2 so so let me write i becomes equal to 2 so 3 power 2 is 9 3 power 2 is 9 so now n is 3 when we check 3 minus so now n is 3 when we check 3 minus 9 okay that will be a negative number so 9 okay that will be a negative number so this if this if n minus number greater than equal to n minus number greater than equal to zero condition will not be satisfied zero condition will not be satisfied so we will just go to the next iteration so we will just go to the next iteration so in the next iteration so in the next iteration uh i will become equal to 1 so 3 power 1 uh i will become equal to 1 so 3 power 1 is 3 then 3 minus 3 is equal to is 3 then 3 minus 3 is equal to 0 so now we have given this condition n 0 so now we have given this condition n minus number greater than equal to 0. so minus number greater than equal to 0. so this condition will be satisfied this condition will be satisfied so n will become equal to 0 so n becomes so n will become equal to 0 so n becomes equal to 0 equal to 0 right so now if n is 0 we can return right so now if n is 0 we can return true that means we have successfully true that means we have successfully been able to make the number been able to make the number otherwise at last we can return false otherwise at last we can return false okay and now i took the example by okay and now i took the example by starting from 3 power 3 starting from 3 power 3 but what it will do is it will start but what it will do is it will start from 3 power 14 from 3 power 14 because i just explained that we have to because i just explained that we have to take n less than equal to 10 power 7 so take n less than equal to 10 power 7 so that is the maximum case that they can that is the maximum case that they can give us give us so what will happen even if your n is 30 so what will happen even if your n is 30 okay when we start from 3 power 14 okay when we start from 3 power 14 when we try to subtract okay when we try when we try to subtract okay when we try to subtract to subtract 3 power 14 okay so and number is 3 power 3 power 14 okay so and number is 3 power 14 14 n is 30 so 30 minus um n is 30 so 30 minus um let's say 3 power 14 that will be a let's say 3 power 14 that will be a negative quantity it will be large negative quantity it will be large negative quantity so we need not worry n negative quantity so we need not worry n will just remain as n will just remain as n and it will keep iterating it will keep and it will keep iterating it will keep decrementing i okay so this will become decrementing i okay so this will become 13 this will become 12 13 this will become 12 and so on unless we reach uh 3 power 3 and so on unless we reach uh 3 power 3 okay when once we reach this okay when once we reach this then um so 3 power 3 is 27 30 minus 27 then um so 3 power 3 is 27 30 minus 27 is uh is uh greater than equal to 0 so then we n greater than equal to 0 so then we n will uh subtract and we will get the will uh subtract and we will get the iteration that we just saw so i hope iteration that we just saw so i hope that that this was helpful let me just run and see this was helpful let me just run and see if it is accepted if it is accepted so it is fine for this let me just so it is fine for this let me just submit and see if it is accepted submit and see if it is accepted so it's an accepted solution that's it so it's an accepted solution that's it thank you for being patient and thank you for being patient and listening | 2024-03-22 14:35:03 | 1,780 | Leetcode 1780. Check if Number is a Sum of Powers of Three #Leetcode #1780 #powers of three |
|
FnxMbolL9cM | hello everyone I'm going to be showing you guys how to do 70 climbing stairs you guys how to do 70 climbing stairs and it's ranked easy for elite code and it's ranked easy for elite code so it says you're climbing a staircase so it says you're climbing a staircase it takes n-steps to reach the top each it takes n-steps to reach the top each time you can either climb one or two time you can either climb one or two steps steps and how many distinct ways can you climb and how many distinct ways can you climb to the top to the top so it's just checking the possibilities so it's just checking the possibilities of uh how many times you can climb to of uh how many times you can climb to the top and you have one or two steps uh the top and you have one or two steps uh for the first example there's two steps for the first example there's two steps so the output is two because there are so the output is two because there are only two ways to climb to the top it's only two ways to climb to the top it's either one step plus one step or two either one step plus one step or two steps but you should also recognize steps but you should also recognize example two n equals three the output is example two n equals three the output is three three the explanation is that there are three the explanation is that there are three ways to come to the top so it literally ways to come to the top so it literally takes every uh way to climb to the top takes every uh way to climb to the top so One Stop Plus One Stop plus one stop so One Stop Plus One Stop plus one stop one stop plus two step and two steps one stop plus two step and two steps plus one step plus one step so so we gotta keep that in mind first you can we gotta keep that in mind first you can set two variables so step two variables set two variables so step two variables you can set it to you let's name it one you can set it to you let's name it one two and we'll do one one two and we'll do one one okay so you wanna Loop through n minus okay so you wanna Loop through n minus one all right so you want to set one equals to one plus two and then two equal to one but if you think about line seven two equal to one doesn't make sense because uh will equal it to one plus two we don't want to do that we just want it to equal to the value of one right here so what you can do before uh one equals one plus two you can do uh temp equals to one so temporary value and equal to equals itself so one one plus two and then one uh the value of 2 will be one because we made a new variable right here so and iterating through and iterating through n minus one n minus one Okay so Okay so we have this down now we want to make we have this down now we want to make sure we return it on the outside so we sure we return it on the outside so we return one and this should give you the value yep there you go and I hope this makes sense to y'all | 2024-03-20 11:22:21 | 70 | LeetCode: 70 - Climbing Stairs (Python) |
|
o4YuEQ9kM74 | We have to do that so we we will see later how it comes in this type of picture first let's understand so what is given here is where life is asteroids of wait representing asteroid in ours okay so we have the ering of an asteroid asteroids Richter absolute value represented size on Ka, so whatever the error image is, it tells the size of the asteroids, like here we have 510 and -5, so if 5 is 5 and if 10 is OK, then the size of the rate of 5x is If it is then it will be bigger than 10 Okay so If it is then it will be bigger than 10 Okay so If it is then it will be bigger than 10 Okay so this is tells our size of D story Okay so this is tells our size of D story Okay so D sign in represents its direction D sign in represents its direction So positive meaning right and negative meaning So positive meaning right and negative meaning left Okay so if this five and this 10 if left Okay so if this five and this 10 if positive AIDS means this what does positive AIDS means this what does this mean this mean this mean right and if this is minus five here we can see -5 then what will be its size, what will have to be done but it will go to the left because its sign is negative here Coming at Coming at Coming at speed from D, what does it mean that these two speed from D, what does it mean that these two asteroids which are five and 10 are going at speed from this, asteroids which are five and 10 are going at speed from this, if they are going in the same direction if they are going in the same direction then they will never collide but then they will never collide but if they are going in a different direction then if they are going in a different direction then it means collision okay so it means collision okay so it means collision okay so state of d asteroid after which colleges so what we have to do in the last return is to direct an output in which what is the state of the asteroid we have to give that means asteroid concept children that is what we have to return here and if collide ok If they are over then it will not If they are over then it will not If they are over then it will not remain here OK so here what we have given is remain here OK so here what we have given is that IF tu asteroid made d smaller one will that IF tu asteroid made d smaller one will collide OK so 10 and -5 collide OK so 10 and -5 will collide here right so what is given here will collide here right so what is given here that the smaller one is that that the smaller one is that that the smaller one is that means mines five bill explode and these both are R of D size both bill explore like here fiber is -5 so 5 and -5 if collide then both x will be loaded neither of them will be left 2s so right Moving in the direction from D. Okay, so if there is five and 10, they will not weigh, so from our example here, like 8 and -8 are given here, what does it mean that both the asteroids are of the same size but they are Direction, Direction, Direction, both of them will collide and both bills get destroyed, both of them will collide and both bills get destroyed, so here our output so here our output is the output which we have given, it is empty is the output which we have given, it is empty iron. Okay, so what will be the approach in this, what will iron. Okay, so what will be the approach in this, what will they do? Here we can see that whenever they do? Here we can see that whenever such a thing happens. such a thing happens. such a thing happens. pop the action or destroy, we have to give it after seeing the first element and the second element, then the date time is mostly given by time. Okay, so in this we are doing it for stay because here It is doing one of the two It is doing one of the two It is doing one of the two and it depends on looking at the previous ones, and it depends on looking at the previous ones, meaning like we took 10, like meaning like we took 10, like we put five, but we put five, but from this we will not know what we have to from this we will not know what we have to do next, so if we get minus five, then do next, so if we get minus five, then we we we n't do this, then this time will come, okay, if we strike him, then how will be the solution in our strike, what will we do, we will start traveling from here, right okay and right, we will be able to do We will maintain and what we will do is that We will maintain and what we will do is that We will maintain and what we will do is that if we come to any of our elements then if it is if we come to any of our elements then if it is empty then directly we will push it empty then directly we will push it here OK and if any element remains here OK and if any element remains if it is assumed we will push it positive and the if it is assumed we will push it positive and the next element is positive then still proceed next element is positive then still proceed directly. directly. directly. element if is negative so what bill do they bill compare with our top of D Okay so what can we do here like our 10 put we give over next element is positive so they bill again no no The next The next The next element here is pe-5 so we'll look at minus five so element here is pe-5 so we'll look at minus five so what we'll do is we'll compare it to our top of what we'll do is we'll compare it to our top of D cent tax so D cent tax so what's bigger between -5 and 2 here is this minus five what's bigger between -5 and 2 here is this minus five is bigger because here is bigger because here is bigger because here not a problem with mines Bill Have you take d absolute of d number so take its absolute value so will be 5 so five give it greater 2 so what bill do they bill pop this out bill pop this out and give what Without top of this type Without top of this type Without top of this type again so our top of this type is 10 right again so our top of this type is 10 right so this is our top okay we will compare 5 and 10 so so this is our top okay we will compare 5 and 10 so here 10 is greater so this is five's here 10 is greater so this is five's we will not do anything here we will not do anything here okay so which office tag okay so which office tag okay so which office tag final result. Okay, so the asteroids left in the strike now will be the same result as the steroids left in the last strike. So here, when we compare -5 and 10, then the bill C's -5 will be Note push it Note push it Note push it in it okay because they are smaller written in it okay because they are smaller written and give what bill do you bill compare our and give what bill do you bill compare our so 11 is greater give 10 so or it's a so 11 is greater give 10 so or it's a greater so what will we do pop this greater so what will we do pop this and here what we will do -11 insert and here what we will do -11 insert Because there is no number ahead and Because there is no number ahead and this is strike vote then bill directly this is strike vote then bill directly insert minus 11 so this is the logic way insert minus 11 so this is the logic way bill try you implemented okay in the morning also bill try you implemented okay in the morning also start implementing so what we will do first start implementing so what we will do first we will write our style and do normal and one what we will do we will size size ok after that what will we do Asteroids ok so here what happened is that when the strike will not be our empty ok second will not be empty then what will we see If that's top, If that's top, If that's top, if that's greater than the current element, if that's greater than the current element, if that's more than that, negative pocket if that's more than that, negative pocket top, and that's going to push our current limit, top, and that's going to push our current limit, okay, so what we're going to do here is okay, so what we're going to do here is STK dot top, STK dot top, that's your greater. that's your greater. that's your greater. positive if it is positive and our asteroid which is okay so our asteroid now which is the current element current asset which is if it is negative so if it is negative then what will we write top which is our which is the positive element okay Aggarwal Lee, ours is asteroids, Aggarwal Lee, ours is asteroids, Aggarwal Lee, ours is asteroids, so what will we do, we will take its absolute, so what will we do, we will take its absolute, okay so we will take its absolute, and what will we write here, okay so we will take its absolute, and what will we write here, if it is less than what is ours now, we will make it okay, then top, if ours is Greater Abraham, If the same If the same If the same if the top is getting if the top is getting bigger then what they bill do they bill just to bigger then what they bill do they bill just to I plus plus okay so I plus I plus plus okay so I plus plus rate and will do direct increment if we plus rate and will do direct increment if we look at the next negative number then it look at the next negative number then it means whatever students are left in the last will be means whatever students are left in the last will be our our our start back, so what will happen here, we will not do cadence, what will you put in the condition, the one who is going in asteroid negative and the one who is on top i.e. who is positive, Will get disturbed right so what Will get disturbed right so what Will get disturbed right so what bill just like dot com because we will pop the positive one which is in strike and we will also increment the bill and we will pop the positive one which is in strike and we will also increment the bill and sound ok they also incremented the sound ok they also incremented the value ok so this is ours value ok so this is ours what was this in this condition what was this in this condition what was this in this condition if it is positive and when the current element is negative then we have to do all this but if the time we have is positive and the next element is positive then what we will do is we will directly push right so here after the if condition. and after that we will do something i plus plus what is happening, we will and after that we will do something i plus plus what is happening, we will first do something increment so here we have done first do something increment so here we have done okay so now what we will do is okay so now what we will do is finish smile loco and after that what we will do we will simply Whatever asteroid we have in our track, we will Whatever asteroid we have in our track, we will Whatever asteroid we have in our track, we will simply put it in the result, simply put it in the result, so what will we do to make it useless, what will we do, we will put another one for the asteroid, we will pop the egg and put another one for the asteroid, we will pop the egg and put it in the result, then what will happen with that, that is put it in the result, then what will happen with that, that is our starting. our starting. our starting. put in this type also, it is the opposite, meaning if we look here, if we look here, we have done something like 10 here and then you have pushed, if one - 5, everyone When we do something, we have to give When we do something, we have to give When we do something, we have to give him the result, don't you him the result, don't you give another 10, we have to give 10 and 2 sitters, okay so what bill do they bill him, give another 10, we have to give 10 and 2 sitters, okay so what bill do they bill him, type it type it back, correct order and this what they can do this but back, correct order and this what they can do this but they can do this they can do this water bill If driver seat pops from back and back side bill If driver seat pops from back and back side travel, then we will put it in the last, travel, then we will put it in the last, right so date is our way, you do it, right so date is our way, you do it, so what will we do here, we will so what will we do here, we will put it on SDK.com, Back in I plus Back in I plus Back in I plus plus means I can go to the next element plus means I can go to the next element okay so by doing this our result will okay so by doing this our result will be populated and give what they can do it they can just return our be populated and give what they can do it they can just return our result so result so here we are right time offer okay so when does this come here we are right time offer okay so when does this come when when when do plus here, sometimes we make the error straight, so we can see here that if we travel from last, last time is zero then travel and they are increment so this OK, so what will we do here and here our result will be in dot size because here the result which we have taken as a vector, what will be its size, its size will be result minus one, we will travel from there, we will submit it and see. Next Video By Next Video By [Music] | 2024-03-21 11:54:58 | 735 | Asteroid Collision | Stack Based Approach | Leetcode | 735 |
|
71hgZy3uEJ8 | uh hey hey everybody this is larry this is a cube one of the recent contests is a cube one of the recent contests uh three consecutive odds um so this is uh three consecutive odds um so this is easy and it's easy i think you should easy and it's easy i think you should just do the first thing that comes into just do the first thing that comes into your mind your mind and in this case given that n is less and in this case given that n is less than a thousand than a thousand just do the stupid thing uh and that's just do the stupid thing uh and that's basically what i did um basically what i did um i you could see me solve it during the i you could see me solve it during the contest and i solved it in something contest and i solved it in something like 40 seconds or something like that like 40 seconds or something like that but i was even too lazy to put minus two but i was even too lazy to put minus two here because i didn't want it to here because i didn't want it to have enough by one so i just did have enough by one so i just did you know if the first numbers are the you know if the first numbers are the second numbers are then the third number second numbers are then the third number is odd is odd then return true otherwise just return then return true otherwise just return first so it should be straightforward first so it should be straightforward uh if you're watching this video i don't uh if you're watching this video i don't know why to be honest but know why to be honest but hope you solved it quickly um and yeah hope you solved it quickly um and yeah let me know what you think and you can let me know what you think and you can watch me stop it live | 2024-03-21 11:47:45 | 1,550 | 1550. Three Consecutive Odds (Leetcode Easy) |
|
roRCxBmstHQ | guys this is you sir hi Serena going in this video I'm going to take a look at this video I'm going to take a look at 266 button pattern from permutation 266 button pattern from permutation clean a string to me for the permutation clean a string to me for the permutation of the string could form a palindrome of the string could form a palindrome told not okay told not okay may be true your rear rack true so what may be true your rear rack true so what is palatal it means like a be a and AP is palatal it means like a be a and AP day right so you read it from left or day right so you read it from left or from right it could be saying so from right it could be saying so actually we if we if we because it's actually we if we if we because it's symmetric if it's all it means they will symmetric if it's all it means they will be always duplicate numbers right be always duplicate numbers right two plates accepts the middle one so for two plates accepts the middle one so for this case will be one odd count for the this case will be one odd count for the characters and or even else and for the characters and or even else and for the case here or even right so actually what we can do is just account count the characters count the character and the are count the doubt count must be smaller waited one men it could be a parent oh yeah so it so we do we get the count quickly count no we have we have to count to four all of them yeah let's count it so user created years already years already we're not saying that okay we're not we're not saying that okay we're not guaranteed a B the B string is only half guaranteed a B the B string is only half of it so this is cat okay for a minute of it so this is cat okay for a minute actor of SAT tool okay so now we count actor of SAT tool okay so now we count the all count count of aunt earth okay the all count count of aunt earth okay so for that or an it's count is not these brings values divided - he's a macho equals one which mean we have found that articles so plus one right and then if either one then the triangle pose finally we try to write so this is the solution to look at and then autocrine uh my head is in the and then autocrine uh my head is in the work it's too late count and occurrence work it's too late count and occurrence of devalues it should be all ah there's of devalues it should be all ah there's a typo here man who yeah it's breezy now a typo here man who yeah it's breezy now hug helps say the exact right | 2024-03-22 12:23:50 | 266 | LeetCode 266. Palindrome Permutation | JSer - JavaScript & Algorithm |
|
wnoVc3BZMkA | hey hey everybody this is larry this is day 28 of the august decode daily day 28 of the august decode daily challenge challenge i hit the like button hit the subscribe i hit the like button hit the subscribe button and button and let's get started uh join me on discord let's get started uh join me on discord and implement rent 10 using van 7 using and implement rent 10 using van 7 using a given when seven one two seven uh okay a given when seven one two seven uh okay yeah i mean okay yeah i mean okay what are these oh they're just number what are these oh they're just number numbers um so the couple of ways we can do it uh the the most naive way is just we do it twice if it's outside of um you know you have if it's outside of um you know you have two numbers two numbers uh and and uh and and you can i was gonna say you could add you can i was gonna say you could add them but then that them but then that doesn't give you an even distribution doesn't give you an even distribution because then you have this binomial because then you have this binomial thing right so you could just multiply thing right so you could just multiply them and them and um and then if it's not from um and then if it's not from um if it's not um if it's not uh um from 1 to 40 or whatever it is uh um from 1 to 40 or whatever it is then now can you multiply them then now can you multiply them uh i mean i guess the most naive is just uh i mean i guess the most naive is just do it 10 times do it 10 times uh and then sum it up is that right my math is pretty terrible today i think that should be rough yeah i mean i think for some reason i think i'm square boot but i think what i actually wanted to say was just do a base seven um oh sorry i think of square but uh but yeah this is one of those one-off farms maybe an even interview from but it doesn't really come up that much so my tools are a little bit rusty for it uh so that's what i'm thinking about again but this is a good problem to think about i just come up like i'm gonna sell the sim requirement elementary um algorithms back in college uh so definitely it's a fun brain teaser e problem uh and and yeah and i think i was thinking of squaring it to get to base seven but what i actually want is just the base seven um and then now we have a base seven number um we can just divide it by in this case it goes the ranges from one to forty nine uh we just want to get it to 1 to 40 divided by 4 so we get 1 to 10 uh and then we and then we um we roll it right uh if it doesn't uh and you could do another way as well you got this base 7 number uh and then if it's not between one to ten but then you would reroll a lot of times right um so yeah and we'll do the math uh afterwards maybe we do these follow-up questions uh but yeah so that's what i'm gonna do for now um so now we have let's just say a rand 49 um which i guess is it 149 i guess it's around 49. now it just depends on with the serial base or one based is what i was thinking of um so yeah so this is just return rand of seven uh times seven plus random seven um maybe plus one wait is one seven one two seven okay so actually um because yeah but then you wanna plus one again but then you wanna plus one again right i'm just trying to think about the right i'm just trying to think about the edge case of like okay edge case of like okay so this is uh one and this is zero um sorry if this is two this is so this is one then this would be seven right so okay and then now we do wow when 49 um is less than or you go to i'm just going to do this in uh so this gives us a number from just to be clear this gives us from zero to zero to 48 um so yeah so now while this is less than 40 or this is greater than or equal to 40. operated in yet i don't know let's try if not then we just someone like that right yeah someone like that right yeah yes it's just getting random numbers uh yes it's just getting random numbers uh let's see if it gives us any issues let's see if it gives us any issues uh okay the world's operator kind of uh okay the world's operator kind of works but not really works but not really oh no no this is fine for some reason i oh no no this is fine for some reason i thought it was seven thought it was seven uh uh let's try again i mean randomness is let's try again i mean randomness is always tough to kind of eyeball always tough to kind of eyeball uh but it looks okay in that it doesn't uh but it looks okay in that it doesn't give you anything bigger than 10 it give you anything bigger than 10 it doesn't give you anything smaller than doesn't give you anything smaller than uh uh one right so yeah let's go submit this one right so yeah let's go submit this and then we'll analyze this uh code and then we'll analyze this uh code later with later with cool uh yeah uh cool uh yeah uh again so this takes some practice and it again so this takes some practice and it took and i just woke up that's my excuse took and i just woke up that's my excuse but uh but you know it took me a little but uh but you know it took me a little bit to catch up on it um because i was bit to catch up on it um because i was seeing some seeing some at because you know and and one thing is at because you know and and one thing is just with experience you can just with experience you can at least validate your dots very quickly at least validate your dots very quickly right i said oh you could just add them right i said oh you could just add them and then you know and it adds up to up and then you know and it adds up to up to 14 and you just stick to it one to to 14 and you just stick to it one to ten but then i was like oh right now ten but then i was like oh right now that's just obviously binomial that's just obviously binomial uh choose two so then that means that uh choose two so then that means that you have this like peak thing right you have this like peak thing right um because that was not going to be um because that was not going to be uniform and then i said uniform and then i said squaring uh not squaring them but squaring uh not squaring them but multiplying them but then multiplying them but then obviously you're not going to get the obviously you're not going to get the right distribution even though it goes right distribution even though it goes from 0 to 49 so from 0 to 49 so or 0 to 48 uh or 1 to 49 i guess so the or 0 to 48 uh or 1 to 49 i guess so the domain is right but it's a little bit domain is right but it's a little bit off off uh because it's not you know every uh because it's not you know every number is going to be number is going to be not equal to represent represented so not equal to represent represented so then i just remembered i was like oh then i just remembered i was like oh yeah you just need a base seven number yeah you just need a base seven number um yeah and um yeah and basically um so what is the expected basically um so what is the expected number of calls right so number of calls right so this so you do something like uh so you this so you do something like uh so you could also do something like this could also do something like this uh and they would probably work but it uh and they would probably work but it may be a lot slower may be a lot slower so if you have something like this then so if you have something like this then well what's the chance of success right well what's the chance of success right um so the expected value of um so the expected value of x is equal to x um x is equal to x um just expect the value of x plus um in this case it is but oh uh i think i just messed it up but oh uh i think i just messed it up it's like i said it's like i said um so it's four fifths roughly speaking um so it's four fifths roughly speaking i mean i'm hand waving is actually i mean i'm hand waving is actually um okay fine let's just be precise then um okay fine let's just be precise then right so it's like 39 out of 49. right so it's like 39 out of 49. um chances maybe i'm off by one but it's um chances maybe i'm off by one but it's still roughly right right still roughly right right um so this is the recurrence uh and if um so this is the recurrence uh and if you sell for it then you sell for it then it's you know it's a lot more i'll leave it's you know it's a lot more i'll leave that as an exercise at home there's a that as an exercise at home there's a formula for it formula for it but um when you do something like you but um when you do something like you know and if you reduce this to 40 know and if you reduce this to 40 then you reduce this to 9 over 49 times then you reduce this to 9 over 49 times use of x use of x um plus one and you know and this is um plus one and you know and this is clearly um this is clearly a clearly um this is clearly a convergent because you can show that convergent because you can show that this is uh this is uh clearly less than clearly less than this is clearly less than uh one half u this is clearly less than uh one half u sub x sub x plus one uh and this obviously is just plus one uh and this obviously is just maybe not obviously but but if you have maybe not obviously but but if you have uh this formula uh this formula of e of x is equal to one half of e of x is equal to one half to oops u of x is equal to one half y of to oops u of x is equal to one half y of x plus one x plus one uh that's just like the classic uh that's just like the classic conversion of um conversion of um you know dot dot dot uh is one plus one you know dot dot dot uh is one plus one half plus one fourth plus dot half plus one fourth plus dot dot right and that obviously is just you dot right and that obviously is just you know know linear slash you know uh uh well not linear slash you know uh uh well not linear sorry linear sorry it's just two right so that's what the it's just two right so that's what the convergence series is convergence series is uh so that and because this is less than uh so that and because this is less than uh the function that we're doing is less uh the function that we're doing is less than this that means that we're only than this that means that we're only going to call this going to call this uh less than two times is the expected uh less than two times is the expected value value um and you know and each of these calls um and you know and each of these calls this twice this twice so you could say it's less than four as so you could say it's less than four as an expected value uh can you minimize an expected value uh can you minimize the number of coursework the number of coursework um you can probably do some funky math um you can probably do some funky math with different bases or something like with different bases or something like that to play around with it so that that to play around with it so that maybe the number of course but uh but maybe the number of course but uh but that's all i have for this one i think that's all i have for this one i think i'm i'm confident with it so i'm okay uh let me confident with it so i'm okay uh let me know what you think let me know if you know what you think let me know if you optimized it or did it a different way optimized it or did it a different way because i assumed i because i assumed i think there quite a couple of ways to do think there quite a couple of ways to do this so let me know what you think this so let me know what you think let me know how you celebrate hit the let me know how you celebrate hit the like button to subscribe on drum and like button to subscribe on drum and discord and i'll see y'all tomorrow bye | 2024-03-22 15:16:43 | 470 | 470. Implement Rand10() Using Rand7() - Day 28/31 Leetcode August Challenge |
|
73VqBxfGlmE | ne them big this time and welcome back to new video in this video before going to solve new video in this video before going to solve six second problem only code and six second problem only code and visiting squad unique parts software will visiting squad unique parts software will give and grade of clan hair in this give and grade of clan hair in this case which has great of three 2279 teen rose seven case which has great of three 2279 teen rose seven columns no columns no columns no in which 1000 that is laptop portion of the great and will have to furnish etc subscribe bottom part of the hero 10 whole grade only option hate here and there right side and off the side of the great Can Take To Do Subscribe Possible All Possible And So On 500 Or Hafta The Same Kind Of 3570 This Point To The Worst Position And This Point To Be Our Position Subscribe Programming Problem Solve Every Possible Parts And Password To Start With What Is This What Is Point Possible Way Should Point Possible Way Should Point Possible Way Should Start From A Number Of Way To Go To Is Start From A Number Of Way To Go To Is Just Like Subscribe And Possible To Reach The Well Simran Liye What Are The Possible Ways To Reach At The Next Point Which Never Ignore This Way The The The position which like and share and to go to all the like subscribe and share and hear water the best tourist this point sauvir will have two option will come from upward from left side and Top and from left from from from from from from from record record quick end oneplus 5 hair record 6 and quick end oneplus 5 hair record 6 and hair oneplus 6t quote 7 if you want to reach at its hair oneplus 6t quote 7 if you want to reach at its particular position it is 512 possible final final 700 plus possible final final 700 plus 7v quote 28 sudhir 7v quote 28 sudhir 7v quote 28 sudhir From This 020 Leftmost Position Of Great Thursday Subscribe Values Subscribe To Our Thursday Subscribe Values Subscribe To Our YouTube Channel Subscribe To The YouTube Channel Subscribe To The Software Which Has Given Benefit Which Software Which Has Given Benefit Which Is The Number Of Crops And Columns To The Is The Number Of Crops And Columns To The Worst Thing Happened Worst Thing Happened Worst Thing Happened values for grade 03 Patience to you a bill passed and which are the end columns of this will all the the the the phone I love you I love you the Simply Call Win7 Passing Accused Chords The Column0 Trolls Pale One And Similarly I Need For Column 1 Column Values Of 1808 Jaune Player I will also subscribe Row End Column One Em Lucky Warden Ek Singh VHP Snake Singh Bihar Feel Patience With All Possible 500 We Need To Arrested For Us For Peon In School And Subscribe List Play List A Foreign And Junior Executive Vijay Love And Joy Please Like This Page Don't Share Value Of Subscribe - 1898 - Switch Of The Value Of Subscribe - 1898 - Switch Of The Year Film Triple X That all dance with falling they are not meat by the way Hussain player return the value of the right bottom part which is defense position then simply return layer - 110 - 110 handed over money abroad lax long distance and css working or not So let's So let's So let's submit this and see testing accepting submit this and see testing accepting ok solid this submit and behave ok solid this submit and behave with force solution with force solution that research set for this video will have seen how they can that research set for this video will have seen how they can you white ko rural solve this problem you white ko rural solve this problem solve inch width like button and solve inch width like button and dislike subscribe The Channel for dislike subscribe The Channel for More More More | 2024-03-20 10:54:30 | 62 | 62. Unique Paths | Google's Coding Interview Problem | LeetCode |
|
8GThD5cyAgY | uh today we're gonna be working on lead code question number 37 suru suroku code question number 37 suru suroku solver solver so last time we did just uh we checked so last time we did just uh we checked for the validity of the circle and the for the validity of the circle and the last question last question this question we're gonna be solving the this question we're gonna be solving the sudoku sudoku so it's going it's gonna be done using a so it's going it's gonna be done using a back tracking back tracking uh here are the rules it's gonna go from uh here are the rules it's gonna go from one to nine one to nine and the blocks are three cross three and the blocks are three cross three and wherever there is a dot that means and wherever there is a dot that means it's an empty one which we need to fill it's an empty one which we need to fill out out and we're gonna be doing it using and we're gonna be doing it using backtracking here backtracking here uh because uh uh because uh basically we're gonna be trying all the basically we're gonna be trying all the different combinations and see if different combinations and see if it still keeps it valid or not it still keeps it valid or not and that's how we're going to be coming and that's how we're going to be coming up with the up with the solution so solution so here is a basic structure of it we're here is a basic structure of it we're going to be returned going to be returned so it's uh so it's uh initially n is going to be the length of initially n is going to be the length of the board which is the board which is going to be 9 actually going to be 9 actually and then we're going to be depth first and then we're going to be depth first search we're going to have a function search we're going to have a function definite search which we're going to be definite search which we're going to be providing the board providing the board and and the length of um you can say row or call the length of um you can say row or call and then we're gonna go through we're and then we're gonna go through we're gonna basically traverse through the gonna basically traverse through the board uh the right one is gonna go from board uh the right one is gonna go from zero to nine and then uh sorry rows are zero to nine and then uh sorry rows are gonna go from zero to nine the columns gonna go from zero to nine the columns are gonna go from zero to are gonna go from zero to nine nine so while we are traversing that and we so while we are traversing that and we find out that where we are find out that where we are it's uh the board's value is equal to a it's uh the board's value is equal to a dot dot we're gonna do something about it we're gonna do something about it what we're gonna be doing is like we're what we're gonna be doing is like we're gonna be continuing we're gonna say that gonna be continuing we're gonna say that okay okay uh this is uh this is good we're gonna oh sorry good we're gonna oh sorry if it is not equal to dot we're gonna if it is not equal to dot we're gonna say that okay continue we don't wanna say that okay continue we don't wanna worry about anything like that that is the case but if it is a dot if there is an empty if this is this is the place where we need to fill uh fill up what we're gonna be doing the possible solutions can go from one to nine so so what we're going to be doing is like what we're going to be doing is like we're going to take the i character we're going to take the i character which is basically what which is basically what it's a it's a it's an integer converted to a string it's an integer converted to a string and its value can be from one to nine and its value can be from one to nine we're gonna take that i character we're we're gonna take that i character we're gonna check we're gonna before each even gonna check we're gonna before each even putting it in we're gonna we're gonna putting it in we're gonna we're gonna validate it sorry validated we're gonna validate it sorry validated we're gonna send the board send the board the row the row like the like the the which row we are the which row we are in in which column we are which column we are we have right now we have right now n which is basically nine in in in this n which is basically nine in in in this case and i character which is the you case and i character which is the you know the character we want to try out know the character we want to try out if there is a valid if there is a valid that like after putting that in that like after putting that in if it still stays valid we cannot put if it still stays valid we cannot put the i character the i character at that place at that place and after that we're gonna undo uh and after that we're gonna undo uh we're gonna call back the dfs with the we're gonna call back the dfs with the board with the new board with that ver board with the new board with that ver edit value edit value and the n and the n and if we receive and if we receive um and after this and after this like like after checking all the the nine values what we're gonna be doing here is like we're gonna say that that is so basically in in back backtracking once we are done testing with these values we're going to move it back to if none of them work we need to need to move it back to a dot and return false now the last thing we need to actually before that uh after uh coming out of these two traversal loops we're gonna be returning the last thing we need to do is to the last thing we need to do is to program this is valid program this is valid function function so the is valid function going to take the board um the row the current row the current column uh n which is the total num like the total number of rows the total number of columns which is nine and the i character which is an integer from one to nine converted to a character so we're gonna try that out so so for that what we're gonna be doing is like first of all we're going to be doing the block row which is r divided by 3 and after taking the floor of that multiplied by 3. similarly the column the block column like which block we want to check for is again c divided by three taking the floor of that and then again multiplying it by three now we're gonna traverse through like the i is gonna be going from 0 to and then we want to check that the row we want to check few things here first of all we want to check that yeah we are checking that whether if in yeah we are checking that whether if in in three different cases if in three different cases if uh the value of that i character if it uh the value of that i character if it is already equal to i character which we is already equal to i character which we want to put in want to put in uh that means it's a it's a false we uh that means it's a it's a false we shouldn't be able to do that so yeah shouldn't be able to do that so yeah there's a mistake here though we're there's a mistake here though we're gonna check at the earth gonna check at the earth row and the eighth column row and the eighth column i throw and the c column i throw and the c column yeah we basically want to check in these yeah we basically want to check in these two things two things we need to return if that we need to return if that if we have that then we're gonna say that the current row is equal to the block row because we also want to check uh uh in that block do we have that value in that block right so we have to have like a three cross three block which we want to try out so the current row is gonna be equal to the block row plus the math dot floor of i divided by three is going to be equal to the block column of i divided by 3 of i divided by 3 oh actually this is this time it's going oh actually this is this time it's going to be equal to to be equal to the modulus of 3 the modulus of 3 so once we have the once we have so once we have the once we have calculated the block so we have to calculated the block so we have to we have to make sure that we have to make sure that that that if the if the board of that current row and the board of that current row and the current column becomes equal to i current column becomes equal to i character character that means we're going to be returning that means we're going to be returning the false so initially we were just the false so initially we were just checking the rows and the columns now we checking the rows and the columns now we are checking on the whole blocks are checking on the whole blocks if we come out of that for loop that if we come out of that for loop that means we are good to return the true means we are good to return the true that that after putting it after putting it putting on the i character at this putting on the i character at this current row and column current row and column we we this is gonna still be a valid this is gonna still be a valid uh uh invalid sudoku so that is it we implemented the is valid which actually gives us that whether it's going to be valid after putting the value in and then we have the default search when it passed let's see if it how it does for the other test yeah on the test pass passed | 2024-03-20 09:01:31 | 37 | Leetcode Question 37 "Sudoku Solver" in Javascript |
|
A8nPlIknSHw | um hello so today we are going to do um this problem this problem non-decreasing array non-decreasing array uh basically what the problem says is we uh basically what the problem says is we get an array of numbers with n integers get an array of numbers with n integers and what we want is to check if and what we want is to check if this array can become non-decreasing this array can become non-decreasing which means basically increasing which means basically increasing um by modifying at most one element so um by modifying at most one element so we take that away we can modify at most we take that away we can modify at most one element one element and we want to see if we can make it not and we want to see if we can make it not decreasing or not decreasing or not by just modifying by just modifying zero or one element at most zero or one element at most um and not decreasing of course it's the um and not decreasing of course it's the previous element is smaller or equal previous element is smaller or equal than the next element than the next element um and that's pretty much it so if you um and that's pretty much it so if you take a look at this example four two take a look at this example four two three three um we could just change form here um we could just change form here maybe make it one and that would make it maybe make it one and that would make it increasing right increasing right make it make it increasing which is not decreasing um increasing which is not decreasing um here we can't right um here we can't right um we have to modify maybe two elements we have to modify maybe two elements maybe we have to do here put here one maybe we have to do here put here one and then put here three to make it and then put here three to make it non-decreasing right non-decreasing right um so here we can do it with just one um so here we can do it with just one element element um and yeah these are the bonds so um and yeah these are the bonds so that's pretty much the idea now let's that's pretty much the idea now let's see how we can solve it so one idea here uh we'll take these two examples and use but the one main idea here is that if you have a number at the previous position right bigger than the number at position i then it's always more optimal to replace with the smaller value because uh let's say this is i right and this is i minus one and we find that this is bigger position i is bigger it's always more optimal to place i minus one with the value at position i right and make that the modification because then um numbers we will find here if if if this array will return true a numbers we'll find here will be always bigger so it's more optimal to replace with the smaller value and so here we'll place we can just take um the number at position i minus 1 and replace it with the number at position i and count this as a modification so if we have a counter for the number of modifications since we are allowed only at most one uh we count it here okay however there is one case where this is not not not working properly for this example it works because we find that okay four is bigger than two and so we replace four with with two right and so now we end up with two two three which is and decreasing so this works out however with this array it doesn't work out quite well because okay so uh we if we are this is smaller so it's good so we move to i being at position two here and so we find that it's um it's smaller right and this i minus one and so we do what we did here which is replace and so what do we end up with we end up with two here but then the problem is i minus 2 is also smaller so if we do the same thing as well then 2 is also smaller than i minus 2 if we do 2 here as well then we did two modifications right so the count here is two and do our load only at most once so this is not the optimal solution actually we can do um we can solve it differently what we can do instead is for this three four two six we can instead replace the two with four so replace the element at position i with the element at position i minus one and so with that we'd have here 4 and we'd end up with an array that has 3 4 4 6 so it's sorted here and so the the conclusion here is that we can do only two modifications either place the element at position i minus one with the element at position i or replace the element at position i with the element at position i minus one and how do we decide it's just by comparing if the element at i minus 2 is already smaller than the element at position i then we will get a sorted array because we'll have the smaller number at i minus 2 the same number at i minus one and i uh the position i and then the rest hopefully it's sorted um but we'll check and if count is exceeds one then we'll return false um and then for the second case where we need to place the element at position i we just need to check if i minus 1 minus 2 both i minus 1 and i minus 2 are bigger than i then we need to just replace the number at position i with the element at position i minus 1 and that way we'll get a non-decreasing sequence there right and so here in this case basically if in addition to this we have a number at position i minus 2 is bigger than the number at position i then what we want to do is replace the l limit at position i with position i minus 2 right and so this is what we need to do here okay um okay so that's pretty much it for this idea now let's cut it up and make sure it passes our test cases um okay so let's solve it with this with the solution here so uh and we'll go through from one to end and we'll go through from one to end because we'll check the number at because we'll check the number at position i minus 1 and so we need to be position i minus 1 and so we need to be to start from one to start from one and here we need a to initialize our and here we need a to initialize our count count and also we need to have n which is and also we need to have n which is equal to the number of elements equal to the number of elements okay okay um and then what we need to do is just um and then what we need to do is just do the check so if do the check so if um numbers position i minus 1 is bigger um numbers position i minus 1 is bigger than the number of position i than the number of position i then what we want to do here then what we want to do here is is of course increment the count because we of course increment the count because we found found a correction or a modification that we a correction or a modification that we need to do need to do but before finishing there we need to but before finishing there we need to check i minus 2. check i minus 2. if it's bigger than at position i then what work to do here is replace the number of position i so so that we replace this element with i minus 1 instead of modifying both are minus two and i minus one which will give us count of two instead of one and so here we'll just replace with i minus one otherwise it means this is already smaller than the number of position i so we can just replace i minus 1 with the number at position i i since it was bigger what a place it becomes smaller it becomes non-decreasing and now after each increment if we increment count each time we check if the inc we incremented and we exceeded one because that means we need to modify more than one element and so that means we need to return false because we can't make it non-decreasing with just one element with just one change right um and then at the end we can just return if the account is still smaller or equal to one which is at most one element um and that's pretty much it so also on um looks like no we got um looks like no we got uh false in the first uh false in the first in the first in the first test case test case um and the problem is here so python if um and the problem is here so python if you do you do um oh sorry python if you do a number at um oh sorry python if you do a number at position if you do something like this position if you do something like this minus one then it counts right and we minus one then it counts right and we don't don't and that's what is happening here we so and that's what is happening here we so with if i equal to one then we'll get with if i equal to one then we'll get minus one so we'll get minus one so we'll get minus one at the end which is actually minus one at the end which is actually um um the the last element in the array and so this last element in the array and so this check here check here we need to check also that this is valid we need to check also that this is valid right right that is a valid index that is a valid index um um and that's pretty much that should work and that's pretty much that should work source front again okay so that seems to pass there let's and their classes test cases um yeah so and their classes test cases um yeah so that's pretty much it um you can solve that's pretty much it um you can solve it a couple of other different ways but it a couple of other different ways but i find this to be the most i find this to be the most straightforward solution um yeah so straightforward solution um yeah so thanks for watching and see you at the thanks for watching and see you at the next one bye | 2024-03-20 15:43:31 | 665 | Leetcode 665. Non-decreasing Array |
|
eFznyui3iGM | So hello friends today I have given 48 and my name is Keshav you are watching take it world is Keshav you are watching take it world search second actually this is a hard problem search second actually this is a hard problem why is it hard actually no problem is why is it hard actually no problem is hard it just has hard it just has more parts so if we divide it part by part more parts so if we divide it part by part more parts so if we divide it part by part understand the parts then it becomes easy then why is there a reason for it being here because look at which number 20 we saw this look at the 23rd day which is our cup's gone then If If If Rakhi has been made, then Rakhi has been made, then I had told in the word search, okay, then I had told in the word search, okay, then you will say that it is okay, I told you on 23rd, you will say that it is okay, I told you on 23rd, but why have you taken it so far, that is, after giving 24th, you can do it, but it is being implemented in it If it If it If it can be optimized then it was necessary to understand for whom can be optimized then it was necessary to understand for whom word search has been made, then look at the word search has been made, then look at the question, this is the question, first question, this is the question, first you will remember what happened in word search, if you will remember what happened in word search, if not then please watch further, please please give me the not then please watch further, please please give me the video. video. video. tree date, I think, now I had also shown which one was 46, and the other one was 23. I had seen the one with word search, so what is there in it, what do we do by searching the word, It's It's It's okay, return true, return two characters, okay, return true, return two characters, return false. Now the matter has progressed a little, the return false. Now the matter has progressed a little, the matter will not end in true and false. matter will not end in true and false. Now we have a lot of words in the input, whatever is there Now we have a lot of words in the input, whatever is there inside the board, we have given the inside the board, we have given the word key. word key. word key. now I have to find out the list of this board inside this board and here I have to find out if anyone from these worlds can see me, then whoever And it is visible And it is visible And it is visible as you can see that here they have as you can see that here they have highlighted it, I am seeing highlighted it, I am seeing this is the output that we want, so what do we do, this is the output that we want, so what do we do, whenever we search, we do dfsbfs, what do we do, each particular group of us. What is done in force technique is to go and see each and every value, what is the point of doing this, there are four directions, top and bottom, and look from above, there are some constraints too. If you read carefully, then he has told. That it will be between A and S only and should not go out of bounds, keep in mind that there is nothing else left, you will sit up and down and on top of that there is a cross of M and also So the So the So the process of all those things will slow us down a lot. process of all those things will slow us down a lot. Time complexity increases, so to Time complexity increases, so to avoid this, we have avoid this, we have try, we try, we do prefix tree, so do prefix tree, so I will tell you about it in the notebook, right? I will tell you about it in the notebook, right? I will tell you about it in the notebook, right? let's move on to that and I will say again that you should check the prefix tree once because we are going to write its code here, then you will say, have you understood, why not, then we have explained it there, okay, so let's make It is It is It is like this has been given to us and like a word search van, like this has been given to us and like a word search van, I take it in a particular word, I take it in a particular word, like in the beginning, I have to like in the beginning, I have to find the other word, a list of such words is being made, find the other word, a list of such words is being made, so what will I do here, each so what will I do here, each one? one? one? talk about root force approach, then I will check by going to each value and going further like O came A came A came ok, meaning from O we get only two directions, one to Actually, there are Actually, there are Actually, there are four ways to go down, forward and backward, right, but it will be out four ways to go down, forward and backward, right, but it will be out of bounds, right here and here, you of bounds, right here and here, you can go here only and you can go here only, can go here only and you can go here only, so we checked this possibility also, so we checked this possibility also, then did this one also, so O A then did this one also, so O A then did this one also, so O A t and then we have found it, so I have found it from the list of many words from the world list, we have found our particular word which can be formed, we have it through word search, A good case is A good case is A good case is done, but if we do not want to find whether a done, but if we do not want to find whether a particular word is there or not, then I will have to reduce each one by going to particular word is there or not, then I will have to reduce each one by going to each particular each particular value, going forward, backward, right and left. Otherwise, value, going forward, backward, right and left. Otherwise, when you remember, when you remember, I have written the world I have written the world I have written the world what was there to do in it, we were reducing it like this, there are four directions, but tell me once, you have given me so many words and I tell me anything, okay, the list will not go on such words. We mean, start from where you can go. Well, it's lucky that O was there, so it was there in the beginning. Now let's talk about P. P is not there. TV is a good example. Look, it is not there, so why We have made a fixed tree by We have made a fixed tree by We have made a fixed tree by taking a small example, it will become bigger, is taking a small example, it will become bigger, is n't it? I take four at random, I have kept a list of words from late, I will do it from here, so if I make a prefix tree, I make a prefix tree. I know what all I have I know what all I have given here, it is true that given here, it is true that I have given it, I know that if there are more, they will come from here, for the I have given it, I know that if there are more, they will come from here, for the time being in this case, it is time being in this case, it is given by O, then where are we? given by O, then where are we? given by O, then where are we? n't it? From A, we have two values. One n't it? From A, we have two values. One A comes, so we go to this A, so the A comes, so we go to this A, so the value comes 80, one A comes, so value comes 80, one A comes, so we go to this A also we go to this A also and from here. and from here. and from here. also A here. Look, OK, the point is, A is followed by T, so by doing this, our prefix becomes 'Tu'. Okay, this thing is clear, Man lo, it let's say it is being formed, so there was nothing below it, it means that the word ends here, so it is present in our world, so the There will be talking about There will be talking about There will be talking about OK, after I, after TPT, OK, after I, after TPT, A was to come, so here there is nothing below A, A was to come, so here there is nothing below A, but we got this, so we also but we got this, so we also got the word named Oye, whatever it got the word named Oye, whatever it is, it is Ot, isn't it? is, it is Ot, isn't it? is, it is Ot, isn't it? using prefix will also work, okay, there are going to be a lot of previous concepts, friends, I am here again and friends, I am here again and look at this, the code has already been written because it is look at this, the code has already been written because it is very big, isn't it? very big, isn't it? very big, isn't it? reason is that we have implemented Try Note here, so much so that you can imagine how well it is being implemented in the solution, you must be seeing Can you Can you Can you see what a family there is? Firstly, see what a family there is? Firstly, we created children inside the class tree road. we created children inside the class tree road. What does a child do? I What does a child do? I told you that if the value is a foot, then it will told you that if the value is a foot, then it will be our character and what will be the value of be our character and what will be the value of its child, the value of the tree note. its child, the value of the tree note. Whether or not the tri note will be created, it will have Whether or not the tri note will be created, it will have that value of the child and whether it is the end of the that value of the child and whether it is the end of the world or not. Like we just world or not. Like we just saw the example of Oath, it had teeth in the last and there was end of saw the example of Oath, it had teeth in the last and there was end of word, so for now we have kept false for that also, we will word, so for now we have kept false for that also, we will counter it in future. counter it in future. counter it in future. counter. Why, if I tell you further, what will we do? We will add a word and remove a word. We will have to see both the conditions. We are increasing the counter to add a word and decreasing the counter to remove a word. Okay, and the four C's in Word are the same concept that I told you in Word, which we had read about Edward etc. earlier, it is the same that if we do not have an account in the current children, then we will add it to the The The The end of the world will come true in the end, it will go end of the world will come true in the end, it will go meaning the whole world, we have seen it, meaning the whole world, we have seen it, we are removing it from the concept, the current we are removing it from the concept, the current counter will be decreasing and the counter will be counter will be decreasing and the counter will be increasing, meaning it will be moving forward, increasing, meaning it will be moving forward, what have we done inside the solution, find the word. what have we done inside the solution, find the word. Inside, I also took the board, it Inside, I also took the board, it is the same as before, I left the rest of the words as words, is the same as before, I left the rest of the words as words, no problem and took the root of the tree note no problem and took the root of the tree note for in the world Sam, what are you doing to each word, adding the for in the world Sam, what are you doing to each word, adding the initial and row initial and row columns. columns. columns. zero date is for this column, so if you are reading it before then we have taken answer and VS, it is ok for visit set, both of these are set, what should be the answer, do you know Is there any word that is being repeated? To Is there any word that is being repeated? To Is there any word that is being repeated? To avoid this thing, we have avoid this thing, we have set the answer also. Visit must happen set the answer also. Visit must happen further because look, I am writing to you, that to further because look, I am writing to you, that to me is the excite code with prefix tree me is the excite code with prefix tree written above and written above and written above and written here that we do only this, I have taken the unload and the world separately, why have I taken the road because it is already visited to see which all have been visited? Because how much of the word has been made by us till now, no word and how much have I taken, how much have I made, so are you equal, you cry or are you greater, give equal, whatever you have to do, and meaning, the role should not be exceeded, it should not If it doesn't happen, If it doesn't happen, If it doesn't happen, give it smaller or if it doesn't happen, it means we have to check auto bound give it smaller or if it doesn't happen, it means we have to check auto bound and if R and C are in our visit set and if R and C are in our visit set then it is a matter of problem, no, this is a matter of problem then it is a matter of problem, no, this is a matter of problem and if it is a matter of problem, then return it as and if it is a matter of problem, then return it as base case, right? base case, right? base case, right? here brother, its meaning cannot be reduced and similarly, if it is not in the board and not in the children, then what is the use of the board, the word is not there in the board and there is an Android children counter, It's okay to keep It's okay to keep It's okay to keep our counter. Decreasing the time limit does our counter. Decreasing the time limit does not mean that we get a seed. The not mean that we get a seed. The counter is running, so it is guiding us. If we counter is running, so it is guiding us. If we put it to check, what will we do? put it to check, what will we do? Like before, what will we do? Like before, what will we do? Like before, what will we do? adding it from the visit, adding it and adding R and C, making it a tuple and removing it from the visit, less is going on in between, how many times did we have to call four times, so I Right, left, Right, left, Right, left, plus one, minus one, we will plus one, minus one, we will do it from the row, then we will do plus one minus one from the column, do it from the row, then we will do plus one minus one from the column, along with N and W, note and word, along with N and W, note and word, these four parameters are these four parameters are variables and we will calling the end of the world, we have got it. calling the end of the world, we have got it. And add it to the answer and also remove it, we will score two runs and when we go to remove it means we have removed it from the visit set, now the court will run in our place, we take R and C separately, right? For the column DFS, initially we will give RC root team and along with it we will give an empty word because the word that is our increase is going to increase, here is the word plus equal, here is the word plus equal, we have initially put empty, we will increase it, our To make the string, finally the list which was created by our set will be returned. The list of our answers will be returned. By the way, I have already run it, I will do it again for you just for sure. Okay, so give it in the description. give it in the description. give it in the description. play list of Blind 75 etc. Questions etc. Go to the description and hit check. You will get it in the next video. My name is Keshav. You are watching. If you have any doubt then what should you do once. If you have any doubt then just once. Watch the video again, understand what is not said above, what is said because if we keep typing each and every thing, then a video of 20 minutes to 40 minutes will be made, so understand a little bit, Everything is Everything is Everything is fine in every step, let's go | 2024-03-22 10:32:02 | 212 | Leetcode 212. Word Search II. Python (TrieNode/Prefix Tree) |
|
ewww8VWF-rE | hi everyone once again welcome to my channel today in this video we are channel today in this video we are solving another problem from lit code solving another problem from lit code top and derby question list and the top and derby question list and the problem is permutations so if you see problem is permutations so if you see this problem like and dislike ratio you this problem like and dislike ratio you can get automatically how much important can get automatically how much important is this problem so is this problem so and this problem is get asked in all and this problem is get asked in all type of companies so this problem is type of companies so this problem is very important to solve if you are very important to solve if you are practicing for the upcoming your practicing for the upcoming your interviews so the problem is like we are interviews so the problem is like we are given input integer array with all given input integer array with all integers is distinct and we need to integers is distinct and we need to return all possible permutation and we return all possible permutation and we can return the permutation in any order can return the permutation in any order that does not matter so for example one that does not matter so for example one we are given input array nums which has we are given input array nums which has three integer one two three and we need three integer one two three and we need to return all possible permutation of to return all possible permutation of this so if we have n number then we will this so if we have n number then we will have n factorial permutation for three have n factorial permutation for three we will have three factorial permutation we will have three factorial permutation that is six so we will have six that is six so we will have six different permutation and we are different permutation and we are returning in the output so how to solve returning in the output so how to solve this kind of problems so this kind of this kind of problems so this kind of problem can be solved easily by the problem can be solved easily by the trying to formulate recursive solutions trying to formulate recursive solutions and that netting what called the and that netting what called the backtracking algorithm so let's start backtracking algorithm so let's start implement implement like understanding it so initially we like understanding it so initially we are given like one two three so this is are given like one two three so this is our input array so what we need to do we our input array so what we need to do we need to first fill the first place of need to first fill the first place of our uh our uh result like permutation so if i draw it result like permutation so if i draw it so the first place can be filled with so the first place can be filled with the three possible numbers so we can the three possible numbers so we can have three possible first place numbers have three possible first place numbers candidate and we will draw three candidate and we will draw three branches from this so first we can fill branches from this so first we can fill one then two then three and the rest one then two then three and the rest let's keep it is as it is so if we let's keep it is as it is so if we keeping one and two three like as it is keeping one and two three like as it is we are swiping with two so this is one we are swiping with two so this is one and three and similarly this will be two and three and similarly this will be two and three so that just we are swapping and three so that just we are swapping with this 0th place so we will also get with this 0th place so we will also get by index initialize from 0 at this place by index initialize from 0 at this place the index is 0 and we are filled with 0. the index is 0 and we are filled with 0. so after that when we are calling next so after that when we are calling next the permutation call our index at each the permutation call our index at each level this will become 1 one over here level this will become 1 one over here one over here one over here now we will try to fill the second place now we will try to fill the second place for this call so for this call for for this call so for this call for filling second place we can fill like filling second place we can fill like one is already filled so now we have one is already filled so now we have again two option two or three so first again two option two or three so first we can fill two then three is as it is we can fill two then three is as it is similarly we can fill one is already similarly we can fill one is already filled three then two so this is now filled three then two so this is now over here two second place is filled over here two second place is filled again from here we can do again two one again from here we can do again two one and three and three and another we can do this is and another we can do this is two two is already then three and one similarly from here we given then finally we need to fill the third place index over here will become two at each all this is like index in the level so level of our tree so we are kind of now when we fill three we have only one option so we will keep one two three as it is so this is our one permutation and at this place our index becomes three so when our index becomes equals to number of elements so initially number of element of in our array is and which is three so once it becomes that means this is a valid pair of permutation and that we can store in our result so we can also declare a result and once our index equals to the n then and once our index equals to the n then we will fill that into the ah list of we will fill that into the ah list of list of integers list of integers so that is the idea behind it so that is the idea behind it and from here also we will get one pair and from here also we will get one pair then one pair then one pair so from then one pair then one pair so from total we are terminating this approach total we are terminating this approach in these six places so in these six places so that is the idea now how to implement in that is the idea now how to implement in code so for implementing this code i code so for implementing this code i have already given some idea but let us have already given some idea but let us see what we can do we will initialize see what we can do we will initialize this in the our we will write a this in the our we will write a backtrack backtrack helper method here we will have a list of list that will hold our result first as a reference we will pass from kali method also we will pass an index that we will initialize from 0 from the calling method as well as we will pass our nums this is nums original the input array so once we got and the base condition here we will check if our index if this is the case that means we found if this is the case that means we found the permutation so we will do some the permutation so we will do some processing and processing and store the permutation into the result store the permutation into the result obviously so here we need to fill the obviously so here we need to fill the list list as a list so we will first convert this as a list so we will first convert this current array and store into the list current array and store into the list now now what we need to do what we need to do we will run like for we will run like for starting from int i for in i starting starting from int i for in i starting from index current index we will go from index current index we will go until the length of our array so nums until the length of our array so nums dot length dot length and we will and we will first call the backtrack method so first call the backtrack method so before that before that we will fill the place so we are storing we will fill the place so we are storing in the so here we are in the so here we are uh keeping this in the integer variable uh keeping this in the integer variable so this is our input original array nums so this is our input original array nums and initially let us say we are 1 2 and initially let us say we are 1 2 something 3 so at this place we will something 3 so at this place we will swap with this place so whatever place swap with this place so whatever place the value of our initial index so we the value of our initial index so we will swap at place like index at place like index and the current i and the current i once this done we will call again the once this done we will call again the method backtrack with the new method backtrack with the new index so the index plus one and after that once we done we will backtrack because we need to try other possible case once we done with either we found the solution or not we will backtrack again so we will swap it back the index and the i same place because initially first we swap we put at the index integer into the ith index and then we are swiping back so that we will try other possible cases so this is the code idea now you can try to pause the video and implement the code by yourself so here is the code i have already implemented so this is the code as i initially this is our main method where we are declaring a result list of list as a output and we are calling the permuta so that is nothing but the backtrack method and here we are passing this an index from initializing from 0 now we are checking if index is nums dot length we are creating a list uh from the array and this is box we are using as we are converting primitive data type into the reference object integral object and then we are restoring into the creating a copy list and then we are storing back into the list of list this in our result variable otherwise we are iterating from index to the length of our array and first swap that index i element with the index element and then backtrack it here so this is the step where we are backtracking back track it back now what is the so before that let us try to run the code so this code will run as it is already i have tested so it is working as it is so let me show you this so let me show you this these submissions so it got accepted so these submissions so it got accepted so it's like running 5 millisecond as i am it's like running 5 millisecond as i am using the streams so if you use normal using the streams so if you use normal convert the normally this array that convert the normally this array that will improve your runtime as i don't will improve your runtime as i don't know like in using a stream will take know like in using a stream will take more time in lit code compiler so just more time in lit code compiler so just we you can also do this we you can also do this like with the very basic approach so like with the very basic approach so into num in nums into num in nums and store this into the copyless and store this into the copyless copyless start add the num copyless start add the num once is done we will store lets submit once is done we will store lets submit give a submit again for this so this give a submit again for this so this will be faster than the previous one will be faster than the previous one so this is like you can see 100 percent so this is like you can see 100 percent faster than all the java solution now faster than all the java solution now what is the what is the ah what is the like time space complexity of this solution time and space complexity so as we saw in the tree in our this permutation tree so we will have total and factorial permutation and for each we are this we are copying from here in arrays to the the list so that will be n times so this the time complexity of this solution will become so the time complexity is o of n into n factorial and the space complexity is so space complexity is off and factorial so that's it so you can also try other backtracking problem which i have already published the video solution on my channel and you can find in the all the important top interview question in the top interview playlist so that's it if you like the solution hit the like button and subscribe to my channel | 2024-03-20 09:32:14 | 46 | Permutations | LeetCode 46 | TopInterview | Google Facebook | Backtracking |
|
uJxpLJiJaK0 | hey hey everybody this is Larry this is me doing attempting day 17 of the legal me doing attempting day 17 of the legal daily challenge hit the like button hit daily challenge hit the like button hit the Subscribe button drop me on Discord the Subscribe button drop me on Discord let me know what you think about today's let me know what you think about today's problem today's problem is going to be 8 problem today's problem is going to be 8 47. uh shortest path visiting or notes 47. uh shortest path visiting or notes this seems like a short platform is the this seems like a short platform is the name let's let's take a look uh you give name let's let's take a look uh you give an undirected connected graph of an undirected connected graph of endnotes label from zero two and minus endnotes label from zero two and minus one you're given in a way graph where one you're given in a way graph where graph survives a list of all nodes graph survives a list of all nodes connecting connected with node I by an connecting connected with node I by an edge we turn the link with the shortest edge we turn the link with the shortest path that visit every note oh okay that path that visit every note oh okay that is actually not the path that oh not the is actually not the path that oh not the problem you may start and stop it and problem you may start and stop it and you know you may revisit notes multiple you know you may revisit notes multiple time and you may reuse edges okay time and you may reuse edges okay so you have a graph uh I thought it'd be so you have a graph uh I thought it'd be a little bit maybe interesting but n is a little bit maybe interesting but n is going to be equal to 12 and N is equal going to be equal to 12 and N is equal to 12 means that they're probably some to 12 means that they're probably some like like you know 12 factorials a little bit too you know 12 factorials a little bit too slow but n times two to the N which is slow but n times two to the N which is 12 times 2 to the 12 will be fast enough 12 times 2 to the 12 will be fast enough so something like that some sort of bid so something like that some sort of bid Mass dynamic programming is where the Mass dynamic programming is where the hints at I actually thought that there hints at I actually thought that there may be a better thing for it may be a better thing for it oh wait did I misunderstood oh it's oh wait did I misunderstood oh it's listening oh no so this is okay well I I listening oh no so this is okay well I I think I misread this due to this problem think I misread this due to this problem or this thing or this thing um I think you have to raise it every um I think you have to raise it every Edge in that case it'll be some sort of Edge in that case it'll be some sort of oily and path or Lillian psycho or oily and path or Lillian psycho or something like this and don't the thing something like this and don't the thing with that one is with that one is you know it is polynomial right you know it is polynomial right um but and I guess we did something um but and I guess we did something similar recently but if it was it all similar recently but if it was it all notes then it's a little bit different notes then it's a little bit different because um because now basically this is uh uh uh depending how the problem is structured uh it's either you know tsp travel salesperson or hempath hamiltonian path hamiltonian psycho well that doesn't have to be in cycle in this case but yeah something like that but and you know uh the common part about all those things and I just misread it a little bit is that they're all NP plus right I say NP plus just because I'm a little bit lazy I I always forget where hempath is in um NP or MP complete uh for me it doesn't really matter uh or whether um um yeah I always forget whether it's an MP yeah I always forget whether it's an MP computer or whatever but I mean it's computer or whatever but I mean it's exponential I think is the point that exponential I think is the point that I'm trying to make which of course is I'm trying to make which of course is going to be hard enough and what that going to be hard enough and what that means is that uh there are two things means is that uh there are two things right in general for NP problems uh one right in general for NP problems uh one is is uh you know once you the the uh you know once you the the ability to recognize the MP problem is ability to recognize the MP problem is that you stop looking for well a that you stop looking for well a polynomial solution right uh or if you polynomial solution right uh or if you do then maybe you'll be world famous or do then maybe you'll be world famous or uh you know maybe there's some uh you know maybe there's some constraints that you can exploit that constraints that you can exploit that makes it not MP maybe there's like a um makes it not MP maybe there's like a um you know like one random rule in in the you know like one random rule in in the problem that is like oh it's this but problem that is like oh it's this but you can do this one thing and then like you can do this one thing and then like okay well this one thing changes okay well this one thing changes everything it's not an NP anymore right everything it's not an NP anymore right uh and yeah and then in real life what uh and yeah and then in real life what you would end up actually doing is uh you would end up actually doing is uh kind of well the couple of things a lot kind of well the couple of things a lot of things you can do but I think the of things you can do but I think the couple things that are off my head one couple things that are off my head one is just looking for an approximation is just looking for an approximation algorithm so in that case you know algorithm so in that case you know you'll try to find an algorithm that uh you'll try to find an algorithm that uh you can maybe prove is within certain you can maybe prove is within certain percentage of the optimal uh especially percentage of the optimal uh especially in this particular mtsp like there's a in this particular mtsp like there's a such a thing of course such a thing of course um or you may you know look at the the you know like like try to figure out their additional constraints or looking for properties within a certain input that you can exploit right like maybe maybe for whatever reason like you realize that 80 of your input is by by parti or something like this right I don't know and then in that case you can solve 80 of your things like your real life data set may be useful or maybe you notice that the graph is plainer or something like this right some sort of property that you can play around with and kind of uh you know make a special case for and maybe you can solve them in a piecewise me or something like this in any case that's a lot of of talk but yeah knowing that this is an MP means that we don't really try to find something better than that uh NP uh of course in this case you can do dynamic programming and given that two to the N or n times two to the N where n is 12 is fast enough we can kind of just get started and of course is such a fancy word if you haven't done is such a fancy word if you haven't done been masked before uh I'll do I'll do a been masked before uh I'll do I'll do a great brief intro but great brief intro but I I think it's very intimate it can be I I think it's very intimate it can be intimidating to say and see all these intimidating to say and see all these like funky symbols for the first time like funky symbols for the first time but it's not that bad I promise you uh but it's not that bad I promise you uh okay you know it's understandable I I okay you know it's understandable I I believe in you uh but yeah believe in you uh but yeah um um um so let's say we want to write a Brute um so let's say we want to write a Brute Force right how would we kind of write Force right how would we kind of write this so the way that I would just write this so the way that I would just write it is like the 12 factorial way where I it is like the 12 factorial way where I go from zero then one then zero two like go from zero then one then zero two like you know just all the permutations right you know just all the permutations right so yeah so maybe we can do something so yeah so maybe we can do something like uh what are we supposed to return like uh what are we supposed to return the length of the shortest path okay the length of the shortest path okay um a couple of ways you can do it but I think like for start in range of n uh uh you know maybe best as you go to some Infinity right so best is you're gonna men a best and then calculate from the start and then uh and maybe you know we were writing uh and maybe you know we were writing before us maybe we have a scene thing uh before us maybe we have a scene thing uh where you know scene as you go to force where you know scene as you go to force times n or something like this right uh times n or something like this right uh I'm gonna write it to Brute Force way a I'm gonna write it to Brute Force way a little bit first I mean little bit first I mean just to kind of you know you could skip just to kind of you know you could skip ahead if you already ahead if you already thank you all you know what I'm gonna do thank you all you know what I'm gonna do but you know uh uh yeah so then now um to the current node and then you have the scene away and then the idea is it should be um uh it's structured like oh what did I do record graphs of current so for yeah uh we can calculate you know same yeah uh we can calculate you know same thing expressing infinity and then we thing expressing infinity and then we turn it up turn it up we can do a calculate on WE and then we can do a calculate on WE and then scene right and then maybe like scene of scene right and then maybe like scene of v as you go to true and this is if you v as you go to true and this is if you need to go to four something like this need to go to four something like this and then press is equal to Min best uh and then press is equal to Min best uh This plus one because we took an edge or This plus one because we took an edge or something like this right so a couple of something like this right so a couple of ways you can write this as well or even ways you can write this as well or even optimize even this but that's the really optimize even this but that's the really straight core part of straight core part of um of writing it in a Brute Force kind of way right uh uh quite right because there's no base case and you can kind of go back and forth I am aware of these things but that's kind of like the most basic um way to kind of write just like a proof first like we said before this is a book first and this will never terminate just because you can go back and forth um and also we don't have a base case so base case is something like or scene is uh uh so it's actually good enough we've all seen them we return zero right meaning that we've we've visited every node then we return zero we're gonna run it will never finish I don't think oh well they'll never even start apparently but but even assuming all the syntax is correct they'll never finish right uh oh actually a little surprise we're not that surprised because uh yeah probably only but yeah it it goes it's too much of a but yeah it it goes it's too much of a recursion depth and if you let it it'll recursion depth and if you let it it'll probably even go even more uh and you'll probably even go even more uh and you'll always run out of Stack space eventually always run out of Stack space eventually uh uh uh yeah okay first thing to note uh what uh yeah okay first thing to note uh what are we doing man are we doing man uh first optimization step uh first optimization step um one one thing that we can do here is you know we we go back and forth from notes we already seen so how do we skip notes that we've seen before well if we want to skip the notes that we've seen before then we can just do do something like this right if not seen of me then we do this but this is not gonna work either because or by itself it doesn't work because like we have example one where you want the zero to go to two and then back up right you there's no path at least the way that we've written it there's no path going from one zero and then two and then three directly or it's not as given so maybe one thing that you can do and there are different ways to tackle this but the way that I'm going to tackle this this form is just write the shortest path thing right uh so yeah so so what I mean is that now I'm creating all pair shortest path there's only n oh there's only 12 or n is equal to 12 number of of notes so 12 squares n Square you know that's that's enough to do anything really so yeah so let's let's get to that but so let's just say infinity times n for to do right uh yeah and you know maybe you can do something with the base case like if I I is equal to zero something like this and then now we can also go through the list uh so for for I and range of N I guess we already have that Loop right uh for we in graph um D of IV is equal to D of v i is equal um D of IV is equal to D of v i is equal to one right I think it to one right I think it yeah it shouldn't matter whether we do yeah it shouldn't matter whether we do it I mean it's a symmetric thing right it I mean it's a symmetric thing right so that now we have the the one distance so that now we have the the one distance away thing and here I'm just gonna you away thing and here I'm just gonna you know uh there are a couple of ways you know uh there are a couple of ways you can do the all pair shortest path I'm can do the all pair shortest path I'm just going to write it with just going to write it with um um Floyd shows algorithm right Floyd shows algorithm right and dfij is gonna mean of the dfij is gonna mean of the ik DFI ik DFI okay okay I'm not gonna go over this okay okay I'm not gonna go over this point too much to be frank uh you know point too much to be frank uh you know they're different ways to do it yeah can I type uh definitely looked that up and Googled it up or whatever uh as you need so then now we can actually get this to you know be a little bit correct in that instead of you know now going from current to V and you know and now we don't have to do and you know and now we don't have to do dupes so that's good right uh maybe yeah yeah actually don't know why this is actually don't know why this is Infinity hmm uh I think they should I mean this Pro will still timeout for energy go to 12 but it should be okay for these inputs to be frank so I'm trying to think what did that there is something silly which is probably possible and yeah uh well I didn't do scene of starters to go to true so I guess that's one thing but where am I doing this I mean I know that this is infinity but dude um um did I mess something up let me clearly did I mess something up let me clearly but but okay so the the this array is fine okay so the the this array is fine well then why does this work huh well then why does this work huh [Music] [Music] I did forget this part though but hmm what is going on um this has never hit maybe misunderstood um um I'm being dumb sorry I'm being dumb sorry uh I did uh okay I made a modification uh I did uh okay I made a modification for this but that also means that this for this but that also means that this is no longer true because these are only is no longer true because these are only um um one one distance away edges so now we one one distance away edges so now we have to do something uh we have to have to do something uh we have to change this to going from zero to n all change this to going from zero to n all together okay there we go uh and yeah together okay there we go uh and yeah and like I said this is gonna be n and like I said this is gonna be n factorio uh which is fine up to like factorio uh which is fine up to like seven or eight or something like this seven or eight or something like this right maybe even I don't remember what right maybe even I don't remember what the numbers but the numbers but 12 is getting it over tight what is 12 12 is getting it over tight what is 12 factorial 12 factorial is 479 million factorial 12 factorial is 479 million actually maybe in some languages it'll actually maybe in some languages it'll fight it'll be okay maybe I don't even fight it'll be okay maybe I don't even think that's true but think that's true but right away now we have to do something right away now we have to do something called called uh well I mean and this is you know uh uh well I mean and this is you know uh uh at this point uh at this point we have to do some memorization note we have to do some memorization note that every time we you know we call this that every time we you know we call this if we give it the same input we expect if we give it the same input we expect the same output and that is basically the same output and that is basically the only condition for memoization the only condition for memoization really no side effects no uh no weird really no side effects no uh no weird things and that would allow us to do it things and that would allow us to do it so how do we memorize this well so how do we memorize this well current can go from zero to n so that current can go from zero to n so that part is easy so to n minus one scene is part is easy so to n minus one scene is just basically a brilliant away of just basically a brilliant away of you know and what and uh you know and what and uh pulling away of n values right and so pulling away of n values right and so this is where the bed mask stuff comes this is where the bed mask stuff comes in in um um you can kind of see how I did it with you can kind of see how I did it with the uh with the Boolean away but you the uh with the Boolean away but you know what is a brilliant away well but know what is a brilliant away well but in a way you could think of it as like in a way you could think of it as like just ftftm you know like force and True just ftftm you know like force and True Values and if you can't convert these Values and if you can't convert these Force Through values to zero and ones so Force Through values to zero and ones so f for zero T is f for zero T is uh one so you could kind of uh uh one so you could kind of uh you know you could convert them to you know you could convert them to Binary values and instead and now Binary values and instead and now instead of an array of instead of an array of um in a way of bits you can just um in a way of bits you can just condense them into one number condense them into one number um and that's basically a bit best right um and that's basically a bit best right every other operation will do together every other operation will do together but but uh but this is basically the logic of uh but this is basically the logic of how what it looks like and how what it looks like and and yeah and and because of this and now and yeah and and because of this and now we can think about it with NYU is how we can think about it with NYU is how many possible distinct values there are many possible distinct values there are well each one of them could be have two well each one of them could be have two values and there's n of them so it's two values and there's n of them so it's two times two times two dot dot which is times two times two dot dot which is also two to the N so also two to the N so so that means that total number of so that means that total number of inputs is O of n times two to the n um and and each input takes both end times is the way that we did it so that means that total is actually going to be total time there's going to be o of N squared times to the N so I was off by n actually whoops in Total Space though would be n times to the N but uh that's pretty much the idea but just to kind of make a little compact and you can actually at least in in pipeline you can actually use like a frozen frozen array or something like this maybe maybe I made that up but you could definitely memorize on this thing already if you really want to you have to be a little bit careful about you know a race because you want to uh memoize not the memory address which may be the thing with cash I don't know so yeah and and for this and for particular and and for this and for particular uh this for this particular video I'm uh this for this particular video I'm gonna just try something funky uh and gonna just try something funky uh and kind of just keep it the same and then kind of just keep it the same and then just change the memorization function just change the memorization function right so good current and the scene fine right so good current and the scene fine uh like hopefully this is understandable uh like hopefully this is understandable so far this is wayproof force so far this is wayproof force um you know top down kind of thing right um you know top down kind of thing right and then now we just have to basically and then now we just have to basically has uh same thing that I always do at has uh same thing that I always do at least on these videos just to kind of um least on these videos just to kind of um you know uh just could kind of visualize a little bit better um both the space and and their usage right so here now if we're seeing we return zero that's fine otherwise uh let's see what do we want to do right otherwise we have to see if if has cash right of current and scene but of course scene cannot you know seen as in a way it's not a number so we just have to convert it to a binary number right so yeah have a helper function right or have a helper function right or something like this but something like this but uh and maybe we store it I don't keep uh and maybe we store it I don't keep calling it right foreign of course we have to write the two binary function and you can write it to Binary function in a number of ways as long as you're consistent about it right so for example now we can say for me and scene um cone we we shift by one so we multiply by two or and and then we added uh if V is true then we add it by one or uh and that's pretty much it really uh and that's pretty much it really uh yeah I'm gonna give us uh I'm gonna uh yeah I'm gonna give us uh I'm gonna give some give some I mean the idea is gonna be right it's I mean the idea is gonna be right it's just like I'm worried a little bit about just like I'm worried a little bit about uh typos and such but I'll actually give uh typos and such but I'll actually give some it and very well but we could fix some it and very well but we could fix it yeah and that's pretty much it 12 65 it yeah and that's pretty much it 12 65 day streak day streak um yeah I mean um yeah I mean the timing is a little bit well but the timing is a little bit well but that's fine that's fine um yeah I think with these kind of um yeah I think with these kind of problems uh hopefully the way that I problems uh hopefully the way that I Illustrated you know uh Illustrated you know uh you know maybe another way of doing bit you know maybe another way of doing bit bit mask uh DP right to show what big bit mask uh DP right to show what big Mass DP is it doesn't have to be Mass DP is it doesn't have to be intimidating uh but yeah intimidating uh but yeah um um that's all I have for this one I think that's all I have for this one I think one I would also say is that um you know one I would also say is that um you know over the years if you have been over the years if you have been following my Channel or server or following my Channel or server or whatever and you see me do bitmashdp whatever and you see me do bitmashdp um I've kind of done it in a number of um I've kind of done it in a number of different ways and you know uh I think different ways and you know uh I think that's and I don't know I don't if it that's and I don't know I don't if it sounds like a brag you could skip it sounds like a brag you could skip it it's not really meant to be but what I it's not really meant to be but what I want to showcase is not even just like want to showcase is not even just like me bragging but or me saying that like me bragging but or me saying that like you know this is you know this is the kind of understanding that I always the kind of understanding that I always try to teach is not like memorizing code try to teach is not like memorizing code or memorizing you know big Mass DP and or memorizing you know big Mass DP and be like oh yeah it's been Mass DP always be like oh yeah it's been Mass DP always do this do this right like uh it's about different you right like uh it's about different you know ways of visualization different know ways of visualization different ways of coding ways of coding um you know there's a lot of different um you know there's a lot of different things and yeah certain ways will be things and yeah certain ways will be more more um um optimal but you know getting to that optimal but you know getting to that point and you know being able to get point and you know being able to get that point and really have that that point and really have that understanding to kind of make changes understanding to kind of make changes along the way it's gonna be the the real along the way it's gonna be the the real difference when it comes to tougher difference when it comes to tougher problems that are a little bit more problems that are a little bit more difficult this one's okay though difficult this one's okay though uh but yeah anyway that's all I have for uh but yeah anyway that's all I have for this one that's all I have for this this one that's all I have for this problem let me know what you think if problem let me know what you think if you're doing a contest in an hour and a you're doing a contest in an hour and a half or so good luck uh wish me good half or so good luck uh wish me good luck uh but yeah stay good stay healthy luck uh but yeah stay good stay healthy take your mental health I'll see y'all take your mental health I'll see y'all later and take care bye bye later and take care bye bye [Music] | 2024-03-22 16:10:40 | 847 | 847. Shortest Path Visiting All Nodes - Day 17/30 Leetcode September Challenge |
|
BAAbDt2JiPs | today we're gonna be working on read quote question number 273 quote question number 273 uh anterior to uh anterior to english words english words convert a non-negative integer num to convert a non-negative integer num to its english words representation its english words representation so the num is equal to 1 2 3 so the num is equal to 1 2 3 which is going to be 123. which is going to be 123. this number is going to be 12 this number is going to be 12 345 and this one is 1 million two hundred thirty so in this class we're going to be so in this class we're going to be uh declaring few uh declaring few [Music] [Music] like the hard coded values these are the uh this is going to be like an like an uh an array private private final final string array we're gonna call it than than 20. 20. it's just gonna be an array having all it's just gonna be an array having all the numbers below 20 the numbers below 20 which is which is nothing nothing and then one three five five six eight ten and we're gonna go all the way up to ten and we're gonna go all the way up to 20 20 less than 20 so it's gonna be we're just less than 20 so it's gonna be we're just gonna keep it up to 19. gonna keep it up to 19. okay okay eleven 13 15 17 and 19. and still we are not done yet because we're gonna have ups we're gonna have two more of such variables now one for covering all the tens and one for covering all the thousands so um private final string and for the tens we're just gonna empty 20 20 [Music] 40 40 50 50 [Music] [Music] 60 eighty okay the last one is for the thousand okay the last one is for the thousand and it's only three some kinds of and it's only three some kinds of thousands we're gonna thousands we're gonna cover as like cover as like it's gonna be less than a billion so okay so for that one we're gonna say private final thousands which is going to be again an array that the first element is empty the second one is going to be thousand [Music] then a million that should be enough that should be enough okay once we have that the logic is very okay once we have that the logic is very simple it's like if the num is equal to simple it's like if the num is equal to zero zero we're gonna be saying that return we're gonna be saying that return zero zero right right that is just that is just a conditional a conditional like if if we are in that condition like if if we are in that condition we're going to be returning zero we're we're going to be returning zero we're gonna initialize our i equals to zero gonna initialize our i equals to zero and we're gonna initialize our answer and we're gonna initialize our answer uh word equals to an empty string uh word equals to an empty string once we initialize it we're gonna look once we initialize it we're gonna look keep looking at the number while the keep looking at the number while the number is greater than zero we're gonna number is greater than zero we're gonna keep processing it keep processing it otherwise we're just gonna return the otherwise we're just gonna return the num num num num sorry word sorry word um dot words let's just call it words um dot words let's just call it words dot trim i should do it okay and once we still have our number like it is greater than zero first thing we want to check if the number if we take the modulus of the number by 1000 right if that thing is not equal to zero if that thing is not equal to zero meaning if it is meaning if it is uh like oh oh that means like like that if we take the modulus by 1000 like that if we take the modulus by 1000 and the answer is not equal to zero and the answer is not equal to zero right right the answer is gonna be the answer is the answer is gonna be the answer is only going to be 0 when the answer is only going to be 0 when when the number is less than is it's going to be less than 1 000. if it is greater than 0 all we need to do is like uh all we need to do is like divide it by a thousand and just keep an eye on our eye we're gonna keep incrementing and i so other than that the only time we're gonna process it is when the number will become less than uh a thousand right when the model is when you take the modulus i'm sorry when the number modulus number modulus doesn't mean that if it is not equal to zero it doesn't mean that uh like it does not mean that it is less than one thousand or greater than one thousand all it means is it's not completely divisible by one thousand so if it isn't completely divisible if it becomes equal to zero right that means if it is completely divisible by 1000 and we're going to keep increment or we're going to keep dividing it by 1 000 and keep an eye on i like keep incrementing the i if it is not completely divisible by one thousand we're gonna take now we're gonna make sure we do we do two things the words is gonna become equal to we're gonna use a helper function in order to uh like calculate anything less than like 100 sorry anything so we take the modulus of that and we send it to the helper function and the helper function is basically gonna be uh looking for two things one is the like what's the uh what's the mo like where does it stand for anything less than 20 and anything less and uh and uh like basically it's gonna go through all like basically it's gonna go through all of it and then it's gonna of it and then it's gonna like it's gonna go through all of the all of these variables and see which ones we're going to be using right that helper function is going to just give you for the first thousand so we'll we're gonna once we're gonna once it comes out we're gonna it comes out we're gonna make use of this thousands of i we're gonna put some space in it and we're gonna put some space in it and plus the words so every single time what we are trying to do is to process it but in the end we are actually appending the the new strings at the beginning so we process the first 1000 and then divided by 1000 right and then just remove that last uh least significant three least significant bits and then we process the next uh next three significant bits and then significant digits and then that's how we keep doing it until it becomes equal to less than zero equals or less than zero so the last thing we want to do is to implement that function public string and num okay so for that the base condition is going to be if the that is the case just return empty that is the case just return empty string if it is not but the number is less than oops and then we're gonna be just returning the this less than 20 array and like plus plus some empty space um like uh some empty space um like uh plus a space so we're gonna append it plus a space so we're gonna append it that's better than that's better than else else if the num is less than 100 so we're gonna be recursively calling this helper function for that uh first thing we're gonna be doing is return then half num divided by 10 plus a space plus the helper function modulus modulus 100 oh sorry 10. and the last thing we're gonna do for that we're gonna say return than 20 num divided by 100 100 helper function helper function num modulus 100 so basically we are processing two things here one is like less than 20 and less than 100 so only two of the uh these final string arrays are used in the helper function less than 20 intense all the thousands okay okay let's give it a try so we are missing i think the space is missing over here and it works | 2024-03-22 12:31:53 | 273 | Leetcode Question 273 "Integer to English Words" in Java |
|
zWVGgmwSY_o | question 63 the code unique path two so you're given an m by n integer array you're given an m by n integer array grid there is a robot initially located grid there is a robot initially located at the top left corner the robot tries at the top left corner the robot tries to move to the bottom right corner the to move to the bottom right corner the robot can only move either down or right robot can only move either down or right at any point in time an obstacle in at any point in time an obstacle in space are marked as one or zero space are marked as one or zero respectively in the grid a path that the respectively in the grid a path that the robot takes cannot include any square robot takes cannot include any square that is an obstacle return the number of that is an obstacle return the number of possible unique paths that the robot can possible unique paths that the robot can take to reach the bottom right corner take to reach the bottom right corner the test cases are generated so that the the test cases are generated so that the answer will be less than or equal to 2 answer will be less than or equal to 2 times 10 to the power of 9. so this times 10 to the power of 9. so this question is just an adaptation of unique question is just an adaptation of unique paths 1 but in this question we have an paths 1 but in this question we have an obstacle which we need to take into obstacle which we need to take into consideration so in this first example consideration so in this first example we have an output of two where the first we have an output of two where the first path is all the way across to the right path is all the way across to the right and all the way down and the second and all the way down and the second possible solution is down and then right possible solution is down and then right all over paths include this obstacle all over paths include this obstacle here and as it states in the question if here and as it states in the question if any path includes the obstacle do not any path includes the obstacle do not include it in your output so let's dive include it in your output so let's dive into the solution to this question so into the solution to this question so with this question just like unique past with this question just like unique past one we're going to be utilizing dynamic one we're going to be utilizing dynamic programming and what dynamic programming programming and what dynamic programming does is it builds upon does is it builds upon sub-problems so it has overlapping sub sub-problems so it has overlapping sub problems in the question we need to find problems in the question we need to find all possible unique paths and that all possible unique paths and that should be a good indicator that we will should be a good indicator that we will be using dynamic programming so right be using dynamic programming so right here we have the grid array we have the here we have the grid array we have the start the finish and an obstacle here start the finish and an obstacle here and then and then this is going to be the dp array and this is going to be the dp array and what we'll do is we'll initialize every what we'll do is we'll initialize every single value within this dp array single value within this dp array to zero okay so this is the starting to zero okay so this is the starting point so what do we need with dynamic point so what do we need with dynamic programming we need some base cases programming we need some base cases in order to start populating this dp in order to start populating this dp array we're going to need some kind of array we're going to need some kind of base to work with and with unique paths base to work with and with unique paths and unique paths too it includes and unique paths too it includes the first rows the first rows and the first columns so what we need to and the first columns so what we need to do is we need to loop through the first do is we need to loop through the first column and we need to decide whether column and we need to decide whether there are any obstacles in there and we there are any obstacles in there and we can populate this dp array with that can populate this dp array with that value so so we know that we can reach value so so we know that we can reach this value because there's no obstacle this value because there's no obstacle there we know we can reach this value there we know we can reach this value and this value so there's one way to get and this value so there's one way to get to each of the columns in the initial to each of the columns in the initial row and then let's and then let's loop row and then let's and then let's loop through the rows in the grid to see through the rows in the grid to see whether there is an obstacle we have an whether there is an obstacle we have an obstacle here right so this value stays obstacle here right so this value stays at zero at zero and then we break from this loop so we and then we break from this loop so we do not check this initial row value here do not check this initial row value here we just keep that at zero which we we just keep that at zero which we initialized the dp array to so now initialized the dp array to so now we have carried out we have carried out the section outside of this the section outside of this and we've created that base to work with and we've created that base to work with so we have created the solutions to so we have created the solutions to previous sub problems and what we're previous sub problems and what we're going to do with dp or dynamic going to do with dp or dynamic programming is we're going to use the programming is we're going to use the solutions to those problems to work out solutions to those problems to work out the rest of the values so how many the rest of the values so how many possible ways are there to get to this possible ways are there to get to this value well there's one from here and value well there's one from here and there's zero from here because that's an there's zero from here because that's an obstacle so we can just add those obstacle so we can just add those together so one plus zero is equal to together so one plus zero is equal to one how many ways are there to get to one how many ways are there to get to this value here this value here well we have one from above well we have one from above which we calculated previously and we which we calculated previously and we have one from the left which we just have one from the left which we just calculated calculated so that is going to be equal to two how so that is going to be equal to two how many ways can we get to this value down many ways can we get to this value down here well we only have one from above here well we only have one from above because we didn't check the value on the because we didn't check the value on the left because there was an obstacle up left because there was an obstacle up here so we can add that into there and here so we can add that into there and then finally so the value for this last then finally so the value for this last one is going to be the summation of the one is going to be the summation of the potential solutions or the potential potential solutions or the potential paths to the cell above and to the cell paths to the cell above and to the cell at the left so that is going to be equal at the left so that is going to be equal to three to three and then we can just return this value and then we can just return this value so time complexity for this solution is so time complexity for this solution is going to be o going to be o m times n m times n where m is the number of rows and n is where m is the number of rows and n is the number of columns the number of columns and then space complexity is also going and then space complexity is also going to be o m times m because we are to be o m times m because we are utilizing a dp grid array here so let's utilizing a dp grid array here so let's code this out let's get let's get the obstacle grid the obstacle grid zero dot length so the columns and we're going to initialize this array and we're going to initialize this array with zeros so like we said in the with zeros so like we said in the solution let's loop through solution let's loop through the rows the rows and let's check to see if the value and let's check to see if the value within the cell within the cell so obstacle grid at i zero so obstacle grid at i zero so we're looping through the right here so we're looping through the right here is equal to one so if it's equal to an is equal to one so if it's equal to an obstacle let's set dp at i zero equal to obstacle let's set dp at i zero equal to zero so because there is an obstacle zero so because there is an obstacle within the grid we're going to set the within the grid we're going to set the value at dp to zero because there is no value at dp to zero because there is no potential way to get to this and this is potential way to get to this and this is a really important part because if we a really important part because if we don't break here we're going to loop don't break here we're going to loop through to the next row and we're going through to the next row and we're going to check that value and if there's no to check that value and if there's no obstacle in there it's going to populate obstacle in there it's going to populate the cell with one so we need to break the cell with one so we need to break out of this loop and because we have out of this loop and because we have initialized the dp array with zero up initialized the dp array with zero up here the next row within this is here the next row within this is automatically going to be set to zero automatically going to be set to zero else what we can do is we can set else what we can do is we can set dp at i0 equal to 1. dp at i0 equal to 1. so if there isn't an obstacle there is a so if there isn't an obstacle there is a path so we can add that into the dp path so we can add that into the dp array and then we need to do the same so remember it's the columns so we're so remember it's the columns so we're going to be looping through going to be looping through and checking obstacle grid 0 and and checking obstacle grid 0 and changing the column value changing the column value so j in this case so j in this case and we're going to be setting dp at zero and we're going to be setting dp at zero j equal to zero j equal to zero remember to break remember to break otherwise we'll set dp at zero j to one otherwise we'll set dp at zero j to one because there is a potential path because there is a potential path so that is the base of this dp solution so that is the base of this dp solution sorted so we have filled the initial sorted so we have filled the initial rows in the initial columns now we just rows in the initial columns now we just need to populate the rest of the dp need to populate the rest of the dp array grid array grid so we can loop through i starting at so we can loop through i starting at position 1 because we've already filled position 1 because we've already filled in the values at index 0. so if obstacle grid at i j is equal to one so if it is an obstacle we just set dp at i j equal to zero because there are no potential powers there else we calculate the recurrence relation so dpij is going to be equal to i minus 1 j so the cell above plus j minus 1 j minus 1 which is going to be the value to the which is going to be the value to the left then we just need to return the left then we just need to return the last value within the dp array grid okay let's submit it okay let's submit it and there you have it | 2024-03-20 10:55:32 | 63 | Unique Paths II - LeetCode 63 - JavaScript |
|
uyaOlNOTUA8 | my dear friend. What are you doing? I hope you will be fine and in the best condition. God willing, we will solve the problem together today. Today, if you have not tried the problem, as usual, you must must switch to it first before you watch the video. Give switch to it first before you watch the video. Give yourself some rest at this time, tomorrow, the problem, and try yourself some rest at this time, tomorrow, the problem, and try to understand it, and try to write the code or to understand it, and try to write the code or to understand it, and try to write the code or and then write the code. If you tried, you wouldn't know. Let's start. In the name of God, he will tell you that it's called [music] and it's called "Kit." Or let's say, for example, that you now have, for example, will tell you that it's called [music] and it's called "Kit." Or let's say, for example, that you now have, for example, a memory in which your a memory in which your house is completely fine, and you have but it will remain. four places like this in the cash. The first place is in, for example, Kilo Value, or Study, and here, and here, and here, for example, Zero, One, Two, Three. The place is 0123. This is FIFA today, for example, X, ABC, and CD. Okay, in order like this. My ABC, and CD. Okay, in order like this. My hand uses it the most hand uses it the most and I use it the most, but and I use it the most, but and I use it the most, but my father, and so A,” for example, “D,” I want to A,” for example, “D,” I want to enter it in the cash register, what will happen if I enter it in the cash register, what will happen if I want to use it, then enter it first in the cash want to use it, then enter it first in the cash register? It is better. I take out the “A,” and “B,” and “C,” better. I take out the “A,” and “B,” and “C,” and “D.” and “D.” and “D.” I came to use the verse once again until I started using it larger than the C. At that verse would remain fine, so when I come, for example, a new one. Something new, so he entered the prison place, and again, if I kept using CC until it came up above the verse and the verse went down at that time, the verse would come out, even though it was the one used the most, but I didn't why let him usage would remain hers. I mean, for example, I used it, that's it, usage would remain hers. I mean, for example, I used it, that's it, three times, that's it. three times, that's it. three times, that's it. By God, the operation is coming up, I need to call for my hand. Finish, add its usage to a cell of six, and for example, I used it the next time, and it will be okay. I used it again once, and there will be five days left. This is going up, and this one is going used it again once, and there will be five days left. This is going up, and this one is going under, and so on. under, and so on. I am using something, so I supply my Frequency I am using something, so I supply my Frequency every time.” every time.” every time.” I used it, so I from the from the priority to the lower, the priority to the higher, the priority increases. Okay, priority to the lower, the priority to the higher, the priority increases. Okay, and when I come to enter new data in the lowest, I and when I come to enter new data in the lowest, I use it, so I take it out of the cache. Okay, okay. This is an use it, so I take it out of the cache. Okay, okay. This is an idea. idea. Ok, what do you have in your hands? The first thing in your hands is Ok, what do you have in your hands? The first thing in your hands is cholesterol that passes through the cache that we were cholesterol that passes through the cache that we were using. using. using. give you a cake. The cake Okay, based on today's complex, my Okay, based on today's complex, my medal, so it's supposed to be me. I mean [music] In the first example with us, first thing he told you is what type of constructor, and first thing he told you is what type of constructor, and after that, what after that, what happens? happens? Send two. Send two. Send two. have crazy people like that. The first one was the second one, Al-Aqsa evidence, something that I could store in the detector. After that, he told you what happened when he made the cash bot. There were two places in it, one place remained in one place, and the first place remained in one place, and the second place remained in one The second one remained empty, perfectly fine. The second one remained empty, perfectly fine. The second one remained empty, perfectly fine. After that, he said to you again, Monday, and After that, he said to you again, Monday, and her team had two, so the cash was now full by her team had two, so the cash was now full by two, one was full, and their counter was full, and the one they were using alone brought the three bots, so when brought the three bots, so when you made a bottle of three, your cash was supposed to be you made a bottle of three, your cash was supposed to be full by now. Okay, when full by now. Okay, when full by now. Okay, when happened. I am supposed to remove either the one or the two. Ok, you will finish one of them. I will remove the two. The one I will remove is the two, because the two are more. I mean, I worked for the two, and the one also deleted it because my cup was two, but deleted it because my cup was two, but two numbers, but okay, it remains the same. two numbers, but okay, it remains the same. two numbers, but okay, it remains the same. to the first and cash register, cash register, which is the first place and the second place. After that, what should I do for the two? There will be two. One is Syrian. Okay. So when I came to make the three bouquets, what should I do for the two? There will be two. One is Syrian. Okay. So when I came to make the three bouquets, what happened? Either I remove this one and put three in his place. Okay, this one and Three, so I will have the Three, so I will have the Three, so I will have the lowest fricon, so I will put three in its place, and her lowest fricon, so I will put three in its place, and her video is 3. If I come to do it, I will come to the two again. What will happen to the two? It is no longer available. I have two places, but where is it in the I come to do it, I will come to the two again. What will happen to the two? It is no longer available. I have two places, but where is it in the cash, so either one or three, cash, so either one or three, the two are not there, so it is returned to a minus one. the two are not there, so it is returned to a minus one. the two are not there, so it is returned to a minus one. expresses half of it, and you go ahead and remain as you are, and this is the Ok, something like this. How do you do the first thing we did in the code? The first thing I told him, by is in Value and Frequency, and its place is in One thing before I One thing before I One thing before I explain the code is how we have our idea in the first place. explain the code is how we have our idea in the first place. Before we explain the code, we will say what our idea is. Our idea is that we have something called cash. Okay. So, we are supposed to have this cash. It has a few places depending on the pressure. Okay, and another thing called a Okay, now I am storing in the cash register what is the nice, his bathtub is 3 ironing. Three is fine. This is nice, meaning that I want this friconciy to be there as well. I mean, I am here if you look at the code. Okay, okay.” Okay, okay.” I said, for example, I entered on Wednesday, and her Frequences are one so far. I mean, my consultations will be based on this place. Okay, okay, okay. I’m doing what I’m doing now. When I do it, you brought me the three. What will change? I will my consultations will be based on this place. Okay, okay, okay. I’m doing what I’m doing now. When I do it, you brought me the three. What will change? I will return her value, which is yours. return her value, which is yours. Three of yours is Three of yours is okay, okay, but there’s something. okay, okay, but there’s something. okay, okay, but there’s something. because I used it more than once, so I change the Frequency and it will remain at two times. Okay. After I change the Frequency, I tell him, “No, here at here at two, and we said this represents Nancy’s team What is the number 4 on it? What is the number 4 on it? What is the number 4 on it? Of course it will be erased from above. Of course it will be erased from above. Okay. It will be the second. The first thing is this review here. Sory, I made a mistake. This is supposed to be four. Okay. Okay. Beautiful. Okay, if this is if I make a bot. Okay. If I do this, what made a mistake. This is supposed to be four. Okay. Okay. Beautiful. Okay, if this is if I make a bot. Okay. If I do this, what happens? The same thing happens. I said that I when happens? The same thing happens. I said that I when happens? The same thing happens. I said that I when which is the two, so that she would let him marry her as she was, I provided her with the which is the two, so that she would let him marry her as she was, I provided her with the two, and after I provided her with the two, I changed the one, I removed the three two, and after I provided her with the two, I changed the one, I removed the three from here, from here, put them in the two fricon, and said to the put them in the two fricon, and said to the pointer, I let him consult on the three, ok, pointer, I let him consult on the three, ok, this is the one that is this is the one that is the boot and the dry, ok, if I want the boot and the dry, ok, if I want the boot and the dry, ok, if I want problem of the lowest value or the lowest Frequency. Ok, I will know how to roll the Requency. I will go to the Frequency, which is four. The one that is Syrian is one of them. This is supposed to be correct. Ok, it is not. One of them will tell me, ok, maybe this one will no longer be assumed that I am already full of cash and want to assumed that I am already full of cash and want to delete from it before. delete from it before. delete from it before. so what will happen is that I will go to the lowest value and find it, which is the one that is the thousand requinti. What will I do? I will find it from here and it from here and change the aluminum fricons from change the aluminum fricons from change the aluminum fricons from remains, this is what we will do. You will understand more if you do not did was this did was this pen. You are ours. It will remain in a video that will be pen. You are ours. It will remain in a video that will be consulted on its place. This is a subscription consulted on its place. This is a subscription to it. This expresses about ironing. Okay. This represents the cake Three Three Three things, the value and the frequency are fine, and you want the one that is a pointer to his place in the frequence, ok, this is for the frequence. This is the frequence. This is the second one, which second one, which is the cash that is is the cash that is stored. stored. stored. my real elements, which are our main ones, and the value will be three things. The value in Fulani, who is number three, will tell me your bag is such and such and such. Their Frequencies are first thing I will do with a premention? What is this first thing I will do with a premention? What is this He will do anything except He will do anything except He will do anything except that I will take this capsule that you that I will take this capsule that you will store in the capsule that I made above here, which is fine, fine, fine, but it is like that for her people, but If you write it If you write it If you write it down, it will pass. I mean, down, it will pass. I mean, after that, you will take the key. I am supposed to return, either with one negative note. If you have not counted on it before that. Either the one inside will come back. You will return, or you will return one negative note if you have not counted on it before that. Either the one inside will come back. You will return, or you will return one negative note if this key is not in the cash register this key is not in the cash register or it is in the checklist at that time. or it is in the checklist at that time. or it is in the checklist at that time. fine, fine. Here, what did I do? The first thing I said to my cash was that I counted this cake by checking it for the amount that was in the cash, or if it was there, it would be returned to us. True, if it was not front of the money. I mean, if it was not there, it would return Fault 2 via the note, and This iron of This iron of This iron of yours is not in the cache yours is not in the cache right now. Well, we assume that there is an existing type that continues to complete right now. Well, we assume that there is an existing type that continues to complete normally, so what will happen? I said, “By God, I I will go to the Frequency with the iron on the cash. I mean, now I will go to the first army. Okay. I will tell him that my iron is, for example, three. three things. Okay. What do I want to do with it? I want to go to the first to the cash register and get your second Frequency from it because the cash stores three things in it. three things. Okay. What do I want to do with it? I want to go to the first to the cash register and get your second Frequency from it because the cash stores three things in it. Valeo and Frequency needs. I that I want to do. I came to this one that is there. What am I supposed to do with it? I am supposed to move it from Frequency 3 right. right. I mean, now if I have a key, let’s set a I mean, now if I have a key, let’s set a better example than this I now have a cash register, which is fine. I will assume that our cash register, for example, has a set of three, while his Palio is 3, and his Frequency is two, fine. Certainly, as long as it is two, he will continue to consult on the second place here, which is two, then whatever Frequency is two, fine. Certainly, as long as it is two, he will continue to consult on the second place here, which is two, then whatever happens, it will be stored here in the Frequency, happens, it will be stored here in the Frequency, not cash has the number three, so I say, I swear to cash has the number three, so I say, I swear to God, what is cash dot com is three, and he God, what is cash dot com is three, and he tells me that it is there. He tells me that it is there. He will return under circumstances. He will continue. I mean, he will not enter the end at that time. What will will return under circumstances. He will continue. I mean, he will not enter the end at that time. What will happen? I need now before I return happen? I need now before I return the video to him that is here. I mean, he is supposed to the video to him that is here. I mean, he is supposed to return two to him. return two to him. I return it to him, but before I return it to him, I'm supposed to I return it to him, but before I return it to him, I'm supposed to change your phone, change your phone, Syrian. This is fine. I'm supposed to want to go back to the video, mean, I'll replace the mean, I'll replace the whole place of this talk with two. So, whole place of this talk with two. So, I'll be free in the two that this I'll be free in the two that this place is. Okay. What's up? place is. Okay. What's up? What will happen is Dot IT, What will happen is Dot IT, which is, which is, give me the cash, and in the K, which is the three, and give me the cash, and in the K, which is the three, and in the A, I.T., which is the place of his, which is this. This is a nice place. This is the three, I am supposed to delete it. This means that it is not the same in three, and in numbers A consultation A consultation A consultation on the place of the three in the studio, on the place of the three in the studio, and Okay, and a consultation on the place of the and Okay, and a consultation on the place of the three, and I go to erase the three, he delete it, that is three, and I go to erase the three, he delete it, that is because he told me, boss, so I said, the three erasing is okay, after I finished the line, Syrian, it is nice, what do I want to do? I will in in in which is the three, so I went to see if it is the frikonis of the new frikonis, which I still changed two, it became three, or remains three, it does not have the which is fine, and after that, change the verse to your tritur, the one who is peshawar here, it is not he who was peshawar here, He is there because he is holding on to erase what He is there because he is holding on to erase what He is there because he is holding on to erase what will happen. I want to leave him instead. will happen. I want to leave him instead. He was consulting here. He is not consulting about He was consulting here. He is not consulting about the three. In this he is consulting about the three. This list will happen. How did you tell him about your examination? What is the plan behind his I.T.? He The preface is still working with a pushback. The preface is still working with a pushback. The preface is still working with a pushback. I don't have it. I didn't make a I don't have it. I didn't make a pushback. If the last place pushback. If the last place is in three, the Peshawar is next to the last one. Okay. Give me his preface, which is the three. Where is the Peshawar is next to the last one. Okay. Give me his preface, which is the three. Where is the safe in the next one? So, it's like I'm telling safe in the next one? So, it's like I'm telling him to go and take a shower on the three like that. I swear to God that the German I swear to God that the German I swear to God that the German from Frequency Plus is fine, and after that, after I finished these operations, I went to the cash and in the ironing Total, do some things that are do some things that are supposed to return his property, and supposed to return his property, and if he is not there, it will return negative one, but in the A few calculations. What are the A few calculations. What are the A few calculations. What are the calculations? The first thing I need to remove are the three from her calculations? The first thing I need to remove are the three from her current Frequency. I don't have a Frequency. For example, it used to have three, so these three inside are supposed to not have all don't have a Frequency. For example, it used to have three, so these three inside are supposed to not have all the bag that they had in three. Okay, the bag that they had in three. Okay, now I made a new query in my Frequency. You will know that for three, there will now I made a new query in my Frequency. You will know that for three, there will actually be four left. I actually be four left. I should delete it. should delete it. should delete it. Ok, if I delete it, it is not that I am supposed to go and look for it, and then it will take time. That's why I'm storing her alter, which is her place, so I will go straight away and tell him to delete such-and-such place for me, okay. So when I told them under such-and-such place, that's it, I Okay, give me the Okay, give me the Okay, give me the new place, which is at the end of the studio. Okay, and new place, which is at the end of the studio. Okay, and see what I deleted. Is it still see what I deleted. Is it still empty or not? empty or not? If it is still empty, then my toilet is supposed to increase by one. Well, if it is not empty, then it is not empty. What do you If it is still empty, then my toilet is supposed to increase by one. Well, if it is not empty, then it is not empty. What do you Other than that, go back to the video, just to get the Other than that, go back to the video, just to get the video back. do n't know how to draw n't know how to draw seconds. The cash that is supposed to be cash that is supposed to be at three, for example, as we agreed at three, and her at three, for example, as we agreed at three, and her freebies are four. So freebies are four. So I need to go to place number I need to go to place number four, and it will be a shower at place 3D in India. four, and it will be a shower at place 3D in India. Fine, fine. I'm fine. thousands mean. If my capsi is thousands mean. If my capsi is zero, I won't be able to add. I don't know how to zero, I won't be able to add. I don't know how to add anything. Okay. I mean, I don't know how to add any value. Okay. Then, Okay. Okay. The first thing is Okay. [Music] Okay. I mean, I'm going to go now and get his video. For example, he wants me to leave these three with 6, for example, so I go and delete the three and put six in their place. Someone will tell me for a few seconds, “ You are not supposed to set the frequency. This is not considered queer. This will be provided to you, Frequency. You are like that.” It means that I will go and delete it from here What will you do in each verse? This art itself will do. It will go and tell us that I, by God Almighty, have such and such example with three. For example, these three frikones have four. What will happen? As we explained, these four will increase. There will be five left and they will be deleted from here and put here. This item will be discussed here. It won't come back to us, but after he returns home, okay, then what do I really need to do for okay, then what do I really need to do for Abbott? If this value is available, I Abbott? If this value is available, I think it's there, so I'm supposed to change its think it's there, so I'm supposed to change its fricons and change the iterator, okay. Delete it, I fricons and change the iterator, okay. Delete it, I mean, from here and put it here and consult about what's mean, from here and put it here and consult about what's new, right, and after that I change it. Okay, I want. new, right, and after that I change it. Okay, I want. new, right, and after that I change it. Okay, I want. first two have done a function. I don't need to do them. The second one will be better. I can Nice, nice. It's not Nice, nice. It's not here. The problem will start. What is the problem? I have two things. The first thing is all. There are still empty places in the cache. Or it's not there and it's not all. There are still empty places in the cache. Or it's not there and it's not there. there. there. about it that is worth the maximum I can about it that is worth the maximum I can get to it. I opened it, get to it. I opened it, I am full of everything else, so I need to do what to take an empty place, a right place, and an empty place, which place is less frictional, so I stood up and right place, and an empty place, which place is less frictional, so I stood up and told him, by God, the cash for the told him, by God, the cash for the fricony, which is an aluminum fricony. fine. It's nice. Delete it for me from the cash. I'm assuming that it's, for example, how many four. I'm looking around the army at the place of four. That's it. I'm going to delete it from where. It's army. So, where will I remove it army. So, where will I remove it from my soul? It's fine. It's okay. As for the cash. Cash. Cash. Cash. it is saved will be where you will put the value and free content. It will remain in okay, then we say [music] The I doing? I will see if I press zero, I will be able to put I will be able to put I will be able to put anything in the cash right away and it won't anything in the cash right away and it won't happen forever and nothing will happen. It's fine if I come to do two things. If it's a negative one like this, she told me that this one does n't exist. Okay, if it's a second number other than a negative one, I mean, it's not a negative one. What did you do? The first benefit is that she made me know that it was not a single negative. Ok, the second benefit is made me know that it was not a single negative. Ok, the second benefit is that she provided me with his fricones and edited the fricones and the cup for me. Okay. So, I am not empty, except that I am editing the video, so I edited the video. I It turned out to be negative It turned out to be negative It turned out to be negative one. If you are new to me, one. If you are new to me, new at that time, what will I do? I have two cases new at that time, what will I do? I have two cases in this place. The first episode is that this in this place. The first episode is that this is me or Syrian. The cash is either there is no okay. After that, okay. After that, we assume. After that, I will put the video up. we assume. After that, I will put the video up. we assume. After that, I will put the video up. that will remain in the new value is one new value and its iterator will be set and everything. If it is in an empty place, it will not be afraid. If it is in an empty place, it will be fine. If it is in an empty place, it will fine. Finish fine. Finish this video. You give an example like this and walk away. this video. You give an example like this and walk away. this video. You give an example like this and walk away. I drew the Quraish like this and walk one by one. But if you do that, the time of the video has already reached 40 that happen in this, it takes one size or, and in the summer of the cover, here you have one cloak and this one in one. here you have one cloak and this one in one. here you have one cloak and this one in one. and this is one, then you have the new one, or in and zero, you and zero, you can say that it is full, and in Upper Egypt, for the people can say that it is full, and in Upper Egypt, for the people you are looking for, spread one, what will it be? It is not nice, it is not nice, this cash dot is one, because it is the cash, this is a cash, this is a hashtag, and this is also one, the front is one. hashtag, and this is also one, the front is one. hashtag, and this is also one, the front is one. internet is one, the pushback is one, this one is one, and this one is free charge as off 1. So we are the same as free charge as off 1. So we are the same as we are in the question: You need to make an off 1 we are in the question: You need to make an off 1 release. He release. He told you that if you feel like you have not understood a little, you can repeat the video again, or it is possible, and this is better, that you answer with This is exactly the same as the one above, for example, this is the first thing the bot tells you to go to the bot's funk and take the one, the one, and the other, and draw the rest of the cash like this, and draw the frequences like this, and let him consult, and these words will make you understand more, God willing, and examples and examples will make you understand more, and sending this code Can you write to me in the comments? God willing, I will Can you write to me in the comments? God willing, I will continue to see the comments. continue to see the comments. But I will see you, God willing. I will see you But I will see you, God willing. I will see you next time, God willing. All will be well. Peace be upon you. | 2024-03-22 15:01:10 | 460 | LeetCode - 460. LFU Cache |
|
TOGUQfEpv7I | Hello everyone, so today we will do division, the problem is that we have given the end of positive integers and we can perform two operations on it. What are the two types of operations we can perform that if the element We can divide by tu We can divide by tu We can divide by tu means like this is 4 emails then we divided it by 2 to get means like this is 4 emails then we divided it by 2 to get tu and if the element is OD then tu and if the element is OD then multiply tu means if it is OD then from tu multiply tu means if it is OD then from tu like if it is 1st or 3rd order then we can convert it into 6 or 2. Now it is said that the division of D is D is the Now it is said that the division of D is D is the maximum difference between other elements, maximum difference between other elements, which is the maximum difference between other which is the maximum difference between other elements present in this means that the elements present in this means that the maximum difference of any two elements is maximum difference of any two elements is said. Okay, and what we have to get is the said. Okay, and what we have to get is the minimum division. minimum division. minimum division. perform this operation and - - maximum - minimum element. maximum - minimum element. Maximum possible Now in the question we have two operations which are Now in the question we have two operations which are and if any element is our and if any element is our and. and. and. is ours and then what can we do with it, we can do it by you, okay okay, this was ours, now look at one thing, we this was ours, now look at one thing, we still talked about that means we still talked about that means we cannot increase, so we can take our minimum. cannot increase, so we can take our minimum. cannot increase, so we can take our minimum. increase, okay, then what will we do, as soon as our first thing, what will be our approach that like this is our what will be the maximum possible value of all these elements, what will be the maximum possible value of four, What will happen to three? If three comes then what is its maximum possible? Now this means that we Now this means that we cannot make the maximum value of any element more than this cannot make the maximum value of any element more than this and what we had to do was to increase the minimum. and what we had to do was to increase the minimum. So what will we do? So what will we do? We have found out the maximum value of all these. We have found out the maximum value of all these. We have found out the maximum value of all these. we will take a minimum of them, ca n't they increase more than me, so the minimum has reached till now, just like you are here, your minimum has reached here, now what can we do, minimum can't do anything, what can we do with the maximum? Now because the whole number is and, these are all the numbers, okay, and we can further decrease the number, this is our element, now our division is - 2 n't ever Ours is the same Then we are ahead n't ever Ours is the same Then we are ahead Meaning Arey's Still What is the minimum maximum Meaning Arey's Still What is the minimum maximum value Three Audition Kitna Aa Gaya 3 - 2 1 Division Can Because we cannot further decrease more elements because if there is any more element then we can multiply it by 3, this means our further increase will be three and for the If we If we If we want a minimum then want a minimum then we cannot do anything less than this, as soon as we cannot do anything less than this, as soon as our maximum amendment is changed, our maximum amendment is changed, our loop will be terminated and the our loop will be terminated and the value of our division will be our minimum value of our division will be our minimum possible. You must have understood, again let possible. You must have understood, again let me tell you me tell you first of all what I said. first of all what I said. first of all what I said. took the error and told what it means, what can be the maximum possible values, what can be the maximum possible values that if the number is and because after and, we cannot increase it, we have to decrease it, so So it was done, So it was done, So it was done, we converted all the numbers we converted all the numbers and converted it to the maximum and converted it to the maximum value, now we had to increase the minimum, value, now we had to increase the minimum, so we calculated the maximum possible so we calculated the maximum possible values, after that values, after that we stored the minimum element from AD. we stored the minimum element from AD. After this, now we plan the maximum After this, now we plan the maximum and we have to decrease the maximum and we have to decrease the maximum because if there is a saree element then there will be a decrease because if there is a saree element then there will be a decrease also, so we have to check that, so we have taken a also, so we have to check that, so we have taken a maximum, in the maxip we have entered this maximum, in the maxip we have entered this saree element which is our first saree element which is our first maximum element, here we maximum element, here we stored the division. stored the division. stored the division. can further decrease this element or not and it has decreased, we again put it in hit and always keep checking this, that means it is minimum, it is minimum of add, so we This will continue This will continue This will continue until until one more element is reached which is on our top and if the element is one more element is reached which is on our top and if the element is reached then it means that we cannot do the degree, that is reached then it means that we cannot do the degree, that is our minimum possible which [laughter] so we have to name it with the name I will store the meditation 1 minute, we have to leave from here, we have to leave, then we will check after leaving. | 2024-03-20 11:00:12 | 1,675 | 1675. Minimize Deviation in Array||LEETCODE||DAILY CHALLENGES|| EASY EXPLANATION|| C++ |
|
Fu1O_k-ogB4 | [Music] [Music] | 2024-03-20 15:51:33 | 1,720 | leetcode 1720 Decode XORed Array |
|
gAjnEoQWRVI | hi so this question is rotate function so you are giving the integer numbers so you are giving the integer numbers array and then you want to rotate the array and then you want to rotate the nodes by K position clockwise so you nodes by K position clockwise so you define the rotate function so this is define the rotate function so this is the formula and then you want to return the formula and then you want to return the maximum of value F of 0 f of one all the maximum of value F of 0 f of one all the way until F of n minus 1. so uh the way until F of n minus 1. so uh let's look at this so I'm just using this example right so you will have to have a coefficient in front of every single num side so this is going to be what zero times four plus one times three plus two times two plus three times six and then you will sum every all of the multiplication up and then you again the value of 25 so let's just swap swap what swap the the num's eye to ABC so the coefficient is going to be still the same so all of zero zero times a plus 1 times B plus 2 times C plus three times d right they are the same 0 times a 1 times B right 2 times C plus 3 times d right so what happened to F of one you want to rotate what clockwise so zero will be what at a d position right so it's going to be Zero D right so Zero D right and then what clockwise so it's going to be about one times four so one times four imagine sorry not imagine look at this one or one times above one uh four is uh a right so one a Plus 2B Plus 3C and then plus right so let's do one more F of two so we in in this one which one is a zero it's going to be here and C 0 C right one one d right one D q a and three e I so this is like f of zero f of one F of two and then using a b c d uh to represent so let's do a little bit math so imagine F of one minus F of zero so what do you get 1n minus zero a one day right plus 2B minus one b one b right plus so we see minus two c one C plus zero D minus 3D negative 3D right all right so let's not uh over yet look at this I'm going to do some magic so 1A is still going to be the same one B this is still send one C still going to be the same so if I add another 1D over here does that mean I need to say subtract 4D right if I add one d right here I need to if I add one d right here I need to subtract 1D again in the same equation subtract 1D again in the same equation right right so what does a plus b plus C plus d so what does a plus b plus C plus d a plus b plus C plus d is what the sum a plus b plus C plus d is what the sum of the nums right of the nums right so sum so sum sum sum or equal to a plus b plus C plus d or equal to a plus b plus C plus d so let's replace some over here so let's replace some over here and then minus 40 and then minus 40 for this equation right for this equation right all right so we have minus 40 right here all right so we have minus 40 right here right so let's look at F of 2. so I'm right so let's look at F of 2. so I'm just using another color just using another color so what does f of 2 minus F of 1 so what does f of 2 minus F of 1 so this is f of 1 minus F of zero right so this is f of 1 minus F of zero right so we got this so let's still get F of 2 so we got this so let's still get F of 2 minus F of 1. so 2N minus 1A 1A minus F of 1. so 2N minus 1A 1A Plus Plus 3B minus 2B 3B minus 2B from B from B Plus Plus zero C minus 3C zero C minus 3C negative 3C negative 3C and then plus 1D minus zero D One D and then plus 1D minus zero D One D all right so it's still going to do some all right so it's still going to do some magic let me magic let me write this clearly so write this clearly so so I'm going to say a oh sorry this so I'm going to say a oh sorry this should be equal sign should be equal sign let's move on here A plus b plus let's move on here A plus b plus if I add another C I need to subtract if I add another C I need to subtract another C right so I'm going to just another C right so I'm going to just write plus d here and then I will say write plus d here and then I will say minus 4 C minus 4 C am I right so I just double check am I right so I just double check a I use it B I use it D I use it a I use it B I use it D I use it see I use it right so minus minus 3 C see I use it right so minus minus 3 C minus C is going to be minus 4C right so minus C is going to be minus 4C right so again this will be what again this will be what this will be the sum right so sum minus 4C equal to F2 minus F1 all right so if you know the pattern if you know the pattern uh let's move move over here so if you know a pattern F of one minus F of zero this is equal to sum minus 40. F of 2 minus F of one it's going to be sum minus 4C and then if you can guess the pattern F of 3 minus F of 2 this is going to be sum minus 4B last but not least forever so do we have F of 4 so do we have F of 4 uh a b c uh a b c uh it looked like we have it right with uh it looked like we have it right with e e actually we don't have ever fall this is actually we don't have ever fall this is biggest one biggest one we only have four uh nums value in the we only have four uh nums value in the numps array numps array so this will be what so this will be what this will be a pattern this will be a pattern and and if you can move minus uh minus F of zero if you can move minus uh minus F of zero onto the right side it's gonna be plus onto the right side it's gonna be plus F of zero right and then minus F of Y is F of zero right and then minus F of Y is going to be plus F of one minus F2 is going to be plus F of 2. so F of 1 is equal to F of 0 plus sum minus 40 right so for every single iteration once we find out the F of zero and then also the sum right and then T is given y this is a e c t if D is given then we don't need to calculate right so we need to calculate for the sum we need to calculate F of zero right and F of zero is super straightforward what does f of zero represent zero a plus one B plus two c plus three b d sorry all right so we need to keep added keep up updating for every single uh h of f of I right so it will be in the full for sure right so what I have is what I will have some so what I have is what I will have some people to watch people to watch the the nums sum and I'm sorry sum right so this is a sum straightforward now and then I have if initial is starting from zero right and then I need to service a photo in the num sorry and the F will be equal to 1 plus equal to I times right so this is going to be 0 a 1B 2C 3D right and then I need to return the maximum value okay so I would say Okay F of 0 is going to be represent the maximum for now right and then I will Traverse the entire uh four iteration right F of 0 to F of three right but since F of 1 minus F of zero F of 1 minus F of zero is equal to sum is equal to sum minus 40. so if you know D this is the minus 40. so if you know D this is the last element in the nums array right so last element in the nums array right so we need to starting from the last we need to starting from the last all the way to I equal to one we don't all the way to I equal to one we don't need to Traverse I equal to zero this is need to Traverse I equal to zero this is represent what we already calculated F represent what we already calculated F of zero right so we don't need to of zero right so we don't need to calculate F of zero again calculate F of zero again but if you're one you can do it but I'm but if you're one you can do it but I'm not doing this not doing this so it's going to be ever num side minus so it's going to be ever num side minus one and then you have the greater equal one and then you have the greater equal then one and I minus minus then one and I minus minus so uh straightforward enough and then so uh straightforward enough and then for every single time I need to keep for every single time I need to keep updating my math result updating my math result right so this is going to be represent right so this is going to be represent the maximum Uh current maximum value for the maximum Uh current maximum value for f of 0 f of one all the way to F of n f of 0 f of one all the way to F of n minus one minus one so if you still remember the formula so if you still remember the formula this is going to be what this is going to be what sum sum plus F of plus F of zero zero in this case this is f of one right F of in this case this is f of one right F of one equal to sum plus F of zero minus one equal to sum plus F of zero minus the length which is four right four is the length which is four right four is representing the length of the the nums representing the length of the the nums uh length of nums times the current uh length of nums times the current d right you need to times d right d right you need to times d right so so um um in this one is three is three D three D in this one is three is three D three D right and then you need to calculate right and then you need to calculate that half the next iteration F again that half the next iteration F again right right again this is a formula for f right if again this is a formula for f right if you still remember you still remember F of 1 is going to be equal to sum plus F of 1 is going to be equal to sum plus F of 0 minus F of 0 minus the three right this is three three the three right this is three three times and then this is going to be c p a times and then this is going to be c p a and for every single each iteration and for every single each iteration later on so I'm gonna just say run it so here we go says look at the time in space for a second this is the time this is the time this is the time and then obviously right all the fun all the fun all the fun and then space this is space space so it's constant so that's pretty much it right so let's just try to use a debug mode and then to see what just happened and yeah all right pause the video at any second and then you see uh the result right so 25 so 25 represent F of one zero right if you if you can remember F of zero right so now I'm going to Traverse so look at this this is going to be the here we go so we just finished here we go so we just finished and if you still have caution leave a and if you still have caution leave a comment below and then subscribe if you comment below and then subscribe if you want it want it so peace out bye | 2024-03-24 12:15:22 | 396 | LeetCode 396 | Rotate Function | Arrays | Debug | Java |
|
eV56CX_cpq8 | in this video we're going to take a look at a lethal problem called paths on at a lethal problem called paths on number three number three so in this video i'm just going to show so in this video i'm just going to show you how we can do this in a you how we can do this in a n squared time complexity as well as a n squared time complexity as well as a linear time complexity linear time complexity and basically the question is that we're and basically the question is that we're given a binary tree and we want to given a binary tree and we want to find uh we want to find the number path find uh we want to find the number path that has a sum that is equal to the that has a sum that is equal to the given sum given sum and the thing is that we can have a and the thing is that we can have a sum where we can have a path that star sum where we can have a path that star that does not have to start from the that does not have to start from the root root and it also does not have to end at the and it also does not have to end at the relief node and relief node and if the path must travel downwards we can if the path must travel downwards we can have negative value in the node we can have negative value in the node we can also have a positive value in the node also have a positive value in the node so basically uh you can see here we give so basically uh you can see here we give an example where we have a binary tree an example where we have a binary tree so we have uh in this case we have so we have uh in this case we have three we we're returning three there are three we we're returning three there are three paths right one is we can do three paths right one is we can do five plus three the other one is uh five five plus three the other one is uh five plus two plus one plus two plus one the other one is negative three plus the other one is negative three plus eleven which also gave us the sum of eleven which also gave us the sum of eight so in this case we are um eight so in this case we are um we're returning three because they're we're returning three because they're total three paths total three paths so how can we do this well what we can so how can we do this well what we can do is do is it's very similar to the path number one it's very similar to the path number one capstone number two capstone number two right we can traverse right we can traverse using that first we can traverse the using that first we can traverse the trees in that first search trees in that first search and uh we're gonna have a list a list of and uh we're gonna have a list a list of elements that were traversed in our list elements that were traversed in our list right all the elements that were right all the elements that were traversing the list traversing the list uh are all the elements that we traverse uh are all the elements that we traverse so far we're going to put them in the so far we're going to put them in the list list if we were to backtrack we will remove if we were to backtrack we will remove that element off the list and then we're that element off the list and then we're just going to just going to basically for each and every single um iteration right for each every single node that we traversed we're just going to do a reverse traversal like a reverse iteration to find the sum that has we're trying to have a trying to find a sum that is equal to target sum right basically if we were traverse right we're going to have a let's put a commons there so let me just demonstrate to you how we can do this using n square time complexity um right basically we're starting from the um starting with a empty list right so we passed in with an empty list and the target sum is eight right so first when we get to the the first level right we have uh 10 right we add 10 onto it then we know that 10 does not equal eight then we just continue traverse the left reverse the right so we're doing that for search so we're going to focus on the left first so that we have five then what we're going to do is we're going to start to iterating starting from the last element to the first element in the list so 5 does not uh so so far the sum is five five plus 15 it does not equal eight so we're just going to continue do that first search now we have three right so we have three here and basically what we're going to do is we're just going to have a a we're just going to iterating backwards and getting the sum so we have 3 3 plus 5 is 8. so now we just basically found a path that has a sum that is equal to eight we just increment the counter by one then we continue that we have 18 which does not equal to eight so then we're just going to terminate right so after we do that we're just going to continue to to um go deeper right we have three here right we're going from here here here here right we're going that first search we're traversing from to the left first so now we have three three plus three is six six that's not equal to eight then we have eleven twenty one right so then we are on the leaf node uh in this case then we're gonna start to do backtracking then we're going to remove the last element off the list and now we're going to a different path we're going to negative two right so we have negative two we know that negative two plus three is one one plus five which is six six plus 10 is 16 so so far didn't really match so we back to the the root which is three back to the the root which is three so then basically what we're going to do so then basically what we're going to do is we're going to backtrack is we're going to backtrack because we exhaust all the options for because we exhaust all the options for three now we backtrack to five three now we backtrack to five and then five we have another path which and then five we have another path which in this case we have two in this case we have two right so in this case we're going down right so in this case we're going down the right side so now we have two the right side so now we have two so two plus five is seven right we're so two plus five is seven right we're we're traversing we're traversing we're iterating uh reverse or reverse we're iterating uh reverse or reverse order so order so now we have two plus five uh does not now we have two plus five uh does not equal to equal to eight so continue two plus uh 5 plus 10 eight so continue two plus uh 5 plus 10 in this case is 17 in this case is 17 so that's not equal to 8 so we're just so that's not equal to 8 so we're just going to continue to go down the right going to continue to go down the right side side because the left side is null and we because the left side is null and we have one have one right so now we have 8 right we have 8 right so now we have 8 right we have 8 here here and then we just increment the counter and then we just increment the counter by one but you get an idea right by one but you get an idea right basically we're just basically we're just have a list that we're just going to have a list that we're just going to keep track keep track that we're gonna pass down and then try that we're gonna pass down and then try to iterate to iterate starting from the last element to the starting from the last element to the first element to get the the sum first element to get the the sum if if our current sum is equal to target if if our current sum is equal to target sum then we just increment the counter sum then we just increment the counter by one otherwise we're just going to by one otherwise we're just going to and then we're just going to traverse and then we're just going to traverse the left side do that for search for the the left side do that for search for the left side left side and then do that for search right side and then do that for search right side and then after come back and then after come back we want to remove that we want to remove we want to remove that we want to remove the last element that we add the last element that we add added on to the list and then we're just added on to the list and then we're just going to continuously going to continuously do that until we traverse each and every do that until we traverse each and every single node in our um single node in our um in our binary tree right so in our binary tree right so in this case what we're going to do is in this case what we're going to do is we're just going to have a basically have a deferred search method right dfs it takes the root node and it also has a list empty list so far like at the beginning we have an empty list and we also going to have a we're going to make the target sum in a global variable so that i don't have to pass that in and then after we're also going to have and then after we're also going to have a counter a counter which is a global variable so if we which is a global variable so if we found found a sum that has equal to the target sum a sum that has equal to the target sum then we're just going to increment the then we're just going to increment the count by one at the end the goal is we want to return the counter right so dfs is just there to traverse the the tree what we really want to return is the counter right so that's basically the idea of it so now let's try to which takes a tree node and as well as a list of integer which basically contains all the nodes value that we traverse right so in and then basically the base case here is and then basically the base case here is that if we found the root is null then that if we found the root is null then we can just return we can just return right so if root is null right so if root is null we can just return okay so that's our we can just return okay so that's our base case right so if root is null we base case right so if root is null we can just can just we can just stop searching uh down this we can just stop searching uh down this path path and then what we're gonna do is we're and then what we're gonna do is we're just going to just going to first get the um get the current note first get the um get the current note value added onto our list value added onto our list right and then we're just going to so right and then we're just going to so first we're going to add first we're going to add a current node's value onto onto the list onto a list then we traverse then we iterate the list backwards to get the current sum right so if the current sum so let's say the current sum is equal to target then we're just going to target some that we saved on in a global variable then we're just going to increment that by one you can run the counter by one i should say then what we're going to do is we're going to uh traverse the left side right we're gonna after we we iterating all the elements that we have on our list we're gonna traverse the left side towards the right side so traverse left traverse right and at the end when we when they coming back to this current level we're just going to remove the last element so remove the current element current node's value of the list right so those are the steps that we're going to going to write so basically add the current notes value onto a list basically it's pretty simple so let's add root.value right so adding the current notes value onto our list then we're going to start to iterate but first we're going to have a counter right so the current sum is zero we're starting to iterate starting from the last element so it's gonna be list dot size minus one i is bigger than or equal to zero so i minus minus so what we're gonna do is we're gonna iterate uh the list backwards and try to get the current cell right so um in this case current sum plus equal to let's get i which gets the current element so we're gonna uh get the current sum which is we're basically updating our current sum and then if the current sum is equal to target we're just going to increment the counter by one so counter plus plus right and then at the end what we're going to do is we're going to traverse focus on traversing the left so we're going to do a dfs rule.left and then the list current list that we have right and then we're going to do a dfs that right i'm gonna pass in the current list that we have after they're done they're coming back to this level we want to make sure we remove the current notes value off the list list.size minus one list.size minus one okay pretty simple uh now let's try to okay pretty simple uh now let's try to run the code run the code and let's try to submit and let's try to submit so as you can see it takes uh it's only so as you can see it takes uh it's only five percent five percent right so in this case because this right so in this case because this solution give us the n square time solution give us the n square time complexity complexity so what we need to do is we need to so what we need to do is we need to focus on how we can be able to improve focus on how we can be able to improve this time this time uh solution down to a linear time uh solution down to a linear time complexity complexity by using a hashmap so let's take a look by using a hashmap so let's take a look let's take a look at how we can do that let's take a look at how we can do that to solve this problem using a linear to solve this problem using a linear time complexity time complexity um we're going to use something called um we're going to use something called prefix up so a couple of videos ago i prefix up so a couple of videos ago i made a video called made a video called leeco 560. in that video i talked about leeco 560. in that video i talked about how we can use a prefix sum to solve a how we can use a prefix sum to solve a problem problem to reduce the time complexity down to a to reduce the time complexity down to a linear uh init array basically the linear uh init array basically the prefix sum prefix sum is there to get the sum of a sub array is there to get the sum of a sub array between between i and j right it's between a i and j right it's between a um between a specific um index um between a specific um index to a specific index in the array right to a specific index in the array right so we can be able to do that using a so we can be able to do that using a hash table hash table using a hash map so how can we solve using a hash map so how can we solve this current problem so to solve this this current problem so to solve this problem what we need to do problem what we need to do is let's say we have 10 is let's say we have 10 5 and 3 right so let's say we have a 5 and 3 right so let's say we have a tree node tree node 10 5 and 3. 10 5 and 3. so what we need to do is we can use a so what we need to do is we can use a hash table right just like how we talked hash table right just like how we talked about in the about in the 560 lego problem we're just going to 560 lego problem we're just going to [Music] [Music] have a hash map with zero right zero is have a hash map with zero right zero is basically the basically the the prefix sum by default in this case the prefix sum by default in this case uh prefix sum of zero appear once uh prefix sum of zero appear once and uh what we're gonna do is we're and uh what we're gonna do is we're going to have 10. so the target sum going to have 10. so the target sum in this case is eight right so target in this case is eight right so target sum sum is eight in this case is eight in this case 10 has a prefix sum of 10 10 has a prefix sum of 10 right so the the the sum right so the the the sum of the current node uh of the current node uh current sub sub node right subtree in current sub sub node right subtree in this case this case just this node right here has a sum of just this node right here has a sum of 10. 10. so in this case we say 10 up here once right this is the prefix sum this is the prefix sum and this is how many times that prefix sum appeared we're just going to get the current prefix sum right remember 10 is the prefix sum of this element right here so we're just going to get the 10 the prefix sum minus 8 the target sum we want to see if two contains in the hash table in this case we don't right so we don't have a prefix sum like we don't have a prefix sum of two in the table so we did not have a previous sum of two then we move on to the next node in this case we have 15 right so the prefix sum of this node is going to be 15 which appear once and then we also have which appear once and then we also have a perfect sum of 18 but 15 minus a perfect sum of 18 but 15 minus the target sum which is seven seven does the target sum which is seven seven does not have it in the table not have it in the table so we're just going to move on to the so we're just going to move on to the next iteration the next node next iteration the next node now we have 18 which only appear once now we have 18 which only appear once so in this case we have 18 right 18 so in this case we have 18 right 18 minus 8 it's target sum is equal to 10 minus 8 it's target sum is equal to 10 10 10 is the prefix sum we know that is the prefix sum we know that 10 exists in the table so 10 exists in the table so we're just going to uh increment the we're just going to uh increment the counter by one because we found a counter by one because we found a a a path it makes sense because we have a a path it makes sense because we have five five and three here right so basically the and three here right so basically the goal is we want to store the prefix sum goal is we want to store the prefix sum in our table and uh if we have the c if in our table and uh if we have the c if we get a we get a get a current notes prefix sum minus the get a current notes prefix sum minus the target sum target sum we want to see if the the if that we want to see if the the if that if that difference right the the prefix if that difference right the the prefix sum container sum container table if it does that means we have a table if it does that means we have a path that means we have a path that means we have a a node that has a prefix sum that is a node that has a prefix sum that is equal to that equal to that right so let's say we have something right so let's say we have something like this right we have like this right we have and the target sum is going to be and the target sum is going to be negative one negative one now we have to um now we have to um like we have to do the same thing right like we have to do the same thing right so in this case one so zero and one so we do the same thing so no one has a prefix sum of one so then we're just going to get the prefix song for this album right here which is one right one appear once so the prefix sum of this element is one minus this element we get two do we see two in the table in this case we don't so we continue going down the left side right so in this case we have left side uh we have negative two and uh now we have negative two but the perfect sum for this element is going to be negative two plus one which is going to be negative one and appear once so this is where this zero right this element right here come into play so basically we have previous sum of negative one minus the target sum which is negative one which give us zero and do we see zero in our table in this case we do because uh for at the beginning we have a prefix sum of zero the current sum we when we before we start it was zero so zero appear once right so in this case we have zero there in this case we're just going to um increment the counter by one and then we're going to start a backtrack right we're going to move on to the next uh path so we have to delete this element uh if we don't delete it if we go back to a different path right then we have negative three negative three has a prefix sum of negative uh yeah yeah basically negative two um in this case negative two minus negative one has a pre um has a [Music] has a prefix sum of negative one and we see that negative one is appeared in table so that does that will not give us a correct answer so what we need to do is we need to before we backtrack right before we backtrack to the root node we have to delete or not delete but like decrement it decrement this element by one if this element is equal to one we can just delete it in our off our table so that we're not getting the incorrect answer right so those are the coordinate cases that we considered let's take a look at how we can do this in code so to do this in code uh basically i delete some of the our code our existing code and we're just going to add a hash table right a hash table uh hash map there and the key is going to be the prefix sum and the value is going to be how many times that prefix sum appear so we're just going to pass in the um zero because in this case the current prefix sum is zero right and we also have to have a hashmap.put zero up here once so the prefix sum for zero appear once right so that's basically the uh the the general idea of our main function so let's define our dfs so this is the current sum right the current sum uh in this case what we're going to do is same thing we're going to have our base case so if root is null we're just going to return and then what we're going to do is we're uh current sum right because we're now uh current sum right because we're now at the at the different level we're just going to add different level we're just going to add the current sum the current sum uh add uh current sum is equal to uh add uh current sum is equal to current sum plus the root of value current sum plus the root of value then after we update our current sum then after we update our current sum right we're just going to um check to right we're just going to um check to see see if this current uh we're just going to if this current uh we're just going to get the get the uh we're just going to see if the hash uh we're just going to see if the hash table table contains current sum minus the target contains current sum minus the target sum sum right check if current sum right check if current sum minus target minus target exists in the table if it does we're exists in the table if it does we're just going to just going to increment the counter based on the increment the counter based on the hashmap.get current sum minus target hashmap.get current sum minus target right and uh then what we're going to do right and uh then what we're going to do is we're going to start to traverse the is we're going to start to traverse the left side and we also have the traverse the right and we also have the traverse the right side but before that we also have to do side but before that we also have to do something very important something very important we have to make sure that we're getting we have to make sure that we're getting the currents on we have to update the currents on we have to update the table with the table with our current sum our current cell right our current sum our current cell right and then after we're done traversing the and then after we're done traversing the left and the right we're going to remove left and the right we're going to remove the current sum the current sum of the table of the table okay pretty simple so let's start start okay pretty simple so let's start start to implement this in code to implement this in code and basically we're updating the current and basically we're updating the current sum so current sum plus sum so current sum plus plus equal to real value plus equal to real value and the current sum basically check c and the current sum basically check c if hash map dot contains key if hash map dot contains key current sum minus target so if it is current sum minus target so if it is then we know that we then we know that we have a path in your table so we're just have a path in your table so we're just going to increment the counter going to increment the counter based on how many times that prefix uh based on how many times that prefix uh current that that's that prefix current that that's that prefix sum appear in our in our table or in our sum appear in our in our table or in our tree tree so hashmap dot get current sum minus target right and then we're just going to start to update our table now with our current sum so in this case if hashmap dot put right in this case there could be a right in this case there could be a situation where this current sum already situation where this current sum already appeared in our table so we want to make appeared in our table so we want to make sure that sure that um that hashmap um that hashmap git right so hashmap dot gets sorry git gets or default current sum plus one okay once we update our table we traverse left to right dfs root dot left we're gonna pass in the current sum right we already update our current soft so and now the most interesting part is to and now the most interesting part is to delete the current sum of the table delete the current sum of the table and basically if we found that the and basically if we found that the current sum current sum right so hashmap get current sum is equal to one we can just delete delete that element off of the otherwise we're just going to say otherwise we're just going to say hashmap hashmap dot put current sum dot put current sum hash map dot get current sum hash map dot get current sum right minus one we're just going to right minus one we're just going to decrement the time slip here decrement the time slip here by one so basically that's just the idea by one so basically that's just the idea of the code of the code and uh let's try to and uh let's try to run the code okay let's try to submit and here to see we have a six set so this is how we solve this problem using a linear time complexity | 2024-03-22 12:15:54 | 437 | [Java] Leetcode 437. Path Sum III [Binary Tree #14] |
|
BRE0mWrwRE4 | uh this question is fine followers come so you need to write Curry for each user so you need to write Curry for each user return number of the following so this return number of the following so this is pretty straightforward so is pretty straightforward so um so uh if you look at the user ID so um so uh if you look at the user ID so there are some repeated users so just there are some repeated users so just just making sure you use screw by so you just making sure you use screw by so you only show once and then the number of only show once and then the number of the users you just have to count the the users you just have to count the difference so they are actually too difference so they are actually too unique right unique right and there are actually one for user ID and there are actually one for user ID one for uh use either one is zero so one one for uh use either one is zero so one one two so if this is what one two so if this is what uh if this is what uh two zero something uh if this is what uh two zero something like this and it should be one like this and it should be one all right so uh this is not possible you all right so uh this is not possible you are not following the person with the are not following the person with the same user for send follow ID right this same user for send follow ID right this is not possible you have you have to is not possible you have you have to follow a different follow ID right on follow a different follow ID right on the same user so uh they're just the same user so uh they're just uploading select the user ID uploading select the user ID comma account this thing comma account this thing follower ID this is going to be about rename as from so uh return the result table order by so uh return the result table order by user ID right so I was user ID right so I was almost missing this keyword almost missing this keyword so uh while I was it should be okay so uh while I was it should be okay right as on it all right so uh just making sure you know Group by order by this thing so | 2024-03-20 17:43:47 | 1,729 | LeetCode 1729 | Find Followers Count | Count distinct | Group by | Order by | SQL |
|
TEAYxdIK2-8 | Ki Welcome Everyone Today In This Video Bihar Ko * Solid Code Is Question And The Question Is Ko * Solid Code Is Question And The Question Is Number Complaint In This Number Complaint In This Question Will Be Given And Enters In Important Where To Written Question Will Be Given And Enters In Important Where To Written And Judgment And Judgment Is So Is So Ki Sapoch Bhi Hai And Input S5 Subah Hai 2012 Ki Sapoch Bhi Hai And Input S5 Subah Hai 2012 Flat Like Flat Like Flat Like representation for 5 This diabetic patient who is the digits in the representation of nine days to return the number of sleeping mother in 200 Answer will be id ok so basically but you can think of that you Pimentel Pimentel Pimentel St And You Can Sleep Obs In You Can St And You Can Sleep Obs In You Can Calculate The Calculate The Recent Years By Converting Balance Recent Years By Converting Balance Representation To Decimal Form But This Representation To Decimal Form But This Process Will Much Less Than Two Years Ago We Process Will Much Less Than Two Years Ago We Used To Operator Operator Operator Which You Can Find On Your Used To Operator Operator Operator Which You Can Find On Your Keyboard 6 Long Something Like This Key And Keyboard 6 Long Something Like This Key And What is and operator basically which raw two What is and operator basically which raw two same numbers will be 2000 but or of different number one can find another same numbers will be 2000 but or of different number one can find another number subscribe will tell number subscribe will tell you how to find the number one five we can do you how to find the number one five we can do it is the representation of it is the representation of that ific force with all weapons with inputs that ific force with all weapons with inputs that ific force with all weapons with inputs without the roof i one spoil basically one will be slip 2010 will be clip 212 david morning using that roadways vacancy lipid calculators number two how to calculate this number i morning from for the country number is the number of you the number 24 you the number 24 you the number 24 number will be an answer okay so let's ride download and a superstar for what will need this half long long and half long long and I answer is vansh and I answer is vansh and that reach and face name is that reach and face name is 110 boil 110 boil phone par phone par afan afan This is trying to calculate number of This is trying to calculate number of birds and according to that I am trying to calculate a answer ok so by the way that country number will be that country number will be bluetooth race to the power number of birds bluetooth race to the power number of birds phone number of the bits Will be the Will be the Will be the tourist to the power then will be tourist to the power then will be 98 98 but will be one 0f sector-21 format will get this the students and time train tourists to the students and time train tourists to the power number of birds minus one ok so let's go back to the co dog show the wild wild The world you and multiply The world you and multiply an answer film to is time basically in an answer film to is time basically in calculating power that n that i will divide android oil subscribe divide android oil subscribe only android one and only android one and it should avoid to ok to equal to that married wedding by to ok sleep nowhere calculated tourist co power number But reduced by But reduced by But reduced by this vansh n every answer will be a this vansh n every answer will be a roar off roar off if input if input thanks thanks 157 157 ok so let's try ok so let's try running state ok ok hai so hai so aaj disawar number complement aaj disawar number complement problem-solving jor jor can be pretty woman problem-solving jor jor can be pretty woman After the times so thank you so much and After the times so thank you so much and figures in next video bye-bye | 2024-03-18 10:57:22 | 476 | Number Complement | LeetCode 476 | XOR | C++ | Shortest Solution |
|
GZh85DkyB5k | hi today we're solving this code number 144 binary tree periodic traversal and 144 binary tree periodic traversal and basically we are given a root node of a basically we are given a root node of a binary tree and we're supposed to travel binary tree and we're supposed to travel seeds uh using the pre-order method and seeds uh using the pre-order method and this is an easiest problem and the only this is an easiest problem and the only problem the only hiccup for this problem the only hiccup for this particular problem is just the fact that particular problem is just the fact that in the follow-up it asks us to solve it in the follow-up it asks us to solve it iteratively as opposed to solving it iteratively as opposed to solving it recursively and that's what the solution recursively and that's what the solution we're actually going to be showing today we're actually going to be showing today so basically when you have the root node so basically when you have the root node in this case root node here is one and in this case root node here is one and and you are trying to Traverse it by and you are trying to Traverse it by using the pre-order method it means they using the pre-order method it means they are going to be getting the leftmost are going to be getting the leftmost number or let me spoke to you or number or let me spoke to you or leftmost node rather on the binary tree leftmost node rather on the binary tree or you can't go any left then you go or you can't go any left then you go right so for instance here we have one right so for instance here we have one and then the leftmost part of one is not and then the leftmost part of one is not expecting to nonsense there's no other expecting to nonsense there's no other um number there and then we have a shoe um number there and then we have a shoe by the right then two on the left has by the right then two on the left has three but on the right it has no so if three but on the right it has no so if there's no number there's no number attached to his friend let's assume that attached to his friend let's assume that the next number there is no right so um the next number there is no right so um in this particular case first of all we in this particular case first of all we print the root node at this point which print the root node at this point which is one that's correct and then after is one that's correct and then after painting the root node we try to print painting the root node we try to print the leftmost node at this point level the leftmost node at this point level slope is null so we don't print that slope is null so we don't print that right so we move to the right most one right so we move to the right most one instead and we print the rightmost node instead and we print the rightmost node which is now currently the roots so we which is now currently the roots so we print two and then after printing to print two and then after printing to we're supposed to print the leftmost we're supposed to print the leftmost node at this point and at this point node at this point and at this point that's straight so we print three and uh that's straight so we print three and uh and because three at this point does not and because three at this point does not have like a leftmost node and also have like a leftmost node and also doesn't have like a right nose node so doesn't have like a right nose node so we move back to two and two also doesn't we move back to two and two also doesn't have like a writing smooth as well so have like a writing smooth as well so that's it it ends there that's it it ends there so that's basically if we don't have so that's basically if we don't have like a node let's just return like an like a node let's just return like an empty array as well so let's actually empty array as well so let's actually get on to solving this get on to solving this for the solution I'm proposing we're for the solution I'm proposing we're going to use a stack right so let's going to use a stack right so let's assume that this is actually the assume that this is actually the question the problem we are trying to question the problem we are trying to solve by this example right here and for solve by this example right here and for the root node of course we have one and the root node of course we have one and then in our stack we start with one then in our stack we start with one obviously now when we get the value at obviously now when we get the value at node right we get the rightmost value node right we get the rightmost value first I don't get the rightmost value we first I don't get the rightmost value we add we change that we take this the add we change that we take this the value out of this stack and replace it value out of this stack and replace it with the value in the rightmost part with the value in the rightmost part while we're going to start with the while we're going to start with the right mode before the left mode this is right mode before the left mode this is because when we're going to be taking it because when we're going to be taking it out of the stack we want to get the left out of the stack we want to get the left first before we get the right right so first before we get the right right so to take no in this instance and then as to take no in this instance and then as we put in law in this instance and then we put in law in this instance and then the next one is going to be two right the next one is going to be two right now that we have to I know of course now now that we have to I know of course now output we're going to have one already output we're going to have one already saved here right now when we pop up this saved here right now when we pop up this next value at this point the next value next value at this point the next value is going to be 2. so when we take off is going to be 2. so when we take off two we're going to take off two we have two we're going to take off two we have two here right now we we have to replace two here right now we we have to replace this two that we've taken now with the this two that we've taken now with the rightmost value now at this point two rightmost value now at this point two does not have any rightmost value so so does not have any rightmost value so so it's just going to be null right and it's just going to be null right and then we have the leftmost then we try to then we have the leftmost then we try to get the leftmost value of it that's this get the leftmost value of it that's this dot left of this particular node so dot left of this particular node so which is at this point is straight so which is at this point is straight so now that we're done with this we can now that we're done with this we can just put this through in our output as just put this through in our output as well now that I've done that we have we well now that I've done that we have we don't have um we don't have any meaning don't have um we don't have any meaning values to go back into our stack right values to go back into our stack right now I'm going back into our stack we get now I'm going back into our stack we get the last one last value at this point the last one last value at this point which is straight now when we get three which is straight now when we get three reject if it has left me if it has reject if it has left me if it has rightmost value it doesn't have right rightmost value it doesn't have right nose value objective translated then it nose value objective translated then it does not have left value so we just put does not have left value so we just put string inside there string inside there just put three inside there and since it just put three inside there and since it um let's actually get to solving it I um let's actually get to solving it I think that when we actually when you think that when we actually when you actually see me try to implement it to actually see me try to implement it to understand a little bit more what I'm understand a little bit more what I'm trying to say so trying to say so you have to order Driver cell access for you have to order Driver cell access for them to declare our variables of course them to declare our variables of course in which case we output you against an in which case we output you against an entirely and then what I'm going to work entirely and then what I'm going to work on at the end at the end once we turn on at the end at the end once we turn out out then once you check for some things then once you check for some things price stands for where is for like price stands for where is for like instances where we don't have anything uh mcre right now we're going to of course I forgot that you said you are going to use a start to start this way here this video now because of the fact that there isn't a start to to represent this it means that our space complexity is going to be of all it's going to be o of n because in this case every single value is going to go into every single value in this tree is going to go into the stack right and then uh time complexity is going to be o of n as well because we're going to run through every single item in the in the tree right so like you said earlier I'm going to be starting with the rules now as far as the stock zero you just want this zero you just want this right so that's basically so what we'll right so that's basically so what we'll be doing here and the first place is be doing here and the first place is that I just have we're going to declare that I just have we're going to declare the node which is just going to be only the node which is just going to be only pop off this is transforming the last 10 pop off this is transforming the last 10 out of out of the stack at every point out of out of the stack at every point and then when we take this off you just and then when we take this off you just have to check if this note that if it's have to check if this note that if it's not more right if it's up now then we not more right if it's up now then we just push just push the value inside output here and then 11 with that because we want to oh we're done with that like I said we're going to take the leftmost right first of all we'll take the right most value right and push it into this stack and left so that's why we have to pop in and left so that's why we have to pop in we get the left face before we get the we get the left face before we get the right I hope that makes sense oh I'm so sorry but I've been stacked up oh I'm so sorry but I've been stacked up the push the push stop it here we are pushing the value in the node yep and then now we can submit our yep and then now we can submit our solution and solution and um yeah that's it and because because of factorizing Stack our memory doing this so well but our runtime is better than 96 percent of the submissions um so yeah that's how you solve that please don't forget to like And | 2024-03-21 12:45:11 | 144 | Leetcode 144: Binary Tree Preorder Traversal |
|
obueB6niKaE | See, in this video we will see lead code 1 2 4 8 In the previous video, we had 2 4 8 In the previous video, we had asked a question, the question was sub ars sum asked a question, the question was sub ars sum = I told you that when the restrictions which are there become = I told you that when the restrictions which are there become strict on all ars, okay then the strict on all ars, okay then the old sliding window which we old sliding window which we approach was they don't do that okay we approach was they don't do that okay we did that in this the prefix even okay the did that in this the prefix even okay the prefix even that we did that in this and has prefix even that we did that in this and has you used in okay that's a good thing you used in okay that's a good thing now we have a question 1248 count now we have a question 1248 count number of nice sabridge good is speaking to number of nice sabridge good is speaking to you you you You have to find out the sabri which has exactly odd numbers. Now see here also the restrictions have been stated exactly and it has become strict. Okay, so like we did the last problem, we Okay, it is Okay, it is Okay, it is saying that saying that exactly the odd numbers should be reverse, exactly the odd numbers should be reverse, good in your morning, like here in front of good in your morning, like here in front of you, there are exactly three odd numbers in it. Okay, three odd numbers in it. Okay, as you will see now, this is one, there are three more as you will see now, this is one, there are three more numbers in this, there are 11 and there is only one in this. numbers in this, there are 11 and there is only one in this. numbers in this, there are 11 and there is only one in this. is no one else, see, this is not this, this is also not this, and one Puri, and this is this, this is not this, we are doing this too. Do you understand, so what will we do like we did in the previous This is how we do it, This is how we do it, This is how we do it, if you have not seen the previous question, if you have not seen the previous question, then see it, okay, it is very then see it, okay, it is very important, your eyes will be opened, important, your eyes will be opened, so what did I take, RS, so what did I take, RS, what will be our result and we will return it in the end, what will be our result and we will return it in the end, okay. okay. okay. tell you, let's take a variable which will keep the count of how many odd numbers have been added till this number. I call it current like in the previous question we prefix How much percentage I was How much percentage I was How much percentage I was putting till here in time and current, in this way putting till here in time and current, in this way what will we do here, how many what will we do here, how many votes till here, how many votes from here, okay, votes till here, how many votes from here, okay, so how can we make it 4 inches, okay, so how can we make it 4 inches, okay, name forint i numbers here name forint i numbers here name forint i numbers here will keep adding to the current plus it is equal tu i modulo you now look at it like this, what does it mean that if that number is even then it will add zero, if it is odd then it will add one to it, okay okay okay and Okay, we will store it also, Okay, we will store it also, Okay, we will store it also, okay, and we will also store the current, okay, and we will also store the current, brother, okay, we will store the brother, okay, we will store the value of one current, which is okay, brother, value of one current, which is okay, brother, see how many times two odd numbers have come. see how many times two odd numbers have come. And how many numbers have you killed, came here And how many numbers have you killed, came here and came here, okay, that's why two and and came here, okay, that's why two and two, okay, if it has come twice, then I two, okay, if it has come twice, then I store it, I am okay, I lie down store it, I am okay, I lie down depending on the first, okay and I would depending on the first, okay and I would dot pat. dot pat. dot pat. What will you put in the current? So take the value of the old one plus one. At this time, I am here. Okay, on this one, the old one, you have come once and here you have come twice. If he had already got If he had already got If he had already got gate and defaulter, then what gate and defaulter, then what was that value. Okay, if the current is not there, then zero and plus was that value. Okay, if the current is not there, then zero and plus one are okay, brother, so one are okay, brother, so we are storing this thing in the map, one more number has come once, we are storing this thing in the map, one more number has come once, okay two odd. okay two odd. okay two odd. and the number have come once, okay race, how many times have the numbers come, twice, like this, how many times have the numbers come, once, do the odd numbers, how many times have they come, do the times, Okay brother, our map has been made, Okay brother, our map has been made, Okay brother, our map has been made, now you will see that K = 3, this is ours, now you will see that K = 3, this is ours, how can we do it, please pay attention, how can we do it, please pay attention, if okay, now we saw in the last video if okay, now we saw in the last video that I now give one dal in dot pat zero, that I now give one dal in dot pat zero, okay i.e. okay i.e. okay i.e. prefix and whatever is there must have been zero. Okay, K = 3, so let's see the example, look at this one, look carefully at this one, okay, what is here, this is our answer because there are three more numbers in it, And even if we have this current, And even if we have this current, And even if we have this current, then let's say by doing this, it's okay, then let's say by doing this, it's okay, what else is up to this, it's three, okay, so if you what else is up to this, it's three, okay, so if you pay attention, if someone is pay attention, if someone is doing more with the key and number like here. doing more with the key and number like here. doing more with the key and number like here. okay, that's the mines and mines will exist in our map. Okay, like what's here 3 - 3 0 has existed. Okay, let's take another example like this. Mother, I am here, I Okay, I am here, okay, Okay, I am here, okay, Okay, I am here, okay, no problem, if there is any sub error no problem, if there is any sub error here, okay, here and doing it, then doing here, okay, here and doing it, then doing minus three, what will exist minus three, what will exist in our map or in Israel, okay, so what is it, in our map or in Israel, okay, so what is it, here is one one a here is one one a here is one one a one time, okay, so what will we do here, we are yes plus this is equal to map dot get and see the defaulter, I had studied in depth in the last question, that is why And by And by And by default, if mines had come default, if mines had come then how many times they had come, we will keep adding them, then how many times they had come, we will keep adding them, okay, this is it, let's remove this one, it is accepted, I submit, okay, accepted, I submit, okay, time complexity is big of others and space time complexity is big of others and space too. too. too. good, you will get the link to the next video, starting | 2024-03-19 17:14:43 | 1,248 | LeetCode 1248 Solution in HIndi | Count Number of Nice Subarrays Solution in Hindi |
|
lpH0BYId0YA | So in this video the problem of soil is the test element against quality of Africa and test element against quality of Africa and so in this brings your so in this brings your energy in the tenets and number of dry is energy in the tenets and number of dry is basically a number which we want to return from direct which basically a number which we want to return from direct which is the largest number is the largest number presented here so let's presented here so let's presented here so let's Sri Lanka Only Nikalna Bulk Rajesh Number Three Se Limit Third Largest Element Of Second Plant 3D 400 How To Prove His Point For The Basic Approach Will Be Sorted Different Sources Of Sexual And Effective On How Should You Can Return Time Tax Can do something so let's get Can do something so let's get Can do something so let's get started in descending started in descending order something like 6532 and world want to order something like 6532 and world want to return like and share number's element which you want to return like and share number's element which you want to return person minus one return person minus one index index is okay so if I want to short in ascending is okay so if I want to short in ascending order one order one 's good luck r the element 's good luck r the element 's good luck r the element return with me and midcap index like RNA 6 and this three sued in 3D from this 0123 alerts for is the largest third statement from this approach cooperative and went to consider using and taylor swift not very often solution free consider and se z900 gift veer se z900 gift veer se z900 gift veer vs triple vs triple Scent Scent Back Slow 210 Hit The Root Of Alarm Liquid Back Slow 210 Hit The Root Of Alarm Liquid Will Always Be Smallest Element Which Will Will Always Be Smallest Element Which Will Present And Scent It All Its Population Have Present And Scent It All Its Population Have Benefited From Active Voice Alarm Benefited From Active Voice Alarm Distant Places For Giving Dark And Bloody Distant Places For Giving Dark And Bloody Mary Celeste One And Logistics 800m G Mary Celeste One And Logistics 800m G Temple Also Always Present Temple Also Always Present Temple Also Always Present one topic Must be reserved Right up to top 10 How they can stop this A few hints only 10 search operations are involved Which time Can always protect The citizenship for mini And you can find a small age limit Period Is Is Is Simrely Information And Action Operation Is Simrely Information And Action Operation Is Midnight Sach Log In Time For This Is The Time Midnight Sach Log In Time For This Is The Time Complexity Of Operations Happy To Complexity Of Operations Happy To Receive Phone How They Can Be Started Receive Phone How They Can Be Started Constructing Is White Is I Will Release Constructing Is White Is I Will Release Patience 3215 Six Inch And West's Is Three Patience 3215 Six Inch And West's Is Three Left Side Of Directors Left Side Of Directors Left Side Of Directors Not Exist For Why This Way Small For Example Giver That 13 Subir Vibes Should Problem Adding All The Elements Of Obscuritism Sanjay Vyas Travel Through The Worst In The How To Do Lagi Formation In Find Nothing But Na Dhari Arrangement Of That sagotra to of That sagotra to of That sagotra to of turmeric and cost will consider only number of turmeric and cost will consider only number of film indian army co film indian army co 108 ambulance first sweet shop alstom 108 ambulance first sweet shop alstom and indicative price and 2001 solve world and indicative price and 2001 solve world will put this in itself something like this sochna pathak will put this in itself something like this sochna pathak etc names 2.2018 difficult expensive and etc names 2.2018 difficult expensive and daddy come dot daddy come dot 202 side 202 side 202 side Question Second Step Three Love And Approved And Researchers Have Not Even Suhaagsays Prithvi Par Something Like This [ 12345 See No Veer That Soft Forget What Will U Will 12345 See No Veer That Soft Forget What Will U Will Remove The Evil Elements And Remove The Evil Elements And Content Should Be Placid Over 12.5 Liquid Subscribe 15 Ki salary bhi hua hai wake up to 6 years will pop up to android something like this reel the 5th and 6th and order last element college limit for b id will have two of three from all hit songs person something like this after 242 242 242 status of electronics and it is the cost of earring swift on the other hand in the wedding elements of [ __ ] and building itself very first flowers is hair soft private security association's secretary and 200 grams pims 200 grams pims 200 grams pims members of the city have seen how they can do this in code and for how they can find team district president elements present 100 and 200 test and also PM something like this 500 600 Largest is that in the beginning it is always for the person point out prescription limit site Soviet plant genetic elements of this up that 24 how they can find the air filter element frequency identification for this next day whole coriander fennel notification Neetu Paul's limits to And Laptop This Is Your Favorite And Laptop This Is Your Favorite And Laptop This Is Your Favorite Place From 1.5 Lakh Awadhesh Mishra Shoaib Squidoo 5530 Element Persona The Limit For B Id M Id To Welcome Teacher Info Point And Click On Subscribe To Subscribed Nahi Kiya Subscribed Nahi Kiya In The Size Of Adi Displaced And In The Size Of Adi Displaced And In The Size Of Adi Displaced And r's person withdrawal that how to the element managing editor use this point time not fixed MS Word Delhi Delhi toe return back toe top spot in vitamin A a | 2024-03-22 10:38:39 | 215 | Kth largest element in an array | Leetcode 215 | Interview Preparation Series | Heap |
|
yHx2TyGRqQM | Hello Hi Everyone Welcome To My Channel It's All The Problem Record Beans Message All The Problem Record Beans Message Containing Letter From The 2G Is VPN To Dr Containing Letter From The 2G Is VPN To Dr To Numbers Using Following Mapping 102 And To Numbers Using Following Mapping 102 And Monitor 2016 Dholi Digits Determine Total Monitor 2016 Dholi Digits Determine Total Number Of Best Dancers Guarantee 232 Sorry Number Of Best Dancers Guarantee 232 Sorry For Example A Number Of Different Video subscribe and subscribe the Video then subscribe to the Page if you liked The office number to protection and fix so how many different office number to protection and fix so how many different ways we can decorate ways we can decorate software like just do and 126 rates on software like just do and 126 rates on electric to and subscribe our Now to that and 2 and six and Mrs in are subscribe subscribe 60000000 the father with 20 have anything e have only from 126 fans this is not fair continue with speech scandal ki ek solution record Like first to leave Like first to leave Like first to leave one and contacts from where they can continue withdrawal one and contacts from where they can continue withdrawal inches and 2.1 a dhoye inches and 2.1 a dhoye or channel subs shyam subscribe and share 1090 can only to which is this point to the number 90 subscribe skin example will oo will start from zero for string in The village quote 1 one will increase in next and you will welcome like to web tracking tool and lag increase 2nd id 1st 2nd id 1000 to two to that from i2i plus to the number dial that from i2i plus to the number dial serving this garlic and to 2610 veer they continue serving this garlic and to 2610 veer they continue Like this is question and share this will Like this is question and share this will not go 800002 MP3 Subscribe to Lohe 4021 channel Like not go 800002 MP3 Subscribe to Lohe 4021 channel Like comment comment share and subscribe so totally different subscribe and this length and question spring which means the process all districts will have evil Please like character in Please like character in Please like character in power string airtight indexes 0 power string airtight indexes 0 conductor middle menu subscribe to be lit conductor middle menu subscribe to be lit character vaikuntha 2G switch to return 180 character vaikuntha 2G switch to return 180 subscribe my video and implement food subscribe my video and implement food and only in the court has been and only in the court has been implemented and see the number of problems implemented and see the number of problems for education say you in Thursday Subscribe to A Tragedy Languages Don't Like It Is That Case Will Just Return Because They Are Able To Liquid Android Is 000 Clear To Convert Into What We Do We Need To Calculate Total Channels Subscribe To My Channel Will First Effigy Thursday In List List List That Form i2i Plus Two Software Testing That Form i2i Plus Two Software Testing Two Character Effect Is Less Than Or Equal Two Character Effect Is Less Than Or Equal 226 History And Inco 2016 Patience With 10 226 History And Inco 2016 Patience With 10 Seconds To Like Subscribe Of Forests Seconds To Like Subscribe Of Forests And Villages Return Of The Rebel To Subscribe To 200 Hair Wear Checking Wear Checking Wear Checking Two Characters Add Vegetables Sentence This Like Two Characters Add Vegetables Sentence This Like Share Plus One Should Be Length Garlic And Share Plus One Should Be Length Garlic And Equal To Short Length Lee Thursday Equal To Short Length Lee Thursday A Fetish Walking And Wear Getting Correct A Fetish Walking And Wear Getting Correct Answers Left Side To Randi Custom Test Answers Left Side To Randi Custom Test Cases Like 00000000 subscribe and Cases Like 00000000 subscribe and subscribe this Video give time let's subscribe this Video give time let's understand or 21 to 0512 two or 21 to 0512 two which hair on this I will welcome to and here I will be which hair on this I will welcome to and here I will be less 3 less 3 because of this lighting also points to because of this lighting also points to entertain hair will get is 30 feet for entertain hair will get is 30 feet for list that opposition 2010 problem android list that opposition 2010 problem android Problems in Life with Three Idiots Problems in Life with Three Idiots Problem Ghrit Problem Problem Problem Ghrit Problem Problem Solution for You Can Do It Use This Map of Solution for You Can Do It Use This Map of Interior to Interior to Mind J Remedy Solution of the Already Mind J Remedy Solution of the Already Calculated Is a Problems and Calculated Is a Problems and Newspaper Encounter Dam Against Here This Newspaper Encounter Dam Against Here This is Practice Na Android Map Not Born is Practice Na Android Map Not Born In solution of birth problem content that I In solution of birth problem content that I will return in Indian villages and effective way will return in Indian villages and effective way yes where is the content type hair that surgical see it's working now they can that surgical see it's working now they can submit this and see the problem will not Start the time forget his Start the time forget his Start the time forget his leg return from fear and its leg return from fear and its effect on returning festival solution sid effect on returning festival solution sid time complexity of dissolution subscribe time complexity of dissolution and complexity and space complexity you can also change this like withdraw pf withdraw pf office late and later office late and later office late and later Care If Life Is My Channel Thank You Will Return To Defeat After Is Not No Loot For Using Chief Secretary Dare And Written Over Subscribe To Subscribe To Nifty 126 Laptop Patience The College Nifty 126 Laptop Patience The College Girl Don't Forget Disting Ayush Tourist Girl Don't Forget Disting Ayush Tourist Again Soft Classification Solve This Again Soft Classification Solve This Problem In Water Supply And Suez Religion Problem In Water Supply And Suez Religion Subscribe No Problem Amazon Placid At Subscribe No Problem Amazon Placid At Home And Share And Subscribe Like Share And Subscribe Fast Track Court Se 1000 V Way Will Fast Track Court Se 1000 V Way Will Proceed From 2ND Year Will Update Character Proceed From 2ND Year Will Update Character 90 512 MB This Hair Pack To 90 512 MB This Hair Pack To 90 512 MB This Hair Pack To British Midlands And One For This And Answer In Number Of Veg Sandwich Subscribe Button Subscribe My Channel Subscribe Like Share And Different Only Boys Channel Tarf Quarterly Spider Live With His Big Space User Free Variables And Solve This Five Five Five percent problem but this comment section percent problem but this comment section thanks for watching | 2024-03-20 13:00:10 | 91 | Decode Ways | decode ways | leetcode 91 | top down bottom up dp |
|
tuF8YhCuxo4 | hello everyone so now we are solving 433 which is minimum genetic mutation it which is minimum genetic mutation it says that you are given a string given says that you are given a string given two Gene strings start Gene and engine two Gene strings start Gene and engine and the gene bank which is basically an and the gene bank which is basically an area of this written the minimum number area of this written the minimum number of mutations needed to mutate star okay of mutations needed to mutate star okay so so um I just solve this sum which was I um I just solve this sum which was I think Word ladder yeah where this is think Word ladder yeah where this is pretty similar to that where you are pretty similar to that where you are just supposed to generate this word just supposed to generate this word using the bank of words and you're using the bank of words and you're supposed to generate this and yeah it supposed to generate this and yeah it was pretty similar but I think the only was pretty similar but I think the only change here is that your given choice is change here is that your given choice is acgt so basically in Word ladder you acgt so basically in Word ladder you could just generate all the 26 could just generate all the 26 possible characters but here you have possible characters but here you have only four so it's very similar to that only four so it's very similar to that if you guys want to refer you guys can if you guys want to refer you guys can check that out video out but I'm just check that out video out but I'm just gonna go ahead with the solution here I gonna go ahead with the solution here I think that should be the solution for think that should be the solution for this as well where I'll have a queue this as well where I'll have a queue which will take in strength which will take in strength right and this queue is basically keeping track of all the possible combinations which are valid I'll have a hash set of right and this is basically a hash set right and this is basically a hash set for the bank for the bank foreign [Music] I'll also have a hash set which will keep track of my scene strings right and then I'm gonna do Q dot add start point right and what I'm going to do is while my queue is not empty right so what I'm gonna do is um since I need to return number of steps I need to keep track of steps so in steps will be one initially uh uh I'm gonna start from here right and at the end of this I'm gonna do steps plus plus so it's kind of like a BFS search and every time I do I'm gonna do Q dot po this is going to be my current string and I'm gonna check if this dot equals my and G if that's the case I'm gonna return steps straight away otherwise I need to generate all the possible values so what I'm going to do is for okay so I need the possible characters um let's say possible um let's say possible cash is equal to new calorie of cash is equal to new calorie of a a C C G and T okay G and T okay uh okay and then what I'm gonna do is uh okay and then what I'm gonna do is for care C4 for care C4 and I start oh I can resize J starting and I start oh I can resize J starting from 0 J less than from 0 J less than current dot length J plus plus uh what I'm going to do is I'm gonna use cap C and possible cats string new word oh current dot substring oh current dot substring of 0 comma J of 0 comma J Plus J Plus 1. right J Plus 1. right and then I'm gonna check if this new and then I'm gonna check if this new word is in my bank word is in my bank so if that's a valid word and and my C dot contains this new word actually should not contain this new word then I'm gonna add it to my queue and then I'm gonna add it to my scene as well yep and it's at the end of this I still don't have it that means it's not possible okay so I failure okay so I messed up okay so I failure okay so I messed up something let's see so I did a start something let's see so I did a start Gene with steps one I'm gonna start with Gene with steps one I'm gonna start with this I'm gonna pull that out if that this I'm gonna pull that out if that equals my engine inside that's the end equals my engine inside that's the end otherwise I'm gonna go over my current otherwise I'm gonna go over my current length and for all the possible cares length and for all the possible cares oh okay let's see yes that's the reason I'm just making sure it's this able to add uh yeah and then let's let's see oh oh so I'm taking it everything and then I'm not sure if this is how you do dot to string dot to string let's add C I think maybe that's the let's add C I think maybe that's the reason I'm not sure reason I'm not sure okay that's not the reason so what's happening here let's print a new word is it even able to produce the okay let's see the words that we are okay let's see the words that we are generating thank you a c g t okay the first word is changes okay so it's able to generate the new watch so that's not the issue uh oh I see because my bank set has not been populated for for oh string bankset.addex yeah that makes sense bankset.addex yeah that makes sense let's see let's see okay so output is two right now oh let's okay so output is two right now oh let's see why see why so I start with steps of one I pull that so I start with steps of one I pull that out out if everything works fine I guess it has to start at zero and then if I add I do one and then yeah this makes sense okay let's submit yeah this works yeah so the basic idea is similar to the word ladder I didn't explain this much but if you guys want to check that out that's the video you guys should look up and yeah in terms of time and space complexity that this one is tough which I don't know so basically it's like you go over these are the number of nodes that you are going to go over right so each in word is a word so the graph would be o of n Square where n is the number of words in the bank and then to generate each of these Banks it's going to be Dot M where m is basically the length of your board so the length of your start G so that's your space and time complexity uh but yeah I mean this is kind of tough but yeah all right so that's it thank | 2024-03-22 12:05:45 | 433 | 433. Minimum Genetic Mutation |
|
J5IIH35EBVE | hello thanks for checking out this video in today's video we'll be looking at in today's video we'll be looking at lead code problem number one five lead code problem number one five eight eight the sum of all odd length eight eight the sum of all odd length sub arrays the problem description says sub arrays the problem description says given an array of positive integers we given an array of positive integers we want to calculate the sum want to calculate the sum of all possible odd length subarrays of all possible odd length subarrays we're told that a subarray is a we're told that a subarray is a contiguous subsequence contiguous subsequence of the array and we want to return the of the array and we want to return the sum sum of all odd length subarrays so here's of all odd length subarrays so here's the first example that they've given us the first example that they've given us we have an array of length we have an array of length five with the numbers one four two five five with the numbers one four two five and three and three and just to clarify real quick what a and just to clarify real quick what a sub array is sub array is a sub array means we're going to start a sub array means we're going to start at some number maybe i start at one at some number maybe i start at one and we're gonna move in the right and we're gonna move in the right direction direction and end at some other number maybe i'll and end at some other number maybe i'll end at two here end at two here the sub array here would be one four the sub array here would be one four two we have to include all numbers from two we have to include all numbers from one to two and you one to two and you you just choose some number and then go you just choose some number and then go right right and end at some other number i could and end at some other number i could also if i have wanted to also if i have wanted to start and end at five this would produce start and end at five this would produce the sub array just five it's different the sub array just five it's different from a subsequence because in a from a subsequence because in a subsequence subsequence you can start and end at some value but you can start and end at some value but you don't need to include every number you don't need to include every number in between in between i like to just be very sure that i know i like to just be very sure that i know that we're dealing with a sub array or a that we're dealing with a sub array or a subsequence because there's been a few subsequence because there's been a few times where times where i thought it was a subsequence that i i thought it was a subsequence that i was looking at and i made the problem was looking at and i made the problem more difficult than it needed to be but more difficult than it needed to be but in this problem we are looking at in this problem we are looking at subarrays now i've gone ahead and subarrays now i've gone ahead and written out all the possible sublim sub written out all the possible sublim sub sub-arrays sub-arrays with their lengths so in this purple with their lengths so in this purple column on the left column on the left i have all of the sub-arrays of length i have all of the sub-arrays of length one one there's one four two five and three and there's one four two five and three and then likewise in the second column then likewise in the second column i have all the sub-arrays of length two i have all the sub-arrays of length two and then there's the sub arrays of and then there's the sub arrays of length three four and five length three four and five but we're really only interested in the but we're really only interested in the odd length sub arrays odd length sub arrays so the odd length sub arrays are one so the odd length sub arrays are one three and three and five we don't really care about two and five we don't really care about two and four because those sub arrays are all four because those sub arrays are all even length so what i'm going to go even length so what i'm going to go ahead and do ahead and do is look at this first number one and is look at this first number one and look at look at for every odd subarray how many times for every odd subarray how many times does it appear does it appear it appears once in the purple it appears once in the purple once in the blue for length three and once in the blue for length three and then one then one in length five so it appears three total in length five so it appears three total times times how many times does four appear in an how many times does four appear in an odd length sub array odd length sub array it appears once on the left it will it appears once on the left it will appear appear twice actually for a twice actually for a subarray of length three and then it subarray of length three and then it will appear will appear once for a sub-array of length five so once for a sub-array of length five so it actually appears it actually appears four times now we'll look at how many four times now we'll look at how many times does two appear times does two appear it appears once for a it appears once for a sub-array of length one for a sub-array sub-array of length one for a sub-array of length three i actually have of length three i actually have these three here so i'm up to four these three here so i'm up to four already already and then i have one more here for and then i have one more here for length five so this actually appears length five so this actually appears five times and then if i look at how five times and then if i look at how many times five appears it appears many times five appears it appears once two three once two three four times and then how many times does four times and then how many times does three up here three up here one two three one two three it appears three times it appears three times now i want to go ahead and multiply now i want to go ahead and multiply these together these together if i do that i'll get 3 16 if i do that i'll get 3 16 10 20 and 9 10 20 and 9 and if i add up these five numbers and if i add up these five numbers together together i will get 58 which is the expected i will get 58 which is the expected answer now look what we did there we answer now look what we did there we looked at looked at how many times each number appears in an how many times each number appears in an odd length sub-array odd length sub-array and then however many times they appear and then however many times they appear in that length in that length sub-array we just multiply it by that sub-array we just multiply it by that number and that's how we get the answer number and that's how we get the answer the hard part of this problem really the hard part of this problem really becomes calculating how many times becomes calculating how many times each number appears in these odd length each number appears in these odd length sub arrays sub arrays so let's try to figure out how that can so let's try to figure out how that can happen if i take a step back and i and i look at for whatever number is at index 0 i'm going to write the indices above if i look at for index zero how many if i look at for index zero how many subarrays total not not just odd length subarrays total not not just odd length subarrays but sub arrays total subarrays but sub arrays total index zero appears at i can calculate index zero appears at i can calculate that that by taking the sub arrays with that and then multiply it with that and then multiply it by the sub arrays that end by the sub arrays that end with that so here's here's what that means let's say for example you have city a you have city b and you have city c there are two paths from a to b and there's three paths from b to c if i asked you how many paths total unique paths can we are there from a to c that go through b here's how you could do it you could just count them you could say well there's one if i go from the top to the top that's one i could go top to the middle that's two i could go the top to the bottom that's three i could also go from the bottom to the top that's four i could go from the bottom to the middle that's five or i could go from the bottom to the bottom and that's 6. another way to calculate that is there's two choices from the left-hand side and 3 on the right there were two choices that end at city b and three choices that start at city b so it's kind of a similar similar process here we're going to look at for each index how many sub-arrays start at that index and how many sub-arrays end at that index here's how we can do that so for index zero how many sub-arrays i look at how many sub-arrays start with i look at how many sub-arrays start with zero index zero there are zero index zero there are five there's the one of just the number five there's the one of just the number itself itself zero i could go zero to one zero one two zero i could go zero to one zero one two zero one two three and zero one two zero one two three and zero one two three four so there's three four so there's five and how many end at index zero five and how many end at index zero there's just one there's the index there's just one there's the index of just itself when i of just itself when i is one if i'm looking at index one how is one if i'm looking at index one how many many subarrays start with one subarrays start with one the answer is four there's one two the answer is four there's one two one two three one two three four one two three one two three four that's it if i look at how many end that's it if i look at how many end i have two choices it could be zero one i have two choices it could be zero one or just one and you might be able to see or just one and you might be able to see the pattern the pattern that in general the that in general the number of subarrays that start from your from whatever index you're looking at is n minus i where n is the length of the array and i is whatever index you're looking at so if you look at the case when i was zero if we take five minus zero we get five or in the case when i is one five minus one is 4. if we look at how many sub-arrays end with that value it's i plus 1. but if we look at this when i is 0 we have one choice when i is one we have two choices and that just and if we multiply these together we get and if we multiply these together we get the total the total number of sub-arrays not the odd length number of sub-arrays not the odd length but the total number but the total number then the next problem becomes well if i then the next problem becomes well if i know the total number of sub-arrays how know the total number of sub-arrays how can i calculate the odd can i calculate the odd well if i know the total and i cut that well if i know the total and i cut that in half in half just take the total number and divide by just take the total number and divide by two two that'll almost give me the answer it that'll almost give me the answer it actually sometimes will give me the actually sometimes will give me the answer answer because i know that half of them will be because i know that half of them will be even even and half of them will be odd however and half of them will be odd however in the case where a number appears in an in the case where a number appears in an odd number of subarrays odd number of subarrays there will actually be an extra odd one there will actually be an extra odd one so here's what that means let me scroll so here's what that means let me scroll up a little bit up a little bit we saw here that for the number one we saw here that for the number one on at index zero it appeared on at index zero it appeared in three in three odd sub-arrays but only two even odd sub-arrays but only two even sub-arrays sub-arrays the total number of sub-arrays it the total number of sub-arrays it appeared in was five appeared in was five so it appeared in five total when we cut so it appeared in five total when we cut that in half that in half we get two for rounding down we get two for rounding down so that's how many even sub arrays it so that's how many even sub arrays it appears in appears in if if n is odd the number of sub arrays if if n is odd the number of sub arrays it appears in is odd it appears in is odd then i have to add one more then i have to add one more to to take into consideration that extra to to take into consideration that extra odd sub-array it appears in odd sub-array it appears in so if i add one to this it would be so if i add one to this it would be three one index zero the number one three one index zero the number one appears in three odd sub-arrays appears in three odd sub-arrays it appears in five total it appears in it appears in five total it appears in two two even and three odd so you have to pay even and three odd so you have to pay attention now attention now to if the the total number of sub-arrays to if the the total number of sub-arrays is odd or even i'm going to do is odd or even i'm going to do one more example now with our original one more example now with our original input using our formula we're using input using our formula we're using where we look at how many sub-arrays where we look at how many sub-arrays start and end at a particular index start and end at a particular index and then how many total sub-arrays and then how many total sub-arrays include that and then the odd just so include that and then the odd just so you can see how the numbers start to you can see how the numbers start to play in play in so if i look at index zero again i think so if i look at index zero again i think we we already looked at this we we already looked at this there are five sub-arrays that start there are five sub-arrays that start with index zero with index zero there's one that ends with it for a there's one that ends with it for a total of five total of five looking at index one there are four looking at index one there are four that start with it i'm getting four by that start with it i'm getting four by plugging one plugging one into our formula of five minus into our formula of five minus i the end would just be i the end would just be two for a total of eight two for a total of eight for index two i would get three for index two i would get three subarrays subarrays that start three sub-arrays that end that start three sub-arrays that end and nine total sub-arrays including and nine total sub-arrays including that include the value two for index that include the value two for index three i would have three i would have five minus three which is two that start with it and i would have four that end with it for a total of eight subarrays including index three and for index four i would get one sub-array that starts with it five that end with it for a total of five and to calculate how many odd sub-arrays i divide by 2 and if it's if my total is odd i add 1 if it's even i leave it so 5 divided by 2 in in java would be 2 but because 5 was odd i add 1 for 3. 8 divided by 2 is 4 and that's even so i can leave it 9 divided by 2 would also be 4 but because 9 was odd i add one to get five i already did eight and i knew that was four and i already did five and i knew that was three and if you look at these numbers down here they exactly match what was up here when we brute forced it and just listed all of the sub-arrays so this is a very fast way to look at how many times a particular index appears in all odd length sub-arrays once we know this we just multiply this odd value however many odd sub-arrays contain the value by the value itself and keep track of that sum now let's take a look at the code for how this can work first thing i want to do for the code is create a variable to hold on to the sum and that at the end here i'll make sure to return that i also want to have a variable to keep track of the length of the array just this is going to make the code look cleaner later on now what i want to do is iterate through every index of this and i want to keep track of how many end and i want to keep track of how many end here here and start here so remember the formula and start here so remember the formula for how many for how many sub-arrays end at this index sub-arrays end at this index it was i plus 1 and then how many start it was i plus 1 and then how many start here here is n minus i for the total it's just the and then finally the odd are going to be and then finally the odd are going to be the total divided by two and then the total divided by two and then there's a quick check i got to do there's a quick check i got to do because if the total was odd then i have to add one to the odd sub-arrays that this value appears in finally i can add to my result the multiplication of how many odd sub arrays this value is and times the value itself and if i go ahead and do that let's see 58 just like we expected and if i submit then we get a successful run if we look at the runtime complexity real quick for time and space if we look at just time first here there is one for loop which will run n times and all these operations inside of the for loop are constant time meaning this is o of n time and space complexity we're just using variables we don't declare any extra memory so the space is constant space thank you for watching the video if you have any questions please comment and if you have any video suggestions please let me know and i'd be happy to make one | 2024-03-21 14:42:30 | 1,588 | Sum of All Odd Length Subarrays | LeetCode 1588 | Explained and Java Code |
|
6AWcGwB9Pgw | Hello everyone welcome back today we will solve another new problem which is the daily problem of lead code the problem which is the daily problem of lead code the problem is very problem is very interesting you will get to learn a lot interesting you will get to learn a lot here so let's start let's here so let's start let's understand what the problem statement understand what the problem statement is saying to us ok and its is saying to us ok and its is saying to us ok and its white board, so what the problem statement is saying is that you are given two strings, okay, we have two strings, okay, we have two strings, and s, okay, we have one s, right, one Characters for order are unique Characters for order are unique Characters for order are unique means one order is given to us like for example means one order is given to us like for example this is ok one order is this is ok one order is given one order right one order is given given one order right one order is given and one s is given then all the characters in this order and one s is given then all the characters in this order are unique ok are unique ok And this s is our input array, the And this s is our input array, the question is saying that we have to sort this input array question is saying that we have to sort this input array which is AB CD in such a way which is AB CD in such a way that the order given is that the order given is maintained, okay for example if we maintained, okay for example if we We have A B C D Right A B C D We have A B C D Right A B C D Right A B C D And what is the order Right A B C D And what is the order given to us Order is equal to c B C B A given to us Order is equal to c B C B A So when we sort then among the first of these So when we sort then among the first of these characters C should come first then characters C should come first then B should come right B should come right B should come right rest of the characters should come ok so this is what the question demands right then you will see the output is yours this is the second also let's see Edge Edge Edge is ok, what is the edge and output string? is ok, what is the edge and output string? Our A B C D is again the same. A B C D. Right, so Our A B C D is again the same. A B C D. Right, so what we will do first is that we will first look at A which is the input array which is the ordered array. Okay, so look at A which is the input array which is the ordered array. Okay, so b should come first. b should come first. b should come first. is b, then we have put b first. After that, c should come. If there is c in our string, then we have put c on the second position. If there is a in our string, then we have Given and finally f is Given and finally f is Given and finally f is not in our g is not there so not in our g is not there so we have put whatever is left so b c ad and this is the we have put whatever is left so b c ad and this is the output Right this is the output So we will output Right this is the output So we will see two methods Right we will see two methods First see two methods Right we will see two methods First method which is inbuilt sort function in it method which is inbuilt sort function in it method which is inbuilt sort function in it try to solve this by passing a Comparator and second, which we just did here when we were doing the dry run. Basically, we saw a pattern. We will solve this question with the help of that pattern. Okay, so let's start. First of all what we will do is like we know STL gives a function t e sort ok sort gives a function what we have to pass inside it is array right array start and array end end and Also we Also we Also we can pass That is the Comparator Function Okay, can pass That is the Comparator Function Okay, so what we will do today is we will try to so what we will do today is we will try to create a new Comparator Function Create a new create a new Comparator Function Create a new Comparator Function which will sort Comparator Function which will sort as we want according to the logic that we have written in this comparison. as we want according to the logic that we have written in this comparison. We are We are seeing this right that if I put this seeing this right that if I put this map, whatever unique elements are there in this map, map, whatever unique elements are there in this map, right, they will always be unique elements, right, they will always be unique elements, keep their positions, right and tell the compiler to keep their positions, right and tell the compiler to put the one whose position is less first, you put the one whose position is less first, you and whose position is later. and whose position is later. and whose position is later. keep it last, then our question will be solved. Correct, let's try like we have made a map. Right, we have made a map. A is ok, what is there in it? What is the position of B? What is the position of B? Right? B's position has become Then what is the second m m off cc Then what is the second m m off cc Then what is the second m m off cc What is the position of C What is the position of C Also became What is the position of C What is the position of C Also became zero right after that m of A A of zero right after that m of A A of A Its position will be Sorry Its position and A Its position will be Sorry Its position and its position has become Two Correct And then m its position has become Two Correct And then m of last What of last What of last What FA's position is done Tha and FG Okay FG what will be its position done Then tomorrow now what will we say to the Comparator that sort our array so array what is our A A B C D This is A B C D This is A B C D This is our input er A B C D So when it goes to sort our input er A B C D So when it goes to sort right, you know that always right, you know that always two characters or two elements are compared two characters or two elements are compared so first of all it will go to sort A. so first of all it will go to sort A. When it goes to sort A then When it goes to sort A then What we will say is that first of all look at the position of a. What we will say is that first of all look at the position of a. We have found the position of a from our map. We have found the position of a from our map. Okay, so what will be the position of a? This will be your position. What will be this position of yours? We have seen that this is the position of 2. Okay, so this is the position of yours. Then we gave it. your position. What will be this position of yours? We have seen that this is the position of 2. Okay, so this is the position of yours. Then we gave it. your position. What will be this position of yours? We have seen that this is the position of 2. Okay, so this is the position of yours. Then we gave it. fine. We have seen how much is the position of B. The position of B is zero right. So whose position is coming first in this, that of B. So we will return our function from our basic Comparator, what is a? Lesson B is right: Is a smaller than b? If a is smaller than b then a will come first otherwise b will come first and based on this our entire function becomes ready, ok just by doing this we Let's go tomorrow and Let's go tomorrow and Let's go tomorrow and see the answer to the question. How is your night? see the answer to the question. How is your night? If I do CPSPS then If I do CPSPS then basically I have solved this question, I just basically I have solved this question, I just did it now. If you want to see, then you did it today did it now. If you want to see, then you did it today itself. itself. 11 is okay, 657, so basically. 11 is okay, 657, so basically. 11 is okay, 657, so basically. Whatever we saw on the white board, we placed the same thing here, then first iterated an order, we kept the position of the order in the map, okay, then we sorted and in the sort, we put the Comparator function. By By By default, give a value to A position and B position. default, give a value to A position and B position. Right after that, find the position of A. Right after that, find the position of A. Find the position of B. And in the end, Find the position of B. And in the end, what do you do? In the end, check whether A position what do you do? In the end, check whether A position is B position or not. Just to is B position or not. Just to check this. check this. check this. okay, let's run it and see, basically it will pass because I have done it in the morning itself, okay, so that's all, right, that's all and I hope you have understood this problem, The approach is The approach is The approach is what I was seeing in the solution section what I was seeing in the solution section right, I was seeing it in the solution section and I right, I was seeing it in the solution section and I also found it very interesting right so let also found it very interesting right so let me explain this to you too so me explain this to you too so basically when we were doing this dry run basically when we were doing this dry run right when we were doing this dry run right when we were doing this dry run right when we were doing this dry run making this order, were we following the map in the map, what is the position of B, what is the position of C, what is the position of A for example let's say right what is this order A & G This is A & G This is A & G This is our order and this is our string A B our order and this is our string A B CD Correct This A B CD So what we will CD Correct This A B CD So what we will do is make a map Let's make a map Let's say do is make a map Let's make a map Let's say A Okay and the input array will A Okay and the input array will keep their positions Basically we will keep their counts keep their positions Basically we will keep their counts Positions otherwise A How many Positions otherwise A How many Positions otherwise A How many came once, okay, so it's counted, one more from Let's, here's one more A from Let's, here's P, okay, m of B, what happened m of B, your one right m of B is also done. Your one write is done then m off s done your one write then m off what is f m off f done your one write sorry m off f no what was d my bat ok input array we are taking One more a we One more a we One more a we added by ourselves so m a now it's done ok cool added by ourselves so m a now it's done ok cool now what we will do is add it to whatever now what we will do is add it to whatever input whatever order is the array we input whatever order is the array we will delete it right so if I put a for loop okay then what is the will delete it right so if I put a for loop okay then what is the first character? first character? first character? I will see if there is B in my map. Right in my map, B is m of B E E 1. If it is there, then I can clearly see how much is it once. So I, the answer is one, for example, let's Equal to mt Equal to mt Equal to mt string is ok one answer equal to mt string is done string is ok one answer equal to mt string is done right if now right if now I will append as many times as b in the answer I will append as many times as b in the answer then see the first character for then see the first character for example aa equal to two is now zero aa equal example aa equal to two is now zero aa equal to what is zero right then to what is zero right then to what is zero right then happened? We have appended here as many times as there was B in the answer, so the answer is now, your B was there only once, then I became one second character. We saw what CC is, Hey, Hey, Hey, yes, C is there once, as many times as C is there, yes, C is there once, as many times as C is there, append it in the answer. Fine, now I have come, append it in the answer. Fine, now I have come, your two are fine, I have come, now two have been your two are fine, I have come, now two have been seen. We have seen the second character of C. Sorry, we have seen. We have seen the second character of C. Sorry, we have seen the second character. We have completed the order of A. seen the second character. We have completed the order of A. seen the second character. We have completed the order of A. see that, okay, then A, we saw what A is in our map, yes, how many times is it there, twice, get A appended twice, okay here and add I plus, then this is done, Thr, then we saw the third character, what? A is there, we don't have A, then there will be nothing here. Is G not in our input array, G is also not there, then nothing will happen. Okay, B C A, we have missed something. Yes, correct then finally what is So, we have done this process, So, we have done this process, So, we have done this process, okay, we have done this process, we have done this process, okay, we have done this process, we have done this process, now whatever is left in the map, you now whatever is left in the map, you append it here and this will be your append it here and this will be your answer, okay, so this was also a good approach, so answer, okay, so this was also a good approach, so I am the same. I am the same. I am the same. and this guy did the same, created an order map, okay, storing the frequency of the string in math, whatever was the input array, okay, kept its frequency, then iterated over the order, and as orders are being Took out the count, kept on Took out the count, kept on Took out the count, kept on adding plus plus to that count on the answer and adding plus plus to that count on the answer and finally, whatever was left in the map in the end, it is finally, whatever was left in the map in the end, it is ok, kept on adding plus plus on it here, ok, kept on adding plus plus on it here, that was it, ok, so this is also a good that was it, ok, so this is also a good approach, you guys can try this too. approach, you guys can try this too. I have not tried this right but you I have not tried this right but you can do it, this will be homework for you, okay, so that's all can do it, this will be homework for you, okay, so that's all for today and I hope for today and I hope you have understood this solution, if you have you have understood this solution, if you have any problem with this then please let us know in the comment any problem with this then please let us know in the comment section. section. section. one problem in the next video thank you so | 2024-03-21 17:01:54 | 791 | Custom Sort String | LeetCode 791 | C++ |
|
kDvNzEgGTuQ | what is going on everyone so today we are going to be looking at are going to be looking at lead code number 207 lead code number 207 it is called course schedule and it is called course schedule and i have to say this one is a pretty i have to say this one is a pretty tricky one it's tricky one it's it's it's working off of some patterns it's it's working off of some patterns and i think the key to this question is and i think the key to this question is really recognizing really recognizing the patterns that are that this question the patterns that are that this question is asking is asking and once you understand that it's and once you understand that it's actually not too bad actually not too bad it i see how this can be solved very it i see how this can be solved very very quickly very quickly in like a matter of minutes just by in like a matter of minutes just by understanding what this question is understanding what this question is really asking really asking so let's go through it we'll go through so let's go through it we'll go through it step by step it step by step okay so the prompt there are a total of okay so the prompt there are a total of num courses you have to take labeled num courses you have to take labeled from zero from zero to num courses minus one some courses to num courses minus one some courses may have prerequisites for example if may have prerequisites for example if you take course zero you take course zero you have to first take course one which you have to first take course one which is expressed as a pair is expressed as a pair zero one given the total number of zero one given the total number of courses and a list courses and a list of prerequisite pairs is it possible for of prerequisite pairs is it possible for you to finish you to finish all courses okay so example one we have all courses okay so example one we have an input of num courses two an input of num courses two and prerequisites of one and zero and prerequisites of one and zero the output is true there are two total the output is true there are two total of two courses to take of two courses to take if you take course one you should have if you take course one you should have finished course zero so it is possible finished course zero so it is possible okay so basically what it's saying is okay so basically what it's saying is that to take course one we have to take course zero but because there is nothing in here that that says anything about course zero we can assume that we can take course zero without any prerequisites here we have the example number two we have two courses and we have a prerequisites to take course one we have to take a prerequisite for course of course zero but to take course zero we have to take a prerequisite of course one and so this is impossible to take because essentially we're getting a cycle to take one we have to be able to take zero and to take zero we have to be able to take one so there's no way to enter into this into this into this graph really and that is really the key to this is understanding that this is a graph problem and what it's really asking is is there a cycle in the graph for this there's no cycle because there's nothing that we have to take in course zero and so we can take course zero and we can get to course one by going through zero but here there's no way because there is a cycle that's happening here and the other thing that they kind of tripped me up was is it undirected or directed and it is a directed graph and and once once that was understood that this is asking that that we have a directed graph and we want to figure out is there a cycle in this directed graph once that connection is made this problem can be solved very quickly and again if if uh if if if if you're not clear on how directed undirected graphs work i highly recommend checking out introduction to algorithms it's a really thick book um but the graph section is is quite comprehensive and there's a lot of patterns in there that i think are really important to just to have down pat that way when you see these types of problems you can just pull from those patterns and you don't have to think too much about it it's really the only thinking that really needs to be done is what pattern is this question asking underneath so if we're dealing with a graph problem and we are trying to detect a cycle then we want to use a depth first search traversal and we want to turn this input first thing we want to do is basically turn this input into an adjacency list so let's go and do that we can do const build adjacency list and again this is it's good to just kind of have these helper functions memorized that way you don't have to think too much about it so with the building adjacency list we're going to have n which is the length and then the edges okay and then what we're going to do is we're going to create our adjacency list so we can do adjacency list of length n and what we're going to do of length n and what we're going to do is set every single one of those edges is set every single one of those edges to an empty array to an empty array okay so all we're doing is we're okay so all we're doing is we're creating an empty array of size creating an empty array of size n and each element in that array we're n and each element in that array we're putting in a brand new array it's not putting in a brand new array it's not the same array it's the same array it's a totally new array that's that's linked a totally new array that's that's linked to a different part in memory to a different part in memory and it's important that that the array and it's important that that the array is that because if you put the same is that because if you put the same array in every element array in every element you'll get a lot of bugs okay so what you'll get a lot of bugs okay so what we're going to do now is we're just we're going to do now is we're just going to iterate over the edges so we'll going to iterate over the edges so we'll do let okay and then what we want to do is we okay and then what we want to do is we want to pull out our source and want to pull out our source and destination destination out of the edge okay and now what we want to do is because this is a directed graph to the destination now if it was to the destination now if it was undirected then we would mirror this undirected then we would mirror this we would we would have an adjacency list we would we would have an adjacency list and we would put in our destination to the source but we don't want to do that because this is a directed graph return our adjacency list return our adjacency list okay so that will that will essentially okay so that will that will essentially convert convert this list of edges into an adjacency this list of edges into an adjacency list list it'll just go ahead and build that in it'll just go ahead and build that in adjacent list adjacency list adjacent list adjacency list and if we look here we can see when we and if we look here we can see when we pull out this pull out this edge we're going to basically pull out edge we're going to basically pull out this one and this this one and this zero the one here is going to be the zero the one here is going to be the source source and the destination is going to be this and the destination is going to be this zero zero so in the index of one so in the index of one of our adjacency list we're going to go of our adjacency list we're going to go ahead and push in that zero ahead and push in that zero but the index of zero is going to be an but the index of zero is going to be an empty array and so again empty array and so again we're looking for cycles so let's just we're looking for cycles so let's just take a look here take a look here we have an input of n equals we have an input of n equals 2 and then our pre-rex 2 and then our pre-rex is going to be let's take a look here is going to be let's take a look here it's 1 and 0. 1 and 0. okay and so what we're doing here is we're creating an array of length two so zero one those will be the and what we're doing is we're going and and what we're doing is we're going and taking one taking one and we're pushing in zero and then in zero there's nothing there to push in so we just have an empty array and if we look at this as a graph we can see that there's no there's no cycle because 0 goes to nowhere and 1 goes to 0 but 0 doesn't go anywhere else so you can see that there's there's no cycle and that's really important for example the second input we see that it's 1 and 0 and 0 and 1. we see that it's 1 and 0 and 0 and 1. so let's just go ahead and so let's just go ahead and refresh this equals two and we have an input of equals two and we have an input of prereqs and one and 0. okay and one and 0. okay and so what all this is is we have edges and so what all this is is we have edges here and we want to create an adjacency here and we want to create an adjacency list out of this list out of this so here we have our so here we have our key essentially or the index key essentially or the index so we can have 0 and 1 and what this is going to map to is the so 0 is going to map to 1 and 1 here so 0 is going to map to 1 and 1 here is going to map to 0. and so you can see is going to map to 0. and so you can see here we have a cycle here we have a cycle if we go to 0 then this is going to go if we go to 0 then this is going to go to 1 and if we go to 1 to 1 and if we go to 1 this is going to go back to 0 and this is going to go back to 0 and there's no way to enter there's no way to enter enter into this and so we can't finish enter into this and so we can't finish all the courses because all the courses because there's a cycle okay so we build our adjacency list now what we want to do is we just want to do a depth first search traversal so we'll just call this has cycle and again this is a pattern so we take and again this is a pattern so we take in the node in the node take in the list we take in visited take in the list we take in visited and then this is this is a way to check and then this is this is a way to check for for cycles with with cycles with with depth first search directed graphs depth first search directed graphs it's it's uh it's something that you it's it's uh it's something that you wanna you wanna make sure you understand wanna you wanna make sure you understand beforehand and it's uh it's basically beforehand and it's uh it's basically edge classifications edge classifications is is is what you wanna look at and you is is is what you wanna look at and you wanna check if there's a back edge wanna check if there's a back edge if there is a back edge in a directed if there is a back edge in a directed graph that means that there's a cycle it graph that means that there's a cycle it means that there's a cycle in there if means that there's a cycle in there if you have a back edge you have a back edge and so you want to have basically a and so you want to have basically a variable variable that stores the arrival and departure and this is a time stamp so every time we we implement we hit this depth first search function so arrive at node so arrive at node increment that we want to set visited to increment that we want to set visited to true true of node true okay and then when we when we go through the entire we traverse the entire graph from that particular node we want to depart we want to increment and again if if you're not familiar with and again if if you're not familiar with this it's good to check out this it's good to check out introduction algorithms they go really introduction algorithms they go really in depth on edge classifications in depth on edge classifications directed versus undirected graphs and directed versus undirected graphs and and how to check for cycles and how to check for cycles and just just common things that you see and just just common things that you see that a lot of these questions kind of that a lot of these questions kind of are asking are asking underneath the hood and i think it's underneath the hood and i think it's really important because once you really important because once you understand how understand how to detect these patterns then a lot of to detect these patterns then a lot of these questions these questions aren't really that difficult you can aren't really that difficult you can just apply a very just apply a very basic template that you can have basic template that you can have somewhat memorized somewhat memorized okay and we just return we want to if we okay and we just return we want to if we go through all of this we want to return go through all of this we want to return false false okay and now we are just we're just okay and now we are just we're just basically basically implementing a very classic depth first implementing a very classic depth first search search so we'll do let neighbor so we'll do let neighbor of adjacency list of adjacency list node okay if not node okay if not visited neighbor then we're going to set okay and what we want to do now is we okay and what we want to do now is we want to basically call our recursive want to basically call our recursive call but we want to check call but we want to check is there a cycle search and we'll put in our neighbor we're traversing from the neighbor visited arrive depart okay now if if we have not visited we have to check is the departure did it depart okay so if equals zero then we also want to return equals zero then we also want to return true what we're basically checking here is if there's a back edge and now we just write our main function so first again this is following a very basic template and we're just going to build our graph so const list and we're going to put in our list and we're going to put in our number number courses prerequisites and then we want to create our visited and we want to have our arrive courses and our and we're going to set courses and our and we're going to set each one of these to zero okay whoops and we're going to do the and now we we again we just do a very and now we we again we just do a very common pattern here of doing a depth common pattern here of doing a depth first search first search algorithm graph traversal we do let algorithm graph traversal we do let vertex equals zero adjacency where vertex equals zero adjacency where vertex vertex is less than jsonc list.length is less than jsonc list.length plus plus and we're going to check plus plus and we're going to check if this is visited at vertex if this is visited at vertex if it's not visited then we're going to if it's not visited then we're going to go ahead and check if go ahead and check if this if we traverse from this node from this if we traverse from this node from this vertex this vertex vertex node uh is there a cycle vertex node uh is there a cycle as cycle that first search and we're going to start with our vertex our adjacency list are visited arrive and depart and if there's a cycle then that means it's false that means we cannot finish finish all those courses and if there's not a cycle then return true okay and that's it it's it's not too bad i mean one all we gotta really figure out with this question is is there a cycle and if there's a cycle then that means we cannot finish all these courses and if there's not a cycle that means we can and we have to also recognize that we're dealing with a directed graph a directed graph and we're just checking for cycles okay so let's run this oh i need to sign in let's see i can do that okay let's go ahead and run this and yeah and we have success and so that's it it's not too bad it's a good question to know you can see that it's asked at amazon facebook bike dance bloomberg and i had trouble with this question when i first encountered it even when i looked at the solution i still had a lot of issues getting my head around this and i think if if you're not familiar with breadth first search depth first search cyclic versus acyclic graphs this can be a tricky one and and i think one of the things that that is really important is when you're solving these lead code problems to really find the pattern solving these problems just as an island or independently can really be exhaustive because there's so many of these problems but many of them are following the same underlying pattern and so once those patterns can be recognized you don't have to think too much you can just solve these really really quickly and quite effectively so that is lead code 207 i hope you liked it and i'll see you on the next | 2024-03-22 09:59:14 | 207 | LEETCODE 207 (JAVASCRIPT) | COURSE SCHEDULE |
|
nqVbUdNqQlE | ajay ko [Music] hua hai [Music] Hello hello everyone welcome to new video in this video marriage ko * Discuss another problem from code problem problem problem life primary element primary element not primary ok not primary ok problem problem said that we are a -Matriculation will go and those who will subscribe us for Rs 500, 600, 800 to 1000, what will be the limits on the use of its primary dialogue, OnePlus 5 Plus 90, what will be the limits on the use of its primary dialogue, OnePlus 5 Plus 90, how long is it to subscribe to the channel, how long is it, we subscribe to the channel, how long is it, we are fine with both of these. this is getting repeated then this war was ours, subscribe our channel and subscribe and what is the problem, if we see examples in China, if we see, then in China, if we give examples, 123 123 45678910 That if That if That if we see here subscribe we see here subscribe scan center scan center 66 this is our primary element 66 this is our primary element primary primary six then this is the final of this six then this is the final of this subscribe to withdrawal 3417 and subscribe jhal if we see here these two said but rich then our how much of this is our 16 Which is our actual group why because first first first first number off number off daily or if our daily or if our we have to take both in this village and we have to take both in this village and after that it will be if you give it would be best to appoint if you give it would be best to appoint them number of columns for this He will He will He will be our answer to Dangal, be our answer to Dangal, so how should we approach this so how should we approach this position? First of all, we, the people who will position? First of all, we, the people who will watch New 2020, will not use it, will keep subscribing, then we will keep our subscribing, then we will keep our festival, Ghaghra Aai means zero, after that, life will be like that, so subscribe to us. subscribe to us. Use our I, that is, whatever is our Use our I, that is, whatever is our matrix M.Ed. Please forgive our I. matrix M.Ed. Please forgive our I. This is our primary diner, all will be covered in it. This is our primary diner, all will be covered in it. Now talking about us, here we have Now talking about us, here we have this our - this our - - - So here we have to do So here we have to do ours today. our first for our first for what we should read on our channel here what we should read on our channel here - If it works then we will get the full limit from this side also and we will get the full limit from the stress, so after this, if we What we have to do is What we have to do is What we have to do is after that we have to check whether our after that we have to check whether our Android is there or not so as soon as this follow is over Android is there or not so as soon as this follow is over we will get it, now we have to see if we will get it, now we have to see if our society if our Ghaghra our society if our Ghaghra 200 if it is ours then we will cut it and 200 if it is ours then we will cut it and return it to us return it to us return it to us - subscribe to appoint ka yaara milan hai our that accused points 152 in this lineage then this is what we will get appointed as a cover with attachment element appointed as a cover with attachment element then it happens here. then it happens here. then it happens here. here, we get this here, we have to subscribe 0210, first of all, we have to subscribe 0210, first of all, we have to hydrate and hydrate and finish both through our lips and lastly on Thursday, we will make our return, this and and if it is raw. Before we solve our problem, what would be our time Before we solve our problem, what would be our time complexity of free space complexity? Complexity is what will it become and our so we have also subscribed our channel for space, so we have also subscribed our channel for space, first of all we will do 2012 quarter then we will get this which will be the do 2012 quarter then we will get this which will be the number of problems of the matrix number of problems of the matrix because both are equal this is what we because both are equal this is what we And make a big village, let's and we will add this trick and element - - - element - - - Okay, we will add this, let's Okay, we will add this, let's put it in the village and like to finish, The time which The time which The time which is our matrix and the number of columns contains the is our matrix and the number of columns contains the content, still those number off, so what will we content, still those number off, so what will we do, we will look at it here, so do, we will look at it here, so now what will we do, we will check whether now what will we do, we will check whether our number off element our number off element Ghr divides, then what Ghr divides, then what will we do. will we do. will we do. what else will we do if there is such a person what else will we do if there is such a person who who subscribes to us like it will be first of all subscribe for the school first of all subscribe for the school and then submit it and come to see the result and then submit it and come to see the result and this is our submission. and this is our submission. and this is our submission. more, we used less space, so we just subscribe and see plus, so we can copy paste this thing, subscribe subscribe control plus, whenever we calculate our length. whenever we calculate our length. Used to do here we put parents after length function Used to do here we put parents after length function after that is equal to after that is equal to zero i labs zero i labs we submit hmm result we submit hmm result pathetic and saiya subscribe if now we see world cup final with inches now it We had to size the We had to size the We had to size the accused result accused result and this we did and this we did not have anything, subscribe, ran Shubhendu as subscribe, ran Shubhendu as we saw here, after that we set, we saw here, after that we set, if that discussion, then summing up two varna if that discussion, then summing up two varna system - million tonne tax 25 solution system - million tonne tax 25 solution system - million tonne tax 25 solution if you have any question then you can post it in the comment section below and we will reply to it. If you subscribe then you can join our channel, the link of which is in the description. Thank you | 2024-03-21 14:22:57 | 1,572 | 1572 Matrix Diagonal Sum | Zero to FAANG Kunal | Assignment Solution | Leetcode |
|
6EZ2qSHYz9g | hey Haleh let's talk about the Leslie coding challenge question removed linked coding challenge question removed linked list elements given a linked list we list elements given a linked list we want to remove the nodes of a given want to remove the nodes of a given value looking at the first example we value looking at the first example we have a linked list of seven notes and we have a linked list of seven notes and we want to remove those nodes with value 6 want to remove those nodes with value 6 that is to say if we exam this input that is to say if we exam this input linked list for every node we check its linked list for every node we check its value if it's Mario is not 6 we will value if it's Mario is not 6 we will definitely keep it in the outputting definitely keep it in the outputting linked list and after that we want to linked list and after that we want to make sure the next pointer in the next make sure the next pointer in the next pointer for this node is pointing to a pointer for this node is pointing to a node that's not 6 so if we're looking at node that's not 6 so if we're looking at the node 2 here the next pointer is the node 2 here the next pointer is pointing to a node of value 6 so we want pointing to a node of value 6 so we want to short it and we want to find the to short it and we want to find the first node of whose value is not 6 in first node of whose value is not 6 in the subsequent linked list we can use the subsequent linked list we can use another pointer to to find this and make another pointer to to find this and make sure that no 2 is actually pointing to sure that no 2 is actually pointing to that so so it's very clear that we can that so so it's very clear that we can solve this by two pointers so let's just solve this by two pointers so let's just demonstrate what the two two pointers demonstrate what the two two pointers Bureaus it is rows are one of the Bureaus it is rows are one of the pointer is pointing to the previous node pointer is pointing to the previous node that has the value that's not 6 then the that has the value that's not 6 then the next pointer should as the the job for next pointer should as the the job for this next pointer is to find the first this next pointer is to find the first no that's not this given value in the no that's not this given value in the subsequent linked list and once we find subsequent linked list and once we find those two the operation we do is to make those two the operation we do is to make sure that these two are connected sure that these two are connected together that is to rewire this link together that is to rewire this link link so no two will no longer points to link so no two will no longer points to note this value 6 but rather pointing to note this value 6 but rather pointing to this first node in the subsequent linked this first node in the subsequent linked list that has a value that's no 6 so list that has a value that's no 6 so that's pretty much the two pointer and that's pretty much the two pointer and while special cases that if they know if while special cases that if they know if the linked list starts with this note the linked list starts with this note value that we want to delete then well value that we want to delete then well we should use a sentinel node for this we should use a sentinel node for this papers so the previous starts with the papers so the previous starts with the sentinel so the next pointer will sentinel so the next pointer will identify the first node in the linked identify the first node in the linked list that's not a value that we wanted list that's not a value that we wanted to lead and establish a link like this as a result in the return statement we want to return the the note that this sentinel node is pointing to so that's the idea so we initialize a sentinel node the bottle doesn't really matter and the next pointer should points to head in the in the beginning in the beginning issue points to the given hetner and the previous is initially pointing out that sentinel and the next node is initially pointing at hand and we just kind of do keep traversing until this next pointer is it's pointing up it's no longer valid node that means the you know the we will terminate while this next pointer is pointing it's a no pointer so every iteration the job for the next pointer is to identify the first subsequent node that's not of this so if if they notice a note that we want so if if they notice a note that we want to delete we will advance advance it so to delete we will advance advance it so after this while loop we should position after this while loop we should position the next note into the next pointer the next note into the next pointer pointing out to the first a subsequent pointing out to the first a subsequent note that's of a value that we don't note that's of a value that we don't want to delete that's the time we want want to delete that's the time we want to rewire this so this comment the step to rewire this so this comment the step here after that we want to move the move those to alter or move them forward the situation here is that we could potentially have this next pointer pointing to a null pointer in that case we don't admit what we don't want to advance it otherwise we will also move it forward as well so let's say that we rewire the two pointing to three we want to move previous to 3 and we want to move next to four so so that in the next generation we will still try to find the next possible node from from this new in the end we return the node without in the end we return the node without the sentinel it's pointing out so that's the sentinel it's pointing out so that's the code for this for this problem the the code for this for this problem the in terms of time and space complexity in terms of time and space complexity even though it looks like a nested loop even though it looks like a nested loop it's a linear time because the next is it's a linear time because the next is just moving to the next position next just moving to the next position next position next position so in total it position next position so in total it would just run exam all the nodes inside would just run exam all the nodes inside this linked list exactly once so it's a this linked list exactly once so it's a linear time and for time complexity all linear time and for time complexity all we have is a few pointers so that's we have is a few pointers so that's constant space yeah | 2024-03-22 09:47:41 | 203 | Leetcode 203 Remove Linked List Elements |
|
9lkn3rHCSLg | hello everyone so in this video let us talk about a medium level problem from talk about a medium level problem from lead code the problem name is minimum lead code the problem name is minimum genetic mutation so problem statement genetic mutation so problem statement goes like this that a gene string can be goes like this that a gene string can be represented by a eight character long represented by a eight character long string which has a choice of characters string which has a choice of characters of atgc so these are the nucleotides if of atgc so these are the nucleotides if you know a little bit about biology that you know a little bit about biology that in a DNA these are the nucleotides in a DNA these are the nucleotides and a gene string they can they are and a gene string they can they are telling us that it will be eight telling us that it will be eight character long now suppose that UI character long now suppose that UI investigation a mutation in mutation any investigation a mutation in mutation any nucleotide will change to any other nucleotide will change to any other other nucleotide so what you can see is other nucleotide so what you can see is that in this investigation of mutation that in this investigation of mutation you start from a given Gene let's say you start from a given Gene let's say from this and you end up to another Gene from this and you end up to another Gene okay let's see this and now what you can okay let's see this and now what you can see is that in each mutation you are see is that in each mutation you are telling that in each mutation only one telling that in each mutation only one character is changing okay it is character is changing okay it is changing from one cat to another changing from one cat to another character so in this you can see that uh character so in this you can see that uh a is same a same c c the last T is a is same a same c c the last T is changed to a okay so this is one changed to a okay so this is one mutation now what you can see is that mutation now what you can see is that there is a gene Bank okay there's a gene there is a gene Bank okay there's a gene bank which stores the record of all bank which stores the record of all valid gene mutations okay which means valid gene mutations okay which means that it stores out what all are the that it stores out what all are the possible gene mutations that can occur possible gene mutations that can occur okay now what you can see is that you okay now what you can see is that you are given a gene Bank also now you are are given a gene Bank also now you are given a starting Gene and an ending Gene given a starting Gene and an ending Gene okay now you have to tell that what is okay now you have to tell that what is the minimum number of mutations data the minimum number of mutations data required to convert from a starting Gene required to convert from a starting Gene to an ending Gene given that all the to an ending Gene given that all the intermediate positions like all the intermediate positions like all the steps that you have to go through to steps that you have to go through to reach from the start till the end should reach from the start till the end should be in the gene bank because though those be in the gene bank because though those also like those genes that are also like those genes that are intermediately on the end should be intermediately on the end should be valid like they should be present in the valid like they should be present in the gene bank because invalid genes or like gene bank because invalid genes or like uh invalid mutations we do not care uh invalid mutations we do not care about that you only care about the about that you only care about the mutations or the genes that are valid so mutations or the genes that are valid so that are stored in the gene bank and if that are stored in the gene bank and if there is a possible part from the start there is a possible part from the start till the end such that all the genes are till the end such that all the genes are present in the gene bank then it is a present in the gene bank then it is a good uh like you can see that you just good uh like you can see that you just have to counter how many number of steps have to counter how many number of steps are required else you have to return are required else you have to return minus one that's a real problem minus one that's a real problem statement now you can see that from this statement now you can see that from this to this you are going from this to this to this you are going from this to this state now in this the last state is state now in this the last state is changed like the last character is changed like the last character is changed and this last Gene is also changed and this last Gene is also present in the gene bank so so every present in the gene bank so so every step that you do from the start till the step that you do from the start till the end should be present inside the gene end should be present inside the gene map now that's the overall problem map now that's the overall problem statement so that you can see again from statement so that you can see again from here to here you want to go now all the here to here you want to go now all the different genes that are possible different genes that are possible pressure in the gene Bank you just have pressure in the gene Bank you just have to tell that whether it is possible to to tell that whether it is possible to do that now what you can directly do that now what you can directly observe from the statement is that you observe from the statement is that you have a particular Gene bank and you have have a particular Gene bank and you have to only do the iteration on that Gene to only do the iteration on that Gene bank so you have to somewhat make a bank so you have to somewhat make a graph out of that because you from so graph out of that because you from so what you can write you also understand what you can write you also understand is that from every position you can go is that from every position you can go to another position by doing one to another position by doing one rotation okay rotation okay so what you can directly understand from so what you can directly understand from here as well is that what you can do is here as well is that what you can do is let's say that you have a static let's say that you have a static position of a I'm just talking about position of a I'm just talking about four characters okay I will only talk four characters okay I will only talk about four cat test but you can about four cat test but you can extrapolate this information to four extrapolate this information to four characters or eight characters or any characters or eight characters or any number of characters which is in the number of characters which is in the prompt statement it has only eight but prompt statement it has only eight but for a simple understanding let us take for a simple understanding let us take out four out four aatt now from this aatt now from this you can go to a state that is a TTT you can go to a state that is a TTT if all of these genes are present inside if all of these genes are present inside a gene bank so I am building this type a gene bank so I am building this type of graph which tells us from which Gene of graph which tells us from which Gene I can go to which Gene given that only I can go to which Gene given that only one character is changed okay now uh one character is changed okay now uh from this also I can go to one more Gene from this also I can go to one more Gene State let's say this person in the gene State let's say this person in the gene Bank Bank a a t g a a t g now from this let's say there's one more now from this let's say there's one more position that I can go to is a position that I can go to is a g t g so only one character should be g t g so only one character should be changed okay so all of this is some sort changed okay so all of this is some sort of a graph now let's see that you want of a graph now let's see that you want you start with you start with a t a t 80 and then 80 and then okay not a C this is the position that you want to start to so what you can do is that from this position what is the intervention like uh so you have to first understand that from this state what all are the genes that are present in gene bank that is just one step ahead or like ahead of this particular uh Gene because this is the starting date I want to go to any other Gene we have to present that it should be present inside the gene bank so the other cases can made a this kind of flipped this kind of flip this can flip this kind of flip so these are different positions and the first one I can actually say that I can go to this state okay then I can I cannot go to this state because uh okay I can also go from this to this state as well because only like G is changed can I go to the state directly I can kind of go to this state by just one change now so these two I can connect to the starting uh like the starting Gene and then you can directly do a BFS because it's just a minimum distance between two given nodes inside a graph which is just a BFF so you just have to do a BFS from this node to the node whatever node you want to reach to so you just do a BFS at any point you just check that whether the ending node I want to go to is present here then you can write blue because these genes are pretty small you can actually do a complete comparison of a Ted uh like characters like whether they're completely matched to the gene I am on I want to go to so you can actually do that and that's it you will just do a DFS we first make a map from the gene bank then you insert the gene I want to start from then do a BFS over that and you will keep on doing the BFS counting out how many number of steps you are doing to reach the end State the end mutation and if it is possible and return the number of steps that you have taken if it is not possible to turn the Mind saw that that's the overall problem statement and the solution part let us moved on to the code part to how we will do this so it will start from here the minimum number mutations this is n this is the adjacency Matrix that is the essential list I can say sorry uh which is used to build this whole graph so this is the identity list which is a particular string is mapped to how many different strings from upper level how many different nodes I can go to so what I'll do is I will iterate over every possible pair of nodes and uh so I and I plus one okay so this is just iterating whatever possible nodes to just bake the essential list that from which node I can go to which node so I can go particular node to different nodes like if I'm on node a I can go to node B if and only if there's only one number of mutations okay so this is the difference this is a difference function that will literate over both of these strings and just check that the number of different number of characters between these two strings okay so this is a and b and if the number of difference is only one then it is a possible mutation I can go from that but we'll note to another note so I will just check out that if it is possible then I will just make a let's get a edge between these two nodes of this particular strand let's say the is is node to the jth node and 0 to 8 node so it's a bi-directional okay uh path so that's why I've created isnc list like this manner now what you have to do is that from the starting node again you have to check that what all nodes you can go to so what you can do is again you will take the starting node that is the start from which I want to start my mutation and it deliver all the other nodes again those endnotes and just check that whether this starting node is connected to all the node like which all nodes I can connect the starting node two because that's that's the starting node and what I'll do is that I'll again iterate over all the nodes check with this difference function that will just check that whether these two nodes are compatible to be called a mutation by mutation that means that this should be only having one character change and this function is just doing that just check that if it is possible then we'll just again make a edge between the starting node and the given nodes in the gene bank now we have the complete map with us so we will just do a BFS from the starting node filmmaker queue of strings push the starting node okay the starting you can say the starting uh Gene and then we'll and to store that whatever Gene strap it rated we don't double it it over all them because we have been making a bi-directional graph that is where set comes into play so we'll also insert all the nodes that we have iterated to push inside the set so that we have to know key which genes we have a data which we genes we have noted over and we have inserted that also this is the total number of steps it will take from going from start till the end that is answer and just the standard BFS keep on doing this uh iteration over this queue until it is not empty uh find out the size of the queue it over all the particular level or the traversal so overall the nodes that we have seen till now okay uh then what we'll do then it will all the edges or all the connected nodes to a given node again okay and what we'll do is that whatever node I am on I have two things I have to push that inside the you and the set given that it is not already iterated over so if the count of that puts a node I'm on if it is zero which means that it is not iterated over eventually like previously then only I will do this operation if it is already fitted over I will not do that and then I will keep on doing this and increment the answer for every level and the end if at any state I find out the like the final node a final State I want to reach to if I insert that inside the you can say set which means means that I have already edited over that particular node and return the answer which means the at the end if I am not able to reach at the end if I am not able to reach that particular state or maybe uh that that particular state or maybe uh that is not present inside the whole Gene is not present inside the whole Gene bank or in the whole graph the answer is bank or in the whole graph the answer is minus one that's it that's your logic minus one that's it that's your logic and the cool part for this particular and the cool part for this particular problem if you still have any doubts you problem if you still have any doubts you can match now in the comment box of this can match now in the comment box of this particular video I will see you in the particular video I will see you in the next one till the recording and bye | 2024-03-18 10:09:17 | 433 | 433. Minimum Genetic Mutation | LEETCODE MEDIUM | BFS | GRAPH TRAVERSAL |
|
E-lGrr7G5yU | hey guys guess you wonder a problem at Lee code copy this will send a boy on a Lee code copy this will send a boy on a linked list is given such that each node linked list is given such that each node contains additional random pointer which contains additional random pointer which could point to any node in the list could point to any node in the list almost returned a deep copy of the list almost returned a deep copy of the list so basically we have to copy Alice rehab so basically we have to copy Alice rehab who each node has a random pointer who each node has a random pointer so we are going to do this in OPM so we are going to do this in OPM without any extra space let's get right without any extra space let's get right to rely on it let me create a current to rely on it let me create a current variable that point to head now what I'm variable that point to head now what I'm going to do is I'm going to go through going to do is I'm going to go through the necklace and each time when I am the necklace and each time when I am going to create a temp variable this is going to create a temp variable this is going to point to current next now with going to point to current next now with the current next I'm going to do the current next I'm going to do something I'm going to create a new node something I'm going to create a new node which will be which will have the value which will be which will have the value of current label so basically I am I'm of current label so basically I am I'm creating a copy of the current pointer creating a copy of the current pointer current node and I am assigning it to my current node and I am assigning it to my current next now it might here is the next point is a copy of the previous previous not mode that's the end idea actually okay and then I simply the are to do anything at this end of youth and dot next will point to temp and current is yes I think this should do it then I am yes I think this should do it then I am going to reset my current to head this going to reset my current to head this one current to head once that is done I one current to head once that is done I am going to value with the same Nadi the am going to value with the same Nadi the culture because in love and go inside culture because in love and go inside blue and the logic of my loop will be you know if now so if current dot random is not equal to null then let's create a menu which will happen next save some writing for me the temp dot next or so temp dot random that current dot random dot next and current is equal to 10 dot next that's it then for the third iteration alpha together note let's call it new head new minus 1 and [Music] cursor the current cursor is equal to at new head and then my current initial a student now while current not equal to null the current next will be equal to currents next and I'm sorry current Carson is equal to the current cursor not next okay then current dot next is equal to cursor dot next and concern is equal to MU for I have to put a condition that because I have to put a condition that because current cursor is not equal to Ma Dan do current cursor is not equal to Ma Dan do this adds don't and once this is over this adds don't and once this is over returning unit let's sum with this code 9:32 okay now it should work but it does okay guys that's it thanks for watching | 2024-03-21 12:21:35 | 138 | Leetcode 138 Copy List with Random Pointer |
|
NC_M12Ad7no | hello guys welcome to deep codes and in today's video we will discuss liquid today's video we will discuss liquid question 1187 that says make error question 1187 that says make error strictly increasing so guys although strictly increasing so guys although this question is very easy to understand this question is very easy to understand and the question description is very and the question description is very clear but the question is slightly a clear but the question is slightly a tougher level where we have to use our tougher level where we have to use our mind and try to derive the different mind and try to derive the different test cases that can be possible in order test cases that can be possible in order to build the intuition so yeah guys to build the intuition so yeah guys stick with that and watch the complete stick with that and watch the complete video video so here you would be given to array so here you would be given to array array 1 and array 2 and you need to array 1 and array 2 and you need to perform some operation on array1 in perform some operation on array1 in order to make it strictly increasing order to make it strictly increasing okay okay so what operation you need to perform is so what operation you need to perform is you can select any index I from the you can select any index I from the error one and replace that value with error one and replace that value with any element of the array two so what you any element of the array two so what you can do is you can select one area of I can do is you can select one area of I and then replace it with any array 2 of and then replace it with any array 2 of J J and you need to perform such operation and you need to perform such operation in order to make error strictly in order to make error strictly increasing okay so in a sorted order you increasing okay so in a sorted order you need to sort it in strictly increasing need to sort it in strictly increasing and you need to return minimum number of and you need to return minimum number of such operation to make array one uh such operation to make array one uh strictly increasing okay strictly increasing okay so yeah here the patient suggests us to so yeah here the patient suggests us to find the optimal answer that is the find the optimal answer that is the minimum number of operation minimum number of operation so guys now let's try to look at the so guys now let's try to look at the examples for better understanding so in examples for better understanding so in the first example here we have added one the first example here we have added one five three six seven so you can see that five three six seven so you can see that this one then this one then um this is uh then it's from 5 so 5 is greater than 1 then comes three now this condition is violated here at three then for six it is okay for seven it is okay so the condition is violated we at three so now do do we have any elements between 5 and 6 no that can be there is no possible elements between five and six that can be inserted here right so what we did here is VD plus five with two then the array becomes something like this one two three six seven so guys although the condition of strictly increasing was violated at uh index two that is for the element three but we didn't replace this and replace the Phi with a 2 and now the array is strictly increasing in a sorted manner so this is how we solve the first example now in the second example what we did here is see initially we replace this 5 with 3 and this 3 with 4. so the final array becomes something like this one three four six seven and yeah this is uh sorted and in a strictly increasing order so yeah guys we perform two replace operation here replace with this 4 and these three so yeah we written two as our answer now in the third example here let's say we have fine now these three we need something that is greater than 5 and less than six but anything is possible no nothing is possible here so let's try to replace five with something so okay so if you replace five with one then this is not strictly increasing so this can be done so my first element of one now let's try to replace five with three so if you replace it with three it's okay till here but the next element three now this three is not greater than the previous we need strictly increasing so we again have to replace this then let's say we replace it with six so now the array because something like this one three six the next element is six okay now this 6 is not um in the strictly increasing to previous so we need to replace it with something but do we have any other option there is greater than six no we don't have any options so yeah we return minus one here so whenever we find it is impossible to sort the error in strictly increasing order we simply return minus one so yeah guys got this clear till here so you can see that uh for each element of the area one there are some options like we can either replace that element or not to replace yeah so based on the option we try to find the best or optimal solution in return uh the minimum number of operation right so guys let's take one more example and try to understand how these things can work so let's say you have arable like this one two three seven six and ten so up till here everything was sorted now at this point the strictly increasing uh condition of array 1 is violated so we have to do something right got it and in the error 2 we have numbers like 14 15 and 5. so one option is what we can do is we can do one two three seven then replace the six with let's say with 14 we replace it with 14 okay now then we also have to replace 10 so let's say we replace it with 15. now this array is sorted okay how many operations we perform we operation perform twice so the answer is to here okay now guys what what another way we could solve this question let's see so we have one two three enough uh let's say we have replaced the seven with five so we have replaced and placed here five then six okay the condition is not satisfied till here and 10 is also satisfied so by performing only one replace operation operation at 7 means at an uh index 3 with a value 7 we can get the array array 1 in assorted in a strictly increasing certain manner so guys we have to identify that what is the best approach to solve this question that means we have multiple approaches or multiple choices or you can say options so one option is this that we have it this is the second option so guys whenever we have multiple options to solve this so to solve the question what we can think of is we can think of recursion right because in recursion what we do is we try to take one of the option and try to find thumbs up if we don't get we try to take a step back and try to find different answer with a different approach or different choice so this is a typical recursion plus memorization question where we first perform the recursion and then memorize the recursive solution and guys building up the intuition for this type of question is in easy because by the test case that I have shown you that either if we have replace six uh six and then ten they need to result 2 but if you have replace seven then it would result one so we have different options or different choices in uh to replace what element and with what right so yeah whenever we have this type of situation when we where we have to make uh different choices and choose the most optimal Choice then we can perform recursion plus memorization also one thing if you note the constraints for this question is uh the size of the array both added one and error 2 is up to two thousand so this is a very good indication that yeah we can perform n Square solution but if this type of situation if you have size of the array up to 10 to the power 5 then you must be clear that big of n Square solution won't work recursion plus memorization won't work and in that case we have to perform some n log n solution so guys uh observing the different test cases as well as observing the constraint can help us to get the idea uh to build the intuition okay now let's move ahead in this question so here what was our observation our observation state that if array of I is greater than add of I minus 1 that means the current element this is the is greater than previous element so if is greater than previous element so if this is the case then we have two this is the case then we have two options right we we can replace it or options right we we can replace it or not to replace it okay so uh if already not to replace it okay so uh if already it is solid then also we can replace it it is solid then also we can replace it as we have seen here that up till 7 the as we have seen here that up till 7 the array was ordered then also if we array was ordered then also if we perform replace operation it was perform replace operation it was beneficial for us so if in this beneficial for us so if in this condition we have two choices we can condition we have two choices we can replace and not to replace replace and not to replace and in this condition let's say add of I and in this condition let's say add of I is less than equal to the previous that is less than equal to the previous that means the current means the current is less than equal to previous in this is less than equal to previous in this situation we have only one choice that situation we have only one choice that is to replace right to perform replace is to replace right to perform replace operation because this will violate the operation because this will violate the condition condition of add a 1 being strictly increasing so of add a 1 being strictly increasing so if this is the case then we definitely if this is the case then we definitely have to perform the replace operation have to perform the replace operation and yeah based on these two observation and yeah based on these two observation uh we will derive the approach okay but uh we will derive the approach okay but guys wait a minute guys wait a minute so this intuition part is very much so this intuition part is very much Clear we have choices to perform replace Clear we have choices to perform replace and not to perform replace operation So and not to perform replace operation So based on that we uh can decrease the based on that we uh can decrease the solution and then memorize it solution and then memorize it now one question I would like to ask you now one question I would like to ask you is whenever you perform a replace is whenever you perform a replace operation that is to replace any nums uh operation that is to replace any nums uh any integer from array 1 with array two any integer from array 1 with array two then what would be the best possible then what would be the best possible choice of replace choice of replace so that would be nothing but a smallest so that would be nothing but a smallest number greater than the uh previous so number greater than the uh previous so let's say if you are performing replace let's say if you are performing replace on array on array one or five so if you want to perform one or five so if you want to perform replace operation on this so for that replace operation on this so for that you have to check you have to check the value of the previous element and the value of the previous element and you need to find the smallest number you need to find the smallest number greater than previous inside added to greater than previous inside added to option so we need to find smallest option so we need to find smallest number greater than previous inside number greater than previous inside added two of J okay why so if we don't added two of J okay why so if we don't do this thing what will happen so let's do this thing what will happen so let's say in the same example above so we have say in the same example above so we have one two three seven six and ten and one two three seven six and ten and array 2 has 14 15 and 5. so what if we array 2 has 14 15 and 5. so what if we have replaced the 6 with 15 okay have replaced the 6 with 15 okay so that then that would result in 1 2 3 so that then that would result in 1 2 3 7 15 and the last remaining element 7 15 and the last remaining element would be 10 now there is no way possible would be 10 now there is no way possible to replace 10 with any numbers from the to replace 10 with any numbers from the erectum that is greater than 15 yeah so erectum that is greater than 15 yeah so this array can never be sorted okay this array can never be sorted okay right so this array if we have replaced right so this array if we have replaced the 6 with 15 then the adder would never the 6 with 15 then the adder would never be sorted so this is not the best way to be sorted so this is not the best way to get the answer right so whenever you are get the answer right so whenever you are performing replace operation try to performing replace operation try to replace it with the element that is replace it with the element that is uh greater than previous but it is uh greater than previous but it is smallest right so here if you want to smallest right so here if you want to replace the six point any element replace the six point any element then we have option of 14 as well as 15. then we have option of 14 as well as 15. so we need to choose the element that is so we need to choose the element that is greater than the previous but it is greater than the previous but it is smallest so that is 14. so if you have smallest so that is 14. so if you have uh choose here 14 and the array would be uh choose here 14 and the array would be something like this one two three seven something like this one two three seven Fourteen and for 10 we would have still Fourteen and for 10 we would have still have the option to replace 10 with 15. have the option to replace 10 with 15. so in this case at least we have some so in this case at least we have some result instead of -1 result instead of -1 so yeah whenever you perform replace so yeah whenever you perform replace operation try to replace it with the operation try to replace it with the smallest number greater than the smallest number greater than the previous okay things are created here previous okay things are created here now the next thing so if you go and try now the next thing so if you go and try to search what is the best possible to search what is the best possible replace number from the edit two then replace number from the edit two then you travel the complete editor then that you travel the complete editor then that will result in big of uh because M time will result in big of uh because M time complexity let's say array two sizes M complexity let's say array two sizes M and you need to search this number there and you need to search this number there is smallest number greater than the is smallest number greater than the previous then that will take big of M previous then that will take big of M time compensating so one thing we can do time compensating so one thing we can do here is we can sort error to object here is we can sort error to object because the any indexing whenever we are because the any indexing whenever we are performing replace operation whatever performing replace operation whatever may be the index of the J uh add a two may be the index of the J uh add a two of J it doesn't matter we can perform it of J it doesn't matter we can perform it with any index number so yeah what we with any index number so yeah what we can do is we can sort the array 2 of J can do is we can sort the array 2 of J and then use binary search to find this and then use binary search to find this number which number smallest number number which number smallest number greater than the previous so this can be greater than the previous so this can be done in big of log of M time complexity done in big of log of M time complexity if we sort array 2 of Gene and then we if we sort array 2 of Gene and then we perform binary search perform binary search so so to find additive of J that is the best to find additive of J that is the best possible candidate for replacement what possible candidate for replacement what we can do is we can first sort array 2 we can do is we can first sort array 2 of J and then apply binary search binary of J and then apply binary search binary Searcher offered wrong they both will Searcher offered wrong they both will take off long end time upper one will take off long end time upper one will Implement binary search internally yeah Implement binary search internally yeah this is the htl statement this is the htl statement and this will use binary search and this will use binary search internally so yeah guys combining all internally so yeah guys combining all these things let's code it okay I know these things let's code it okay I know there would be a few more doubts in your there would be a few more doubts in your mind but we will try to solve them with mind but we will try to solve them with the help of uh four only okay the help of uh four only okay so the first step here is uh let me try this so first step here is to sort the sort added to option then call this answer uh solve function that will store the answer now inside the solve function think of this this is nothing but a base condition so whenever we have process all the elements of the arrayment we would stop and return zero that means by return zero because no more replace operation are required now so yeah we will return 0. okay then skip this for right now now we have two choices operation one and operation two so operation one that means make simply consider this is make replace operation so this is our option one and this is not to make okay so we have two options right either we make the replace operation or not to make now if we have some condition like this with if error if I is greater than 0 okay and the current element is less than equal to previous element so this is the case where we definitely have to make replace operation if the current element is less than or equal to previous element then we have to make replace operation now how we will make replace operation for that we will choose the smallest number that is greater than the previous so we applied here upper bound so upper bound will find us the smallest number greater than the previous so we uh perform upper bound from the added two of begin until added to offend to find the number that is greater than this add a 1o that is this is nothing but the previous so this is previous element and we say subtracted at the beginning so that we get the index okay now if this index lies inside the range of array 2 what we can do is uh and also it is greater than the previous then we can simply replace it replace array 105 with edit workshe and then perform this recursive call okay why we added one because we already performed one replace operation here so we added one and then call recursive function to get the answer from the remaining and F1 right so uh pass this I plus one and yeah and for further solving I will also replace it with the previous num so whatever number was present in the previous week also we again change that area of I this is like a backtracking state okay so this is one thing now the second thing here is if the number if the current number say current and this is previous the current is already greater than the previous so in this case we have two choices right either to make replace operation or not too many so the first thing we did the same thing here this code is the same that is we are performing the replace operation so the same thing we are finding the upper bound and then performing the replace recursively calling this solve function and storing in option one and you are then again changing the value also we have second choice right to us or the second option that is not to perform the plus operation so in that case don't add this one don't add this one because we are not performing anything and simply call solve function correct with height plus one and in the third case here both the time we check if the I is greater than zero but there might be a case where we have to perform the place at the zeroth index right just think if you want to make a replace operation at the zeroth index with what element you will replace you will surely try to replace it with the smallest number right if because we don't have to compare if it is a zeroth index element then that can be the smallest number right so what we would do is we would simply check the zeroth index element of array 1 because zeroth index element of array 2 error 2 is already sorted so now we don't have to go and find upper bound we have we want to make error zeroth index as small as possible so we will choose the smallest element I if it is if it is already small then we won't perform replace operation as we would perform right so if so this Thing Remains the Same inside this so this if condition Remains the Same in the second option option we already have that yeah don't perform any operation so simply go and find the answer for I plus 1 okay the minimum of both option one and option two Choice One and choice two right now guys one thing I forgot here why 2001 buy this so if you go and look at the constraint the size of array is error one size is uh is less than equal to two thousand okay so the maximum replace operation you can perform is 2000 because the size of adamant is itself two thousand then you won't perform more uh replace operation than this number so yeah we have to return some inch Max right in order to handle the situation when we when the strictly increasing array is not possible so if you have seen this in the third example so here strictly increasing add a was not possible in order to handle this case what we did is we simply returned some maximum number that will state that yeah it is not possible see instead of this if you written -1 then perform this mean operation then minus 1 would be minimum but in our case minus 1 means answer is not possible so we have handled it in this way that instead of minus 1 we took some maximum number and if the answer is greater than 2000 okay they're greater than the size of the maximum size of the idea we can have in the input that in that case simply return minus one else the answer okay got it clearly no now count this question that how we can perform memorization if you do until recursion then it will surely give you time limit exceeded now guys in order to perform memorization we have to find what are the changing variables or Changing State of our recursion dream so if you to take a look at this function called the parameters so one is one parameter that is I or the index of the array one we know yeah it is it is changing but for another thing is changing is array one the values of the different indexes of the error is changing because whenever we perform t plus operation at a one values change right so these two things are change now now one thing more to note here is let's say you are checking for any current element you only check uh this current element if it's greater than equal to or less then based on the previous element that means you only perform comparison of the ith element with the previous element right so guys what we we would do is we would store two things one this index that is changing and second to keep track of the current state of ID 1 we would store the previous element because on the previous element only we are making some changes making the replace operation to handle so whenever if whenever you see this I minus 1 I minus in they both are previous element so yeah we would store two things one is the index sign and second is the previous element okay so we took a map a pair of map uh a map with a pad as a key and Inked as a value so in this pair we will store the I as well as the value of the previous element now if I is 0 then we will simply take minus 1 as the value of the previous element right if I is a 0 then there is no previous element so yeah that's why and here also we store um on memo is it the answer in the same way that is the I as well as the with previous element and yeah and here to perform to reduce the number of sub problems we perform this memorization step where we find that whether we are actually calculated the answer for the current step in some previously right so if you calculated the answer previously for the current state then we simply return the answer okay so I hope you guys have now somewhat understanding of what we are trying to do in the code if you guys have still any doubts then do try to write The Code by yourself you try to make different test cases by yourself so that you can get better understanding okay now talking about the complex videos so here the complexity let's talk about the time complexity first so for one is let's say sort so for an example let's say the size of added one is a size of added 2 is m now the sort function will take M log of M time complexity in the first case then we are calling the solve function okay now guys talking about the time complexity for the solve function so let's say the size of added one is n and size of added 2 is M now here what we are storing is inside the map we are storing the index I as well as the previous element so let's say so time probability M log of M based on this sort now adding how many different values are possible for I so that is M different uh not M it's n different possible values okay so n multiplied how many different values possible for the previous so we are storing a previous element right how many different values possible for the previous M different values are possible because the previous element can be replaced by m different elements of the array2 so for each index M different possible values are there for the previous element so these many number of states are possible in a recursion tree also for each time for each state what we are doing we are trying to find the upper bound and it will take log of M time complexity so these upper bound will take log of M time complex setting so this is our overall time complexity for the solution and talking about the space complexity space complexity is also the same as this this is a workspace complexity right plus some recursive stack will be occupied right so yeah guys that's all for this video if you guys have still any doubts then do let me know in the comment section make sure you like this video And | 2024-03-25 18:18:00 | 1,187 | 1187. Make Array Strictly Increasing | Recursion | LeetCode Daily Challenge |
|
esu6uExE0qg | Hello hello everyone welcome welcome back to my channel listen to today's events two problems channel listen to today's events two problems shipped to degrade show in this problem yagya na shipped to degrade show in this problem yagya na today grade of size ambros and when today grade of size ambros and when unit to shift grade of time unit to shift grade of time in the operation in the operation element subscription will go to element subscription will go to columns and columns and elements vich elements vich elements vich after operation Times of the giver Person's time A&M to restore the kid with this form Find out the shipping like Times of water Final merit is that minute written on ok so let's understand with example so Lipstick example to here Lipstick example to here Lipstick example to here I am college student effective two times to I am college student effective two times to butter shifting means let's take now the butter shifting means let's take now the position judgment aa the position judgment aa the book is position and introduction starting book is position and introduction starting for unlimited for unlimited dictionary app the dictionary app the right choice is dam ko amardas grade right choice is dam ko amardas grade five walk rent a position to very nice five walk rent a position to very nice Yaar tu shift shifting one time means the thing which position which will be seen in role same but column will increase in role same but column will increase first to low medium to solve this will first to low medium to solve this will be the true one and column to go ok only a sorry waste E ok sona need your E ok sona need your E ok sona need your support way swift welcome support way swift welcome hai hai torch light similarly for example the again torch light similarly for example the again happy shivdaspur sunavai nasai hai happy shivdaspur sunavai nasai hai precepts current position in one kumawat precepts current position in one kumawat grade one ko - it's position dena ya 250 grade one ko - it's position dena ya 250 against tobacco cessation broken and light show against tobacco cessation broken and light show water witch failed position grade simro water witch failed position grade simro water witch failed position grade simro Will Increase Bye Bye Oh And Listen Will Come From This Year To This A's Rank Morning Bud From Debate How To Shift Get Meaning Of How To Move It Damini Column Bread Member Real Position Now Welcome Aware Of How To Times Leadership Basically 1727 triad meaning of something is Basically 1727 triad meaning of something is Basically 1727 triad meaning of something is increase column increase column so you might be thinking what will happen so you might be thinking what will happen in a flexay the element who in a flexay the element who is the first the is the first the right place right place element which was talking about is back i element which was talking about is back i and let se withdrawal tweet current position and let se withdrawal tweet current position s grade of that s grade of that This Current Position This Red Wine Might Be This Current Position This Red Wine Might Be Morning Shift This Position Vikram Grade One End This Column Increase Morning Shift This Position Vikram Grade One End This Column Increase One To That Is It Will Come Here One To That Is It Will Come Here That Aapke Naav Again Later You Listen To-Do List This 515 Welcome To The The process The process The process was right but here call me too right two plus one will be was right but here call me too right two plus one will be 3 3 your loved ones other dozens of columns that your loved ones other dozens of columns that rights will model set with the problems problems rights will model set with the problems problems 380 Enfield has 200 columns on is but will not Govind Singh Rohit will go through the next9 the Thing to Connect with Design Plus Thing to Connect with Design Plus Thing to Connect with Design Plus Minus A A Minus A A Ruk Sudarshan Have Left To Shift and Subah Ruk Sudarshan Have Left To Shift and Subah Sacrifice Procreation Like This Will Go Sacrifice Procreation Like This Will Go to the Next Row Main to the Next Row Main Office Call Rate Similarly Dushman Free Office Call Rate Similarly Dushman Free Will Go to the Next Rot This Position On Will Go to the Next Rot This Position On That Aapke ₹100 Anurag Vyas 208 That Aapke ₹100 Anurag Vyas 208 That Aapke ₹100 Anurag Vyas 208 They Can Not Protect oo 180 Take Care Expert Se Puck So Let Me To Election 2012 2012 Se Puck So Let Me To Election 2012 2012 Tomorrow Morning See What We Have To Basically Tomorrow Morning See What We Have To Basically Shifting Means Cheating Year Means Digestive Shifting Means Cheating Year Means Digestive Volume Head One Column Hydrate Hai Volume Head One Column Hydrate Hai Tu Tu Tu three letters for 2nd year 45678910 have to shift that from me how to shivdaspur how to times in this very easily debit the sentence is worshiped vitamin for welcome bhaiya very simple i just because the same thing rate explanation View Greed and Disadvantages of View Greed and Disadvantages of View Greed and Disadvantages of Exile for Example of it Exile for Example of it Share Other Side Effects Lipika 100 Beds Share Other Side Effects Lipika 100 Beds Reserved One Position Reserved One Position for It's a Comment Or Leave Your Comment for Us That Police Cheating Writing Grade It's Kind of Similar Scored of Similar to Shipping in the World in Wonderland Pandey Devendra Yadav Shift Same On The Wonderland Pandey Devendra Yadav Shift Same On The Water Of Wick Convert Basically First Formal Wear Converted Into Something Like This One Day Are Worshiped In The World In The Great Ho Okay Sochati Elective With The Wind To Example To Let I Will Show You What I Will Show You What I Will Show You What latest one vehicle related 500 latest one vehicle related 500 attacks done tech juice 5.5 writing for her attacks done tech juice 5.5 writing for her 123 123 45678910 festival is that came from her calligraphy tips disposition and that came from her calligraphy tips disposition and climate grade one to maven climate grade one to maven were write stances five were write stances five disposition and worshiped on disposition and worshiped on torch torch torch Indulge 202 Hawa Will Do It A Hello How I Will Do It I Will Find Out The Corresponding To Give One Right Corresponding To This Position What Will Be The Index Here Demanded A Okay What Within Ther Soul Can Find It Difficult for visiting decided today speech on that this weapon is a torch light distic basically index is this one how they can find your they can find your index in theory induction one-dayer index in theory induction one-dayer how they can find which can find your how they can find which can find your secrets who secrets who is the current row water level controller is is the current row water level controller is multiply rouse and the number of columns the multiply rouse and the number of columns the total number of columns so let's take total number of columns so let's take details in aa rahi to total number of columns sachiv and hai a plus tak current column what is the current column strong system induction pandey c how to Number Number Number of Columns Guest Column Ship Is of Columns Guest Column Ship Is A Plus Current Columbus What One Two's Formula A Plus Current Columbus What One Two's Formula Into One Plus One Four To Index Into One Plus One Four To Index In Theory For This Position To Mount Will Be Points In Theory For This Position To Mount Will Be Points Statistics That Your Ayub Artist That Sufia The Forest Walking See Basically Here this was coming Here this was coming Here this was coming year and skimming share this please come year and skimming share this please come in heading support will be coming ok in heading support will be coming ok subah 510 total number of water dharohar so subah 510 total number of water dharohar so dat paneer position feature plus seat Vivo and what dat paneer position feature plus seat Vivo and what is the number of column that was held on ok so let's know is the number of column that was held on ok so let's know Vinod Vinod Vinod justice for element if index in theory hear tips for plus how many types to times dot in the new position with six that coastal so I don't know of platforms 750 less decide on that without hear communication is six new index the this sex That various you need and hear Big Guide New Index But Know How Will Convert This Index Back to the Question Read Them Into a Temple New A Vaikuntha to Convert Right That Person's * Indexes See Duty Concept You Have Any Questions or Website Will Never See They Have Website Will Never See They Have Website Will Never See They Have Tried To Tried To 1282 Roll Number And Column Number 1282 Roll Number And Column Number To Havaldar Tis Born In Six Divided To Havaldar Tis Born In Six Divided By Total Number Of Columns Will Give The Roll By Total Number Of Columns Will Give The Roll Number This Book Is Divided By Total Number Number This Book Is Divided By Total Number Of Columns Watan Of Columns Watan Ai The Statistics Ai The Statistics 222 222 A Subject Uprising Number And A Subject Uprising Number And A Subject Uprising Number And No. 15 Small Dealers and Statistics Model Ras Teen Which Will Be 0f Hua Tha Reminder Right to Day Two Zero No. 0 Column No. 2 Ko Manzilon Here Here This Will Come After Shifting To Time and Time Tomorrow Morning Yasmin Tomorrow Morning Yasmin Tomorrow Morning Yasmin great which gives any problem will not change this year will begin you matrix light of in size and wearing 1550 place in which a position in five wickets left was new position for a day main tu kya machine on ki To Lucknow Distance Between To Lucknow Distance Between To Lucknow Distance Between Father And Ethos Element Difficulty What They Are Father And Ethos Element Difficulty What They Are Doing Bihar Currency Row And Doing Bihar Currency Row And Column Number From Dead Be Converted Into Index Column Number From Dead Be Converted Into Index In Mind They Are This That Ritual Behavior Of Inquiry Shift's Times The Next Position In The Convert Dhronic Column Dhronic Column Dhronic Column Width Neuron Column Width Neuron Column that is intermediate in the matrix, it is that is intermediate in the matrix, it is systematic, the systematic, the output is improved, output is improved, handed over to the industry, if the industry takes the approach, then handed over to the industry, if the industry takes the approach, then code lineage center code volume and care, code lineage center code volume and care, which one, what are they doing, the which one, what are they doing, the fifth number and the fifth number and the number of India every day, follow them. number of India every day, follow them. number of India every day, follow them. benefits of view of creative stamp emotion eyes of various districts and India going to key element in tomato side view of finding out with evidence ok tu shifted and white widow in models ok tu shifted and white widow in models ramp roshan because total seat mighty bayah ramp roshan because total seat mighty bayah top top top Daily Point Is My Gautam Sunil To Do It Agro Center Embraced With Total Number Of Elements In The Year E In The Work Done What They Are Doing Fine You Coordinator From This Volume 10 Index In 2ND Year wear update shifting diet wear update shifting diet wear update shifting diet value always ready to the new values value always ready to the new values new coordinator you are you see in the temple new coordinator you are you see in the temple improve and find to time to death for this will be improve and find to time to death for this will be president president love we tullu so am process with love we tullu so am process with time complexity a time complexity a a specific tubewell also TVR but a specific tubewell also TVR but gift gift A B Coming Distance Factor Attempt Factor A B Coming Distance Factor Attempt Factor For Basically Choose Out Here Its Time For Basically Choose Out Here Its Time Space Complex Will Not Be Counted But E Feel Space Complex Will Not Be Counted But E Feel Contents Should Be Victorious And Tricks Are Naturally Contents Should Be Victorious And Tricks Are Naturally But This Basis Of Food But This Basis Of Food Recipes Not Counted And Vedic Recipes Not Counted And Vedic Contexts On Ka But But But they need information please they need information please like it to my channel thank you for giving advance. | 2024-03-19 17:42:33 | 1,260 | Shift 2D Grid | Leetcode 1260 | 2-D Array | Day-11 |
|
gHWruHfNjO4 | [Music] hey guys welcome back to another video hey guys welcome back to another video and today we're going to be solving the and today we're going to be solving the lee code question add lee code question add two numbers of part two all right so in two numbers of part two all right so in this question we're given two this question we're given two non-empty linked lists representing two non-empty linked lists representing two non-negative integers so non-negative integers so for example let's just look at the input for example let's just look at the input over here so we have 7 over here so we have 7 2 4 3 and 5 6 and 4. so both of them 2 4 3 and 5 6 and 4. so both of them represent a set of numbers represent a set of numbers so the most significant digit comes so the most significant digit comes first first and each of their notes contains a and each of their notes contains a single digit add the two numbers and single digit add the two numbers and return it return it as a linked list okay so we have 7 as a linked list okay so we have 7 2 4 and 3. so in this case 7 over here 2 4 and 3. so in this case 7 over here would be the most significant digit would be the most significant digit and three would be the least significant and three would be the least significant digit so what does that mean so in digit so what does that mean so in simple words that means that simple words that means that the number here is going to be seven two the number here is going to be seven two four three four three well in other words seven thousand two well in other words seven thousand two hundred and forty three hundred and forty three and this over here is going to be 564. and this over here is going to be 564. okay so you may assume that the two okay so you may assume that the two numbers do not contain any leading zeros numbers do not contain any leading zeros except for the number zero itself okay except for the number zero itself okay so let's just look at this uh so let's just look at this uh input over here so like i said earlier input over here so like i said earlier we have 7243 we have 7243 and we have 564. so when you add those and we have 564. so when you add those two numbers you get two numbers you get an output of 7807. an output of 7807. now how do we actually end up outputting now how do we actually end up outputting this so this so what we want to do is we want to output what we want to do is we want to output this as a linked list this as a linked list and it's going to follow the same rules and it's going to follow the same rules with the largest or the most significant with the largest or the most significant value value coming first so seven eight zero seven coming first so seven eight zero seven seven thousand eight hundred and seven seven thousand eight hundred and seven all right so now let's see how we can all right so now let's see how we can actually do this kind of step by step actually do this kind of step by step and yeah all right so the first step is and yeah all right so the first step is we're given two linked lists so linked we're given two linked lists so linked list one list one linked list two and we need to convert linked list two and we need to convert that into a number that into a number so let's convert this into a number so so let's convert this into a number so how are you gonna do it so it's pretty how are you gonna do it so it's pretty simple simple uh i'll just show you how we do it for uh i'll just show you how we do it for l1 so we will have l1 so we will have a value and let's just call this our a value and let's just call this our number so this value is going to start number so this value is going to start off at zero off at zero so this over here is an integer and so this over here is an integer and another way to kind of say that another way to kind of say that is that it's a base 10 value what that is that it's a base 10 value what that means is that the zeroth means is that the zeroth place is 10 to the power of zero place is 10 to the power of zero multiplied by whatever value we have multiplied by whatever value we have the tens place is 10 to the power of one the tens place is 10 to the power of one the hundredths place is 10 to the power the hundredths place is 10 to the power of 2 of 2 and so on and so forth so kind of using and so on and so forth so kind of using that what we're going to be doing is that what we're going to be doing is we're going to take our zero we're going to take our zero and each time we're going to multi sorry and each time we're going to multi sorry not zero the num each time we're going not zero the num each time we're going to multiply to multiply num by 10 and then we're going to add num by 10 and then we're going to add whatever value we're on whatever value we're on so now we're going to zero multiply by so now we're going to zero multiply by 10 which is both zero and we're gonna 10 which is both zero and we're gonna add seven so so far our number is seven add seven so so far our number is seven so now we're gonna do seven multiplied so now we're gonna do seven multiplied by ten which gives us seventy by ten which gives us seventy and to that we're going to add two so and to that we're going to add two so giving us seventy two giving us seventy two so hopefully you understand how this is so hopefully you understand how this is gonna work so then by the end of it gonna work so then by the end of it you're gonna get to get 7243 you're gonna get to get 7243 and for this you're going to end up and for this you're going to end up getting 564. getting 564. all right so these are our two numbers all right so these are our two numbers so now what we so now what we need to do is we need to find the sum of need to do is we need to find the sum of it and well finding the sum is pretty it and well finding the sum is pretty simple we're just going to end up adding simple we're just going to end up adding them them so since we're just adding them this so since we're just adding them this over here is actually going to have a over here is actually going to have a value seven thousand value seven thousand eight hundred and seven so seven eight hundred and seven so seven thousand eight hundred and seven thousand eight hundred and seven all right so here it gets a little bit all right so here it gets a little bit tricky so now the question is tricky so now the question is how do we actually end up uh outputting how do we actually end up uh outputting this so this so in simple words it's just going to be in simple words it's just going to be seven pointing to h pointing to zero seven pointing to h pointing to zero pointing to seven right pointing to seven right in a linked list but how exactly do you in a linked list but how exactly do you do that do that so now we wanna get each of these so now we wanna get each of these numbers so one thing that we could do numbers so one thing that we could do is uh we can kind of separate these is uh we can kind of separate these numbers and get each of the number numbers and get each of the number itself how do you do that so what you itself how do you do that so what you would do would do is you would each time you would divide is you would each time you would divide it or you would do perform the modulo it or you would do perform the modulo operation by 10. operation by 10. so what that does so 7807 so what that does so 7807 mod 10 would give us the number seven mod 10 would give us the number seven and after we get the number seven that and after we get the number seven that gives us the first digit gives us the first digit so now what we're going to do is we're so now what we're going to do is we're going to divide 7 8 0 7 going to divide 7 8 0 7 divided by 10 and take only the integer divided by 10 and take only the integer value we're gonna value we're gonna uh kind of skip or not talk about or uh kind of skip or not talk about or ignore the decimal values so ignore the decimal values so now we have 7807 divided by 10 which is now we have 7807 divided by 10 which is 780.7 780.7 and we're just going to take it as 780. and we're just going to take it as 780. okay so now again okay so now again we're going to 780 mod 10 so this gives we're going to 780 mod 10 so this gives us the next digit which is zero us the next digit which is zero then we're going to end up with 78 and then we're going to end up with 78 and that's going to give us 8 that's going to give us 8 and then we're going to get 7 and that's and then we're going to get 7 and that's how we end up getting all our numbers how we end up getting all our numbers but now the problem with this is how but now the problem with this is how exactly do you add it to our linked list exactly do you add it to our linked list so uh we have seven zero eight seven and so uh we have seven zero eight seven and if you add if you add in uh if you end up adding it in that in uh if you end up adding it in that order order you get seven pointing to zero pointing you get seven pointing to zero pointing to eight pointing to seven to eight pointing to seven and the number that we end up getting is and the number that we end up getting is seven zero eight seven seven zero eight seven but the actual number that we're looking but the actual number that we're looking for is seven eight zero seven for is seven eight zero seven so obviously these are not the same so obviously these are not the same thing so what we're going to thing so what we're going to end up doing uh one thing that we could end up doing uh one thing that we could do pretty simply is do pretty simply is over here we have seven zero eight seven over here we have seven zero eight seven and we're just going to end up reversing and we're just going to end up reversing it it so in other words uh the 7 0 8 7 so in other words uh the 7 0 8 7 is now going to be 7 pointing to 8 is now going to be 7 pointing to 8 pointing to 0.27 pointing to 0.27 we just reverse it and that actually we just reverse it and that actually ends up giving us our answer ends up giving us our answer which is eight hundred and seven okay which is eight hundred and seven okay and we will see and we will see one more way which i actually found uh one more way which i actually found uh and it's pretty clever and it's pretty clever uh how they did it so i'll just show you uh how they did it so i'll just show you that method as well but for now let's that method as well but for now let's just stick with this just stick with this okay so let's see how we can do this in okay so let's see how we can do this in code and yeah all right so we're gonna code and yeah all right so we're gonna start off by finding out the two numbers start off by finding out the two numbers so so let's just define them as number one and let's just define them as number one and number two they're both going to start number two they're both going to start off with the value of zero off with the value of zero and let's just start off with finding and let's just start off with finding the first number so to do that what i'll the first number so to do that what i'll do is i'll go inside of the first linked do is i'll go inside of the first linked list which is list which is l1 and we're going to do while l1 what l1 and we're going to do while l1 what that means is that means is we're going to stay inside of this we're going to stay inside of this linked list as long as we're not on the linked list as long as we're not on the very ending very ending and we're going to stop at that point and we're going to stop at that point because the very ending because the very ending is going to have a value of none okay so is going to have a value of none okay so over here over here we're going to change our num1 value so we're going to change our num1 value so num1 num1 is now going to be equal to num1 is now going to be equal to num1 multiplied by 10 and after that we're multiplied by 10 and after that we're going to add it with whatever value going to add it with whatever value we're currently on and to do that we can we're currently on and to do that we can just do just do l1 dot val all right now each time we l1 dot val all right now each time we need to kind of need to kind of move our pointer to the right by one bit move our pointer to the right by one bit so to do that we can just do l1 is equal so to do that we can just do l1 is equal to l1 dot next to l1 dot next so you can just imagine that we're so you can just imagine that we're starting off at the head and then each starting off at the head and then each time we're moving to the right time we're moving to the right and once we reach the very ending we're and once we reach the very ending we're not going to go inside of the statement not going to go inside of the statement because because while l1 is not going to be true so now while l1 is not going to be true so now we have the first number we have the first number and all we need to do is we need to do and all we need to do is we need to do the same thing but instead we want to do the same thing but instead we want to do it for the second number it for the second number so i'll just be changing all of the ones so i'll just be changing all of the ones over here so instead of while l1 we'll over here so instead of while l1 we'll do do while l2 and instead of l1 we'll be while l2 and instead of l1 we'll be referring to l2 referring to l2 right so just change all of that to two right so just change all of that to two basically okay so we have that basically okay so we have that and now we have the two numbers ready so and now we have the two numbers ready so now let's find out the sum and to do now let's find out the sum and to do that as well pretty simple you do just that as well pretty simple you do just do do num1 plus num2 all right perfect num1 plus num2 all right perfect okay so we got our sum right now and now okay so we got our sum right now and now the goal or what we really need to be the goal or what we really need to be doing doing is we want to uh convert it into a is we want to uh convert it into a linked list linked list so this linked list over here is going so this linked list over here is going to be the reverse of what we need to be the reverse of what we need the leftmost value or the head node over the leftmost value or the head node over here is going to be here is going to be the smallest the least significant value the smallest the least significant value and the other side is going to be the and the other side is going to be the most significant value most significant value so we just need to reverse that later on so we just need to reverse that later on so we're going to start off by actually so we're going to start off by actually creating a dummy head okay so let's just creating a dummy head okay so let's just call this our head for now call this our head for now and this over here is going to be well and this over here is going to be well an object of the list node class an object of the list node class and it's going to have a value of zero and it's going to have a value of zero all right so why exactly all right so why exactly uh are we doing this so the reason we uh are we doing this so the reason we have a dummy head is because have a dummy head is because we can just add everything to be the we can just add everything to be the next of it and it's just gonna make it a next of it and it's just gonna make it a lot lot easier and when we're returning it we're easier and when we're returning it we're just gonna do just gonna do return head dot next okay so kind of return head dot next okay so kind of keeping that in mind we need to keeping that in mind we need to uh store the head value so to do that uh store the head value so to do that i'll be storing it in a value called i'll be storing it in a value called current okay and the reason we're doing current okay and the reason we're doing that is just so that we can refer to it that is just so that we can refer to it later later now one more thing is that we're giving now one more thing is that we're giving it a value of zero it a value of zero so why are we giving it to value of zero so why are we giving it to value of zero so the reason to that is right over here so the reason to that is right over here so over here we're going to check so over here we're going to check if the sum is equal to zero if the sum is equal to zero so if the sum is zero then we can just so if the sum is zero then we can just directly return the head that we have directly return the head that we have so in that case we're just gonna be so in that case we're just gonna be returning head list node zero returning head list node zero so yeah we're done okay but if that's so yeah we're done okay but if that's not the case well we need to do some not the case well we need to do some stuff and we need to add stuff and we need to add uh on to our linked list so uh i'll just uh on to our linked list so uh i'll just be copying it over be copying it over because i think it's kind of repetitive because i think it's kind of repetitive so um so um this is what we have so while the sum is this is what we have so while the sum is greater than zero greater than zero each time we do that we're going to keep each time we do that we're going to keep going inside in simple words going inside in simple words uh until so in this case uh we have 78 uh until so in this case uh we have 78 then we have 7 then we have 7 and then when you do 7 divided by 10 you and then when you do 7 divided by 10 you get 0.7 and well 0.7 when you round it get 0.7 and well 0.7 when you round it down down because that's what we're doing it's because that's what we're doing it's going to give us a value of 0 going to give us a value of 0 and well 0 is not greater than 0 and well 0 is not greater than 0 obviously obviously so yeah so in that case we would not go so yeah so in that case we would not go into the while loop so now we have head into the while loop so now we have head dot next dot next is equal to list node okay so we're is equal to list node okay so we're creating a list node object creating a list node object and the value of it is going to be our and the value of it is going to be our sum sum mod 10 okay and i went over how we're mod 10 okay and i went over how we're getting that value getting that value and now what we need to do is we need to and now what we need to do is we need to change the head pointer so head is equal change the head pointer so head is equal to hat dot next to hat dot next and simultaneously we're going to change and simultaneously we're going to change our sum value our sum value so we're going to be doing integer so we're going to be doing integer division by 10 and the reason we're division by 10 and the reason we're doing integer division doing integer division is well we want an integer value and is well we want an integer value and basically what it does it's always going basically what it does it's always going to be rounding it down to be rounding it down okay so we have this and uh now we have okay so we have this and uh now we have a linked list a linked list but now what we need to do is we need to but now what we need to do is we need to reverse it so i'll just be copying over reverse it so i'll just be copying over the code for how to do that the code for how to do that and then we'll explain uh okay and then and then we'll explain uh okay and then i'll go over how we can do that i'll go over how we can do that all right so over here we're going to all right so over here we're going to start off with a previous pointer start off with a previous pointer because because while we're reversing it what we're while we're reversing it what we're really doing is we're storing really doing is we're storing what the previous pointer is so in the what the previous pointer is so in the very beginning very beginning the previous pointer over here is going the previous pointer over here is going to be none to be none and the head value is going to be and the head value is going to be current.next current.next so now the question is why is it so now the question is why is it current.next current.next so if you go up over here remember that so if you go up over here remember that current is just kind of like a pointer current is just kind of like a pointer to tell us what the starting of the list to tell us what the starting of the list node is node is and like i said earlier the starting is and like i said earlier the starting is going to be a going to be a value of zero and that's just going to value of zero and that's just going to be a dummy head be a dummy head so everything to the next of it is so everything to the next of it is actually what is being counted actually what is being counted so that's what we're actually going to so that's what we're actually going to have head is going to be equal have head is going to be equal to current dot next so now we're going to current dot next so now we're going to go inside of this uh as long as our to go inside of this uh as long as our head value head value head has a value and it's not equal to head has a value and it's not equal to none none so over here we have a next node and so over here we have a next node and this over here is going to store the this over here is going to store the head dot head dot next and over here what we're going to next and over here what we're going to do is we're going to have do is we're going to have head dot next equal to the previous head dot next equal to the previous value so it's just pointing to value so it's just pointing to its reverse and after we do that the its reverse and after we do that the previous pointer is going to uh equal to previous pointer is going to uh equal to the head the head and the head is going to be equal to the and the head is going to be equal to the next value so next value so literally all we're doing is reversing literally all we're doing is reversing it step by step so 0 over here is going it step by step so 0 over here is going to be pointing to 7 to be pointing to 7 the 8 is going to point to 0 and the 7 the 8 is going to point to 0 and the 7 is going to end up pointing to 8 is going to end up pointing to 8 and writing this like this is the same and writing this like this is the same as writing it as it is as writing it as it is like this so 7 then 8 then 0 then 7 okay like this so 7 then 8 then 0 then 7 okay so yeah um so this is one way you can do so yeah um so this is one way you can do it and if you submit it it should get it and if you submit it it should get accepted accepted okay so the submission was accepted so okay so the submission was accepted so another way i actually another way i actually found this uh online so what they did found this uh online so what they did was pretty clever and uh let's just kind was pretty clever and uh let's just kind of go to that directly of go to that directly so how they did it was basically head so how they did it was basically head dot next dot next is over here right so head dot next is over here right so head dot next equals to list node equals to list node sum mod 10. so we went over why that sum mod 10. so we went over why that works and how that works works and how that works but one more thing that they ended up but one more thing that they ended up doing is they made the self.next value doing is they made the self.next value equal to whatever the current node over equal to whatever the current node over here is so it is kind of confusing so here is so it is kind of confusing so i'll just kind of draw it out to better i'll just kind of draw it out to better explain it so in this case uh we have explain it so in this case uh we have 7807 right 7807 right so the first thing we're doing is where so the first thing we're doing is where we have a node uh which is zero we have a node uh which is zero all right let's just get rid of this so all right let's just get rid of this so seven eight zero seven and we're gonna seven eight zero seven and we're gonna have a dummy node with the value of zero have a dummy node with the value of zero so now what we're gonna do is we're so now what we're gonna do is we're gonna point this value over here gonna point this value over here to uh the number seven so while we are to uh the number seven so while we are pointing it to the number seven pointing it to the number seven this over here is going to store the this over here is going to store the head dot next value head dot next value and it is also going to have the head and it is also going to have the head dot dot next next value so how exactly does this next next value so how exactly does this make sense make sense so basically what's gonna happen now we so basically what's gonna happen now we have seven and now when we're about to have seven and now when we're about to add zero add zero what's going to happen is head dot next what's going to happen is head dot next already points to zero already points to zero so in this case uh what we're doing is so in this case uh what we're doing is head dot next for head dot next for zero is going to end up being the number zero is going to end up being the number zero itself so we now have zero and zero itself so we now have zero and actually don't think of this as a zero actually don't think of this as a zero but just think of it as a dummy head but just think of it as a dummy head so we're pointing this to zero and now so we're pointing this to zero and now this zero this zero is automatically going to point to seven is automatically going to point to seven because head dot next equals zero because head dot next equals zero and we already defined the head dot next and we already defined the head dot next next is equal to seven next is equal to seven so that points over to seven so now we so that points over to seven so now we have eight have eight and it's going to do the same thing and it's going to do the same thing instead what's going to happen is that instead what's going to happen is that head dot next over here head dot next over here is now going to be at zero and so is is now going to be at zero and so is head dot next next head dot next next all right so basically all we did is all right so basically all we did is head dot next equals to list node sum head dot next equals to list node sum and we want to tell it what the next and we want to tell it what the next value is and well in this case the next value is and well in this case the next value is just value is just head dot next okay uh and now let's head dot next okay uh and now let's submit this oh actually we need to submit this oh actually we need to return a value as well return a value as well so the value we're going to return is so the value we're going to return is going to be our current going to be our current dot next and one more thing that we dot next and one more thing that we would need to be doing would need to be doing is will you get rid of uh head equals to is will you get rid of uh head equals to head dot next because head dot next because basically we're not going to be moving basically we're not going to be moving the pointer each time the pointer is the pointer each time the pointer is going to stay going to stay at the same value or at the dummy head at the same value or at the dummy head the entire time the entire time right so we're not changing the pointer right so we're not changing the pointer we're not moving it so we can just get we're not moving it so we can just get rid of this over here rid of this over here so let's submit this and this should so let's submit this and this should also get accepted and as you can see also get accepted and as you can see both the solutions were accepted both the solutions were accepted so yeah thanks a lot for watching guys so yeah thanks a lot for watching guys do let me know if you have any questions do let me know if you have any questions and don't forget to like and subscribe and don't forget to like and subscribe thank you thank you [Music] | 2024-03-22 12:45:26 | 445 | Add Two Numbers II | Leet code 445 | Theory explained + Python code |
|
E6lfc0Q0h-g | hey everybody this is larry this is me going with q1 of the buy weekly contest going with q1 of the buy weekly contest 47. 47. find nearest point that's the same x y find nearest point that's the same x y coordinates um coordinates um to be honest hit the like button to to be honest hit the like button to subscribe on drumming discord if you're subscribe on drumming discord if you're here here thanks for your support because i don't thanks for your support because i don't really think really think this is a hard problem you can look at this is a hard problem you can look at my code my code but it's just basically implementing but it's just basically implementing what they tell you to do um you just what they tell you to do um you just have a for loop to kind of look at have a for loop to kind of look at what's closest to x and which goes to i what's closest to x and which goes to i and then you just keep and then you just keep track of it um i don't know if there's track of it um i don't know if there's anything complex about this uh this is anything complex about this uh this is all one space of end time all one space of end time for reasons that you can kind of look at for reasons that you can kind of look at it's a for loop and it has only constant it's a for loop and it has only constant number of number of items i'm not going to dig into this items i'm not going to dig into this that much after that so that much after that so let me know what you think if you have let me know what you think if you have any questions then just ask in the any questions then just ask in the comments comments and you can watch me solve it live and you can watch me solve it live during the contest next during the contest next one go go go one go go go [Music] huh oh and same x or y whoops hey uh thanks for watching uh hit the like button subscribe and join me on discord let me know what you how you did this contest and how you doing each of the problems um yeah have a good day have a great weekend you know to good health to good mental | 2024-03-22 14:34:00 | 1,779 | 1779. Find Nearest Point That Has the Same X or Y Coordinate (Leetcode Easy) |
|
sDMA9loAhH4 | what's up guys today we're gonna talking about today we're gonna talking about electrical problem named electrical problem named spiral matrix 2. this is a medium spiral matrix 2. this is a medium category problem category problem the problem is asked by several giant the problem is asked by several giant companies like facebook companies like facebook microsoft linkedin oracle etc microsoft linkedin oracle etc uh the problem is pretty straightforward uh the problem is pretty straightforward and here is the estimate is given a and here is the estimate is given a positive integer positive integer n generate and n cross n matrix field n generate and n cross n matrix field with with elements from 1 to n square in spiral elements from 1 to n square in spiral order order if you guys don't know about the if you guys don't know about the experiment then please google it experiment then please google it we'll first discuss about the problem we'll first discuss about the problem and then we'll go through the code and then we'll go through the code we must fill up a 2d array from 1 to n we must fill up a 2d array from 1 to n square just like this 1 2 3 4 square just like this 1 2 3 4 5 6 7 8 9 let's go through another example guys this is a two-day array and for this example n is equal to four and we have to build an array like this one two three four 5 6 7 8 9 10 11 12 13 14 15 and 16 and this is the end point and this is our starting point so what we have to do first we have to print this line in increasing order from from starting column to ending column after that we have to print uh from starting row plus one to uh till ending row after that after that we will print the left side column end minus 1 uh till column column end minus 1 uh till column starting point starting point and then we'll paint on this side after and then we'll paint on this side after that this side that this side this side and this side finally this side and this side finally we can use a counter variable to restore we can use a counter variable to restore uh uh every grid's value like if we start from every grid's value like if we start from this grid and we will set this counter this grid and we will set this counter to on to on after every iteration we will increment after every iteration we will increment the value of the counter the value of the counter uh so what we uh next iteration it will uh so what we uh next iteration it will be two then three then four then five be two then three then four then five in this order and in this order and we have to we have to keep every time we have to we have to keep every time our range uh just like this arrange is our range uh just like this arrange is formed formed is starting column to ending column and is starting column to ending column and this this range is this this range is formed starting row to ending row formed starting row to ending row if you consider this those two grid if you consider this those two grid those are from those are from starting column plus one uh till ending starting column plus one uh till ending column minus one column minus one we have to for uh we have to store four we have to for uh we have to store four values strictly values strictly uh row start row end column start and uh row start row end column start and column end column end okay now let's see okay now let's see [Music] [Music] what will be the code for c plus plus so we need a big we declare the vector and we need a size we declare the vector and we need a size n which will in uh every contain n which will in uh every contain also inverse which means every uh also inverse which means every uh here we declare uh here we declare a here we declare uh here we declare a vector size n vector size n which means the vector will contain n which means the vector will contain n rows and every row rows and every row has n elements right has n elements right vector size n so we declared a n cross n vector after that we need four fixed variable which are row row in column start as we add zero and ending as n minus one as we add zero and ending as n minus one so we need a counter variable for so we need a counter variable for counting every time the grid counting every time the grid which value we will store in the grid okay now what we have to do we have to okay now what we have to do we have to uh uh use loops for storing the values into use loops for storing the values into the the grid okay now what we will do guys uh first we now what we will do guys uh first we will will uh first we will uh first we will fill up this row first column and plus plus and we can extra values in the answer counter plus plus counter plus plus [Music] [Music] because every time we need a increment because every time we need a increment value from the previous value from the previous grid okay so here is the tricky point grid okay so here is the tricky point what we will do here here is the for the what we will do here here is the for the first row our row is fixed right so first row our row is fixed right so we'll use here we'll use here we'll use here we'll use here row start and we will use our i so every time this will ester values in the first row grid like one two three after that we have to go on this portion from top to bottom top to bottom okay but for this we have to uh already we start first row so we'll start from uh second row to row in okay so we'll increment the value of row start but this loop will start from row start but this loop will start from row start [Music] plus plus and the value will be plus plus and the value will be our answer counter plus plus this fixed right and so this is column after this done we have to decrease the after this done we have to decrease the value of column 8 value of column 8 because we we done this column right so now again we have to check that we are still in this conditions or not if the condition not fulfilled yet then we can use another loops if row start row for column start for column start i managements and here i managements and here the values will be answer counter plus class so what will uh the index hello okay we are using for this row right here the row is the ending row after the iteration finished we will uh after the iteration finished we will uh decrease the value of row end if the column is the is within the range so we are doing this for this line right so we are doing this for this line right and this will start from and this will start from uh row in till row start uh row in till row start after this we have to run a loop row end start i minus minus answer i call on counter plus plus after this we have to counter plus plus after this we have to increase the value of the column instead increase the value of the column instead okay and this will work to redone the answer we have to start the counter from on okay let's run this code those works fine let's submit it accept it | 2024-03-20 10:44:47 | 59 | LeetCode 59. Spiral Matrix II C++ Code Simple Solution |
|
4z33NNiXtT0 | hey hey everybody this is larry this is june 12th june 12th the 12th day of the june nico daddy the 12th day of the june nico daddy challenge i feel like i've said this challenge i feel like i've said this before but before but anyway uh yeah today's problem is anyway uh yeah today's problem is minimum number of refueling stops minimum number of refueling stops i usually solve this live so this is my i usually solve this live so this is my disclaimer so if it's a little bit slow disclaimer so if it's a little bit slow just fast forward and all that stuff just fast forward and all that stuff um yeah so i know that you you come here um yeah so i know that you you come here just for the weather report in new york just for the weather report in new york and right now is back to 66 degrees and right now is back to 66 degrees which which in a reasonable um temperature uh what you may call it like in a metric system it's it's like what did 15 or something so it's it's much chillier so uh now i have a shirt on again uh thanks for caring i still have to fix my ac though anyway okay so cars traveling from a starting destination target which is used up to okay what each station has a gas and each station has this little gas to get a car because stuff uh what man maybe maybe i have trouble reading maybe that's why i've been doing struggling lately what's the least number of reviewing stops that needs to do okay so the things are big enough that okay so the things are big enough that you wouldn't even think about dynamic you wouldn't even think about dynamic programming programming uh at least on pseudodynamic form uh at least on pseudodynamic form pseudopolynomial dynamic programming pseudopolynomial dynamic programming anyway but there are only 500 stations anyway but there are only 500 stations so let's see so the target is one what was target again so you're trying to get out guys so you're trying to go to see because they don't okay so yeah so they try to get to this distance there are stops along the way uses one liter of gas when transferring all the gas from the station to the car all the gas from the station that's a lot of okay okay huh so i mean so this is a it's gonna be essentially a breath first search problem this is the shortest path uh the way that you kind of think about the shortest path is well it is uh where did i see it there yeah the least number of refueling stops so the shortest path in that each each the cost of each path is just stopping once um and the key thing to note is that what we talked about earlier with respect to n is equal to 500 meaning that the graph is at most n squared or v squared if you want to go by graph rhetorics um and we square bring or we bring 500 and edges will be being five squared if you want to build a complete graph will be fast enough um especially for breakfast search which is which has a low constant overhead so that's probably what i'm going to end up doing uh yeah is that good enough is it um let me think a little bit for a second i think so it still may be breakfast search but the tricky thing is that there's an additional dimension with respect to the state so oh but i think that's okay okay i see because the the tricky part about this problem is that you have this concept of fear right and you can run out of feel um well that's the that's actually the easy part is running out for you but but the hard part is that you may want to stop or you or you may have extra feel um yeah let's see yeah so what i wanted to say is that so you may have extra feel from previous stop that you may want to make multiple stops and then accumulate those few to get to the longer place right for example i don't know if this is a good example but but you can imagine like if this one is 50 or some number you can imagine that you take three gas states you need to go to all three gas stations to get to the last gas station um in total but the observation here and it might not be easy i don't know if it is uh and it's kind of greedy so i don't know if it's correct which is why i don't know if this is easy which um which is that for each station that you arrive at they're only and for each station k i don't know if this is sorted if not that's fine we could sort it uh okay it does seem like that the distances are short sorted um so we can just go in one direction but otherwise we can sort it anyway so that's not the limiting factor but but the thing is that you know let's say we're at this station right so we have only n possible or k possible states where uh and the the states are the current station and the number of stops we've made before um and then we can greedily take because we're we're doing refresh search so with essentially doing it in order and you can kind of there's a little bit of corollary with dynamic programming in the sense that you and maybe it is maybe you could think of and maybe it is maybe you could think of it as dynamic programming as well it as dynamic programming as well um because the core part of dynamic um because the core part of dynamic programming is doing it programming is doing it in order if you're not doing it and um if you're not doing it with um top down say or you're doing bottoms up so yeah and you can still do it tops so yeah and you can still do it tops down but i think it's really down but i think it's really convoluted uh with respect to dynamic convoluted uh with respect to dynamic programming because programming because ajit station but yeah but at each station so the states are each um the station that we're at and the numbers of stops that we've made previously and those two things gives you um a number of a maximum number of gas that you can have in a greedy way you always want you know given these two parameters if you want to go at that um giving these two components to a state you always want to choose the one that gives you the maximal um the maximal gas or fuel um because the max because there's in a greedy way it doesn't make sense to choose one that's fuel with gas or less gas actually i guess but yeah okay so i think that's enough for me to get started it's still tricky though but let's let's see what's what's uh okay so yeah okay so yeah so we okay so usually i try to teach dynamic okay so usually i try to teach dynamic forum top style and forum top style and instead this time i'm gonna do bottoms instead this time i'm gonna do bottoms up but i might not even up but i might not even trying to think but uh which way is better but for search of dynamic programming i mean i think they're actually very similar in in construct it's just a slightly different way of thinking but let's kind of go over dp real quick maybe dp will be the number of field that you dp will be the number of field that you get to at this point so okay so the first thing and i don't usually do my streams with bottoms up because i think it's easier to explain stuff tops down your mileage may vary but i think this one is more bottoms up so let's actually um be very clear on how i do it uh with respect to defining the states right so dp i sub j is equal to um let's see we're at the ticking chase stops ticking chase stops straight previous stops the straight previous stops the amount of fuel we have and actually what amount of fuel we have and actually what i want to i want to do is maybe just do is maybe just add the target add the target and view at the end so then now we can and view at the end so then now we can just go all the way to the end just go all the way to the end maybe a little bit weird but but then maybe a little bit weird but but then now that means that we put in one of the now that means that we put in one of the states so that we don't have the states so that we don't have the special case and that's the basic idea special case and that's the basic idea um um so now we we're going to start by so now we we're going to start by putting the amount of view we have as putting the amount of view we have as the base case the base case so what is the base case the base cases so what is the base case the base cases we have we have is i mean you could define the base states in a couple of ways you can also start by having a station of zero zero or something or zero and the starting field so maybe that's two um so you can do something like um what is it uh zero starting field that's the equivalent state um maybe that's a little bit awkward i don't know if it is but it depends on your preference but as long as you're consistent about defining your boundaries is okay so what i want to do here is that for i in range of n and this is the new n i with zero and this is of course as we i with zero and this is of course as we use the definition here use the definition here to taking zero previous stops meaning to taking zero previous stops meaning that everything is going to be from the that everything is going to be from the starting field starting field um and actually in this case we should um and actually in this case we should actually have let's just do negative actually have let's just do negative infinity for impossible infinity for impossible um um right instead of zero because maybe zero right instead of zero because maybe zero implies that we could get there but with implies that we could get there but with zero fuels so having negative makes zero fuels so having negative makes sense here sense here a little bit um okay so that that means a little bit um okay so that that means that this that this is basically our starting field because is basically our starting field because we start from zero right we start from zero right just making sure yeah we just making sure yeah we um uh yes okay use of the starting um uh yes okay use of the starting location which i guess location which i guess is there so starting feel minus station is there so starting feel minus station sub i of 0 because that's just the sub i of 0 because that's just the distance that we have to distance that we have to move and that's the starting field so move and that's the starting field so that's our base case right that's our base case right and then now after we have the base case and then now after we have the base case set and of course as i mentioned earlier this could be negative um maybe that's fine in that we that that denotes that it is impossible do i think we have to be a little bit do i think we have to be a little bit careful i mean i think for the starting careful i mean i think for the starting state is fine state is fine but i think we have to be a little bit but i think we have to be a little bit careful because sometimes you do a careful because sometimes you do a math in a way such that the negative math in a way such that the negative could become positive could become positive for example you have a gas station later for example you have a gas station later that has like a million gas that has like a million gas then then that's an error so that's then then that's an error so that's actually actually that's actually um let's actually make that a case so that we're at least consistent about it because otherwise this would still be negative uh infinity so then now that one do i or j loop so the transition what is the transition we we might we i'm not sure about the loop ordering uh i think it might not matter i think that's why i do the loop ordering this way but now the way that i'm doing it i'm making it an n so now it becomes a little bit sketch i think i did the math a little bit long on this one to be honest my bad this 500 cube is going to be 125 million which is going to be slow because what i realized now is that i needed another loop um to make this n cube um or i think we have the states but then we do have to have another loop to get the graph um which makes it end cube i think i when i created a new state i i today i wasn't thinking let's see so how can we exploit this a let's see so how can we exploit this a little bit better okay i think i have and i do is to spray no is to spray no okay i think i have another way of doing okay i think i have another way of doing it i think i messed up here sorry friends if you're watching live or you know um hopefully i didn't lead you to the wrong direction so let's just finish off the dot and then um i'll show you why this is incorrect or this is too slow just in case uh basically this is the this is going to be max over dpi some previous k so for k and it is in range to i or maybe some some sort of push but the or maybe some some sort of push but the idea is that okay so now we have some idea is that okay so now we have some you know this is the maximum view that you know this is the maximum view that we we so we have to do push dp maybe so we so we have to do push dp maybe so we actually want it this way actually want it this way so we this is if dpli is greater than so we this is if dpli is greater than i guess maybe strictly i don't know so i guess maybe strictly i don't know so this is the amount of fuel we have this is the amount of fuel we have and then here we can go okay and then here we can go okay right now we go for k is in range sub right now we go for k is in range sub n uh starting from i plus one say n uh starting from i plus one say um yeah then you can do if so this is the amount of fuel that we have that means that we can check whether we can get from here to deep um yeah so from stations sub you know a few needed is equal to the stations uh you know so we're going from station sub i to stations and so we have something like this so then dp sub uh k sub j plus 1 because we're making an additional stop is equal to dp of i confu minus view needed confu minus view needed uh and then max of this because it you uh and then max of this because it you know you just always want to get the max know you just always want to get the max uh if current view is greater than of uh if current view is greater than of you if you need it you if you need it so that's basically the dynamic so that's basically the dynamic programming uh a solution and then you programming uh a solution and then you just go for the loop but the problem is just go for the loop but the problem is that that in this case it is going to be n cube uh in this case it is going to be n cube uh which i which i to be honest is my bad i i'm sloppy to be honest is my bad i i'm sloppy about it about it but that's basically the idea and this but that's basically the idea and this would be done if if n is say a hundred would be done if if n is say a hundred this would be pretty much done this would be pretty much done and we don't have to worry about it um and we don't have to worry about it um yeah and then there's only one minor yeah and then there's only one minor loop that you have to do loop that you have to do to to yeah there's only one minor loop to to to uh see at the last station um how you know how many or what what's reachable and the fewest number of stops right so basically you check d p sub n minus one of zero then dp sub n minus one of one and so forth um that's gonna so again this is gonna be n cube which is too slow so let's start over a little bit but it is a good practice in dynamic programming um i guess anything is good practice and i don't do it bottoms up enough so hopefully this was at least some word illustrative but i think i have another way of doing it uh well i have to because otherwise this doesn't solve the problem um so the thing to notice is that going from left to right um we can actually actually exploit the order a little bit more we basically have a march of time that we basically have a march of time that happens happens um you can think about it as a scanline um you can think about it as a scanline e e algorithm right uh in that okay you know it we we take a concept that is taken here but yeah in here we basically i yeah in here we basically i don't know how i made the same type of don't know how i made the same type of tries but in here it's dynamic tries but in here it's dynamic programming with respect to the state programming with respect to the state but here but how we i want to solve it but here but how we i want to solve it now is actually through a scan line now is actually through a scan line algorithm algorithm and the idea is that okay and the idea is that okay we arrive at every station let's take we arrive at every station let's take the same states that we have for dynamic the same states that we have for dynamic programming but programming but same logic anyway i mean it's not quite same logic anyway i mean it's not quite the same stage and then put up okay the same stage and then put up okay let's say i arrive at um and actually maybe it's the same maybe i mean i think you think about a scanline but here instead of doing this loop of going forward um we can update it in a smarter way um we can update it in a smarter way such that we don't keep we don't need such that we don't keep we don't need this loop so let's eliminate this loop this loop so let's eliminate this loop maybe that's the better way of thinking maybe that's the better way of thinking about it about it um yeah okay so let's let's we think how we want to structure this so actually i retract what a little bit of i said it's still going to be dynamic programming but with but you can also think about it as not dynamic programming if you if you just think about it as a scan line going from left to right okay let's say i'm at the station but i don't have to use a stop how much gas do i have left right so now we have this state of um yeah man that is yeah that is a trickier problem but it's still doable obviously but okay so how do we want to think about this correct but instead of push let's think correct but instead of push let's think about how we want to structure it about how we want to structure it so then now let's just say we are now at so then now let's just say we are now at station i station i and we want to loop for how many stops and we want to loop for how many stops we made and then now what does that mean we made and then now what does that mean right right so dp of i sub j so dp of i sub j is equal to the max of so what are our states so we want to update this and the only two place so so the question from a previous state is whether we are taking a stop or not right so we are so so it has to be a function of dp of i minus one which is that okay so not stopping so that means this this minus so this is the field that we had before and then we minus this delta and distance which is you know what the fuel needed right uh if you need it so again if you need it is just to go to station of um j sub 0 minus oops oops i sub 0 minus stations of i minus 1 0 right so that's a few needed let's put it outside um yeah so this is not stopping um if we do stop then um if we do stop then it's something like j minus one minus few needed plus station sub um i plus one because this is now this is the field we added right so yeah and we could maybe add that here if you want just this is just obviously if you want just this is just obviously for readability for readability in a very minor way uh for in a very minor way uh for it you know you could see what i'm doing it you know you could see what i'm doing here i mean i'm just doing for here i mean i'm just doing for obviously learning um but yeah um and of obviously learning um but yeah um and of course course this is actually the max of these two i this is actually the max of these two i mean mean in this way um yeah the of course the problem is that it might be infinity so uh so let's actually bump this up a yeah uh so yeah uh so at some point it impedes a performance at some point it impedes a performance so let's just actually say so let's just actually say um um [Music] yeah because we want to make sure that this is is the part that i'm always a little bit and the base case is also a little and the base case is also a little different now i have to we just set the different now i have to we just set the base case base case is dp of zero of zero is eq um store start field um store start field my minus station sub zero my minus station sub zero sub zero yeah the distance right sub zero yeah the distance right because that's also the few needed as we because that's also the few needed as we uh know this is basically it i have to handle some i think maybe let's actually write it up if you need it is greater than uh more fuel than fuel needed then we can more fuel than fuel needed then we can do this thing do this thing [Music] and then also if or still and this one is actually a little bit and this one is actually a little bit more critical because more critical because uh even though this entire expression uh even though this entire expression could be greater than zero could be greater than zero this could be negative and that would be this could be negative and that would be a that would not be a right answer a that would not be a right answer because that's because that's negative even though you it comes up to negative even though you it comes up to be greater than zero afterwards be greater than zero afterwards so yeah um oops and then now we have this a sort of a scanline dynamic programming we can just go through the loop again as we said which is that four i is in range of um uh if dp sub uh uh if dp sub uh n minus 1 i is greater or equal than 0 n minus 1 i is greater or equal than 0 then we then we return i otherwise return negative 1. return i otherwise return negative 1. oops how did that oops how did that that was a bad typo but yeah um that was a bad typo but yeah um that's at least one one the examples oops a few needles not defined did i just have a typo well that's a little bit of a sadness well that's a little bit of a sadness hmm do i have all my indexes correctly okay that's a little bit accurate all oh yikes okay let's make the infinity slightly okay so for this problem we have okay so for this problem we have negative infinity the entire way negative infinity the entire way why is that so yeah so the base case is we get to oh no this [Music] [Music] i think that's this is the part that in i think that's this is the part that in the beginning i was saying uh the beginning i was saying uh yeah because this phase case is wrong so yeah because this phase case is wrong so that's a short answer that's a short answer because yeah this base case as well um this is yeah this base case as well um this is the base case for the first one the base case for the first one but yeah okay but yeah okay so actually we want an additional base case of and this is actually what we had before so i think i messed up in removing that one to be honest still negative one but at least a still negative one but at least a slightly better negative one maybe let me do if start feel oops why am i so bad why is this one well j has to be starting from one but that is still very wrong huh but that is still very wrong huh that is awkward feel like i've been really bad at an feel like i've been really bad at an implementation lady i think this is implementation lady i think this is roughly right roughly right but i'm off by a little bit which is you know pretty binary and how much storing field we have so we how much storing field we have so we have ten yeah so then here oh i see okay i i i forgot one base case of um i think this is the part where as i was saying earlier we had created a fake station that would have been uh much better but yeah but we had to do um yeah plus station so that's basically um yeah plus station so that's basically the base case of us the base case of us refueling from the first stop refueling from the first stop and i guess we have to do it here as and i guess we have to do it here as well well which is very awkward oh wait because maybe wait what what is this swamp in this uh whoops this should be is now this is the right syntax right oh i see now it's not just that this is oh i see now it's not just that this is wrong this is wrong this is that this is wrong because now you can have end stop okay i don't know what to tell your okay i don't know what to tell your friends let's see if this oh let's see if this oh i i think when i rewrote this i i left i i think when i rewrote this i i left out something okay out something okay there you go because you have to still there you go because you have to still remove the fuel that is needed remove the fuel that is needed like i said really sloppy these days like i said really sloppy these days with the implementation with the implementation um okay so this is expected and it's um okay so this is expected and it's impossible but impossible but why tell me why why tell me why oh because this case is oh because this case is is very sloppy um on my part to be is very sloppy um on my part to be honest honest um because i think for i think we said um because i think for i think we said this before which is that what i should this before which is that what i should have done is to create a have done is to create a a send no stop station and that would a send no stop station and that would have been okay okay have been okay okay um now that we we look a little bit um now that we we look a little bit better better and kind of auditing real quick and kind of auditing real quick um yeah it looks okay um yeah it looks okay make sure that we don't put anything one make sure that we don't put anything one one more time and then let's give it a one more time and then let's give it a submit how do we get time limit exceeded for an n square solution and they don't even tell you the case and they don't even tell you the case okay well i guess so the good thing is okay well i guess so the good thing is that we're correct that we're correct but the bad thing is that we're too slow which is kind of weird because as you see but but i don't know why they make things such i don't know why they make things such uh such pain but okay hmm mean there are things to do to hmm mean there are things to do to optimize the space but this is just silly though to be honest um so i think at this point uh let's go with complexity real quick um and this should be straightforward in terms of complexity because this is just n square right we have two for loops it's pretty straightforward we do all of one operations each and then at the very end we do an oven loop but that's pretty much it so n squared for n is equal to 500 i don't know why this is too slow uh this is kind of annoying me trivial to be honest um i mean i know that there are a couple things i can do i could stop calling max but it's not even that many operations unless unless i'm doing something really weird but but i passed all the cases it seems like it's just that the total time is a little bit slow for their taste and you can also optimize the speed but even at 500 squares not that much so i don't even know well like for example you can do this this is greater than dpi just json this is greater than dpi just json oops oops so you can do something like this so you can do something like this because i think max function is a little because i think max function is a little bit slow bit slow but that's like really awkward right and also i would also say that uh for the for those of you who are always jealous of of oh man i have to do this again uh those of you who are jealous of of python uh well this is a reason not and also for those of you who uh who are and also for those of you who uh who are still watching still watching and didn't skip forward leave a comment and didn't skip forward leave a comment in the comment section in the comment section i want to give you props for kind of i want to give you props for kind of sticking with me sticking with me uh though maybe i i i like to think that uh though maybe i i i like to think that it's very informative it's very informative even the wrong things that i'm doing um even the wrong things that i'm doing um because i think i spend a couple of time because i think i spend a couple of time on on wrong things but on on wrong things but i spent some time on doing things i spent some time on doing things incorrectly incorrectly but um is still linear time solution is still linear time solution i don't know at this point it's kind of i don't know at this point it's kind of really annoying because at really annoying because at n square um as this is something that i n square um as this is something that i complain about right n square at n is complain about right n square at n is equal to 500 for most languages this equal to 500 for most languages this should be good should be good um and then um but the thing is that you never know the number of test cases that they're going to give you in this case it's 198. um i mean let's say we optimize our code two times faster right well what if it fails for 400 test cases right and they don't tell you the number of test cases so so that's always going to be a little bit awkward hmm can i do a little can i be a little hmm can i do a little can i be a little bit smarter bit smarter i mean the thing is that these i don't i mean the thing is that these i don't do anything that computationally do anything that computationally expensive i think python is just a expensive i think python is just a little bit awkward and slow little bit awkward and slow perhaps yeah i don't know that i can optimize i mean and that's just a linear time solution that i don't know about i mean if there's a greedy i don't know i mean if there's a greedy i don't know how to prove it so i think that's the how to prove it so i think that's the part that i'm skeptical about and i would say that even if i like if i did uh breakfast search like i said earlier i don't think this would be um i don't think it'll be much faster so i think for cheating i'm gonna change this to another language for today um and then and then we'll go over other people's solutions um just to see maybe i missed something really obvious but i think like for me you know the code is i feel like it is um it's straightforward enough right so so yeah how do i add something to an interview in python actually i don't think that you can but actually i don't think that you can but maybe i'm maybe i'm i just want to see if i missed something i just want to see if i missed something let's create a newer way okay fine i mean it's fine we can just use uh we'll have to do it in um in a silly way but so basically now what i'm doing just so basically now what i'm doing just literally translating this code to java literally translating this code to java um i do have a little bit of a java um i do have a little bit of a java background i used to do competitive in background i used to do competitive in java back in the top code of days java back in the top code of days so i'm not you know but it is also i'm so i'm not you know but it is also i'm really out of shape really out of shape so yeah let's see so if you have any comments about my java uh let me know because can also improve on it not you know yeah but this is what i always say right but this is what i always say right which is that which is that you know languages is just a tool and you know languages is just a tool and obviously obviously you still have to get your tools in good you still have to get your tools in good place place but but once you learn it but but once you learn it uh you know the hard part is always uh you know the hard part is always going to be the algorithms because it going to be the algorithms because it you know you know it is what it is you can probably i mean at this point i give you a lot of permission to uh fast forward through uh because and it might be boring for a little and it might be boring for a little while i don't really have much to say while i don't really have much to say since since i'm literally just copying and pasting i'm literally just copying and pasting code uh in it code uh in it in a non-cheating kind of way but it is in a non-cheating kind of way but it is essentially what i'm doing essentially what i'm doing right like i don't like if you look at right like i don't like if you look at the bottom and i'm what you see on the the bottom and i'm what you see on the screen is what i'm doing screen is what i'm doing we look at the bottom part this is we look at the bottom part this is literally what i'm doing literally what i'm doing so i don't really you know i'm not there's no higher level you know i'm not there's no higher level thinking thinking this this code is pretty this this code is pretty straightforward to i'm going to do this for now also i have i'm going to do this for now also i have to to set this up oh i see wait i messed this up if you need it is almost messed that up so even in uh copy and pasting i i almost messed up i and again as i was saying um and again as i was saying um i don't know maybe there's something i don't know maybe there's something really fundamental i'm missing but but really fundamental i'm missing but but it it at a certain level this is all going to at a certain level this is all going to be about grind and what i mean by that be about grind and what i mean by that is that is that you know you can always there are you know you can always there are there are multiple routes to uh to a there are multiple routes to uh to a prom solution prom solution and you know don't give up keep going and you know don't give up keep going it might not be the optimal it might not it might not be the optimal it might not be cool it might be messy be cool it might be messy but but uh but but uh you know it is what it is what is this oh oh yeah because now we don't add oh i messed this up because i said that i would uh i don't want to change what i wrote just i don't want to change what i wrote just now so now so but basically what you would do is just but basically what you would do is just do an do an do a loop from the end i guess do a loop from the end i guess yeah let's do it that way instead um yeah let's do it that way instead um okay so this is the number of gas we okay so this is the number of gas we have have uh where are we trying to go again uh where are we trying to go again target if this station uh target minus station station uh target minus station n minus one sub zero so this is the few n minus one sub zero so this is the few needed is greater than zero all right so this is greater than zero all right so this is the field that is needed is the field that is needed so if the few that we have is squared so if the few that we have is squared and few that's needed and few that's needed okay maybe that's enough oh i mean that just this is fine but it doesn't address the part that we're here if n is oops but if n is c well let's just special cases but but yeah uh what you see me now is doing a lot of special case which is why um which is why i did the thing that i did in python so that i don't have to worry about all these weird edge cases with n is equal to zero for example so um so that's basically what i'm hacking around if the star view is greater than you go if the star view is greater than you go to target to target then we can return zero otherwise with a then we can return zero otherwise with a negative one um but yeah but you can see that these cases are not needed if i had did what i did before um and yeah let's give it a submit hopefully this time it should be good i think i have it off by one okay so maybe this part is wrong let's see so our few is 50. which one is target again target is 100 which one is target again target is 100 it's time 50 so this should this should be good oh i think now this has to be yeah because because the end before doesn't include the last stop and now i have to include the last stop whoops like i said a lot of things change when you change some stuff so uh oh this is what happens when you this is this is what happens when you this is why i did it in python the way that i why i did it in python the way that i did it with respect to adding a number did it with respect to adding a number because now i have so many weird edge because now i have so many weird edge cases okay let's cases okay let's let's go back to that um let's just create another copy i this is such a mess uh yeah this is such a mess uh cowbooks sometimes coding is pain and this is one of those times mostly because i bring all this on lead code of course because really we should have been done 20 minutes ago but now i'm debugging silly things in in uh in java and in java and if there's a cleaner way to do this let if there's a cleaner way to do this let me know in java if you're a java expert me know in java if you're a java expert i'm doing it obviously in a way whatever i'm doing it obviously in a way whatever kind of way but what am i doing wrong now i should use is that not the right syntax all this i forget new is that right okay i've just said that compiler you're what oh no point of exception i am really bad today okay most of this looks good except for what what why how what what what why how what tell me what how did this get worse okay so i have and it's just not going here so this should all be negative one what uh i'm really tired right now this was not supposed to take an hour i don't know what i blame it's only code this this is a half hour or more that i want to get back i know that took longer under half an hour but i think the beginning i i had a good time in this beginning with this problem but now that i have to change the different languages and go for all these things um it's a little bit just like silly okay my why'd i put two two isn't even oh i see because the n is no longer right that shouldn't why does that matter how did that change the result why this dp sub i don't initialize it so it just i don't initialize it so it just defaults to zero that's why defaults to zero that's why okay a lot of silly things let's give okay a lot of silly things let's give this a minute and hope it's good what a silly thing that we had to do and this is my java solution um i'm going to go over my python solution i don't know let's see this is my python solution uh which is the same except for i just had to convert it to java um yeah let me know what you think i think we went over it a little bit um the states here kind of hopefully makes sense i'm really tired so i my apologies if i'm missing something because i don't i don't even remember what i explained what i haven't anymore um so yeah you just have to go back to about maybe the 30 minutes mark if you missed it or whatever um that's all i have is n squared like i said sometimes this is going to be a grind uh and it could be on silly things it could be related to the judge and stuff like that it is what it is uh let's actually i was going to end it here but let's see if there's any obvious solutions that i've missed clearly uh maybe just agree because i don't know why that pipeline doesn't work dynamic programming so that's basically what we did i guess the heap solution would i don't i guess the heap solution would i don't um but um but i would say they should still make it so i would say they should still make it so that um that um this works i mean i don't i'm curious this works i mean i don't i'm curious whether this whether this actually runs quickly enough uh because actually runs quickly enough uh because for some reason um because this is for some reason um because this is literally exactly the same as my code literally exactly the same as my code right give a tick exactly the same as my code so i mean maybe it's a little bit shorter but but the idea is still the same so i yeah it's very weird i mean maybe i yeah it's very weird i mean maybe i should have came up with the heap should have came up with the heap solution but it solution but it but given i i think i was very stuck on but given i i think i was very stuck on n squared because n is 500 so there's no n squared because n is 500 so there's no way that i should fail way that i should fail but it is what it is and then the max okay that makes sense i suppose okay that makes sense i suppose i don't know i i need to think about it i don't know i i need to think about it a little bit um a little bit um oh that said let me know what you think oh that said let me know what you think i i i don't know i i i don't know today was a little bit weird uh yeah let today was a little bit weird uh yeah let me know what you think hit the like me know what you think hit the like button and subscribe and join me in button and subscribe and join me in discord discord hopefully this is not a uh this is not a preview of what's gonna happen during the contest later in a couple of hours we'll see what happens uh stay good stay healthy have a great weekend everybody enjoy your weekend and i'll see you later | 2024-03-22 16:37:12 | 871 | 871. Minimum Number of Refueling Stops - Day 12/30 Leetcode June Challenge |
|
yhEUwt6bdyY | Hello Hello Everyone Welcome Tension Quiet Days Ago In Dishaon Birthday 27th September List Ko Ago In Dishaon Birthday 27th September List Ko Challenge Today's Problem Missile Edison Challenge Today's Problem Missile Edison Electronic Provident Fund Should Be Electronic Provident Fund Should Be Placid List In The Amazing And Give The Placid List In The Amazing And Give The Number To Computer Classes The Video then subscribe to the Page Let's try to understand which gives an example Let's try to understand which gives an example Let's try to understand which gives an example for its ok software can see for its ok software can see the question raised upwards subscribe and subscribe subscribe now to subscribe my life is the question in new delhi so this video is at the end and this is by civil handed handed handed him over loudly z1000 fluoride subscribe him over loudly z1000 fluoride subscribe button - 10500 subscribe 2019 acid - 01 button - 10500 subscribe 2019 acid - 01 sir dabi suvidha express sir dabi suvidha express transfer for the giver example1 ok so transfer for the giver example1 ok so tomorrow morning style-19 to check if left tomorrow morning style-19 to check if left untreated properly 19 virgin lifting untreated properly 19 virgin lifting happened and real 5th same find the same happened and real 5th same find the same happened and real 5th same find the same The Number Exist in Adheen 21.05 The Number 90 - 119 Hua Tha and Classification is the Understanding Monk Body What Like This Computer Returns The Video then subscribe to the subscribe to the Page if you liked The then subscribe to be lit then subscribe to be lit then subscribe to be lit quick and they can take note of just in quick and they can take note of just in zu zu zu zu ki 2.0 ki similari it can see the question is equal to one officer da ki i will be seen in the cases subscribe Subscribe subscribe this Video not 25000 Notification friends subscribe quote hai allu dena hai karenge ek-ek pehlu between the bab.la bab.la ki sukma electronic electronic ki sukma electronic electronic pollution pollution ok so now identify the apps rights under 1751 aap Apps on Vijay Ayush were also Apps on Vijay Ayush were also Apps on Vijay Ayush were also certified as which can easily identify this certified as which can easily identify this point and then you can calculate the point and then you can calculate the Nehru Youth Center destroyed by Nehru Youth Center destroyed by multiplying brother Hello using this app multiplying brother Hello using this app lets you can always talk to Luthra to see the lets you can always talk to Luthra to see the scene more details Jhunke Subscribe now to scene more details Jhunke Subscribe now to receive new updates receive new updates receive new updates subscribe to the subscribe similarly for b ki mujhe to-do sabse zor sorry bittu hai is 120 b c v n c c c c c b b c b s c c c list play list listen this subscribe subscribe this committee this committee this committee Vijay starts from being informed and then Dr to where not to wish not to go to people subscribe to the Page if you liked The subscribe to the Page if you liked The Video then subscribe to subscribe hai ki values wich stream end and bhairu Maths Video give Subscribe Maths Video give Subscribe Maths Video give Subscribe Subscribe for latest video This Subscribe for latest video This morning and fasting Apart from a peon Calculate Decoration Light Indication Measurements should always need 1000 villages Twitter The Video then subscribe to subscribe feedji.com related tweets subscribe in use size poll feedji.com related tweets subscribe in use size poll Me Sure Status Me Sure Status subscribe to the Page if you liked The subscribe to the Page if you liked The Video then subscribe to the Video then that and hold to internet is ok now we can deposit build or function something like this subscribe screen's light list free subscribe screen's light list free 200 purification questions 200 purification questions 200 purification questions edifice the value of the question ok ok to ise miding subscribe this Video subscribe boys pe hua hai nivesh ke sunavai fikar rich person Delhi stuffing slide reddy will be latest limited equation only but andar subscribe this Video subscribe our It's Something Like This subscribe our It's Something Like This That And Will Be Absolutely Equation That And Will Be Absolutely Equation Bluetooth Dot 10 Wickets In The Worst Bluetooth Dot 10 Wickets In The Worst Position subscribe this Hair Faster Pimple Position subscribe this Hair Faster Pimple And Valuable In The Sun Dot That Video And Valuable In The Sun Dot That Video New Year 2069 New Year 2069 That I Will Call Map Sometimes Scholar That I Will Call Map Sometimes Scholar In Witch Method 40% In Witch Method 40% In Witch Method 40% Pimple New Mahal Samay Price Will Reduce Number Five Lines App Kholo Hai To Way Can Avoid Samay Strife And Content Me Something Like Friend Mukesh Soni Polish 40% Subscribe To Stop This Not Avoid You A Point And Half A Point And Half A Point And Half So Let's Get Benefits And Updates Video.com Video.com I India Server Key Will Be A B A B I India Server Key Will Be A B A B Less And Key Delicious 200 It Is Not Less And Key Delicious 200 It Is Not Exist In Amazon New Said Exist In Amazon New Said A Point Now Being A Point Now Being A Point Now Being Fluoride Map Don't Get End Against Hate Discus and Key Will Be Stopped and Went for the Thing subscribe The Video then subscribe to the Page if you liked The Video then subscribe to subscribe and subscribe Like ur Like ur Like ur right method using which you can calculate and he will return w and he can right method using which you can calculate and he will return w and he can update in update in more jis brothers ib so e will define more jis brothers ib so e will define third calculate result third calculate result my tablet diesel something like this and my tablet diesel something like this and but thursday must subscribe research Dot Net Dot Net Dot Net A I N V 2.5 Ft Get Hero Film Give Me A I N V 2.5 Ft Get Hero Film Give Me The Starting Point To Zafar DMC Posts The Starting Point To Zafar DMC Posts For Students In Softwares Daughter For Students In Softwares Daughter And Will Be 108 Youth To Do The Great subscribe And Will Be 108 Youth To Do The Great subscribe The Channel subscribe comment and subscribe The Channel subscribe comment and subscribe comment and subscribe the comment and subscribe the Channel subscribe Video Channel subscribe Video Channel subscribe Video That Guddu's Trekking Note Switzerland's Setting Open Single Soon After Defeat Friends Talk Show Host Also President of New Administrative Academy 2512 Return Award Toe Will Contest All The Results For Giving Rise Toe Follow She Also Pandit Will Sleep After Calculate Video Like it depends on the software and sleep patterns for things which seems that during value second will be OBC string and under last thing will be mother he bright so e will benefit of him officer stored in the notes notes Do Do Do Something Like This OK School Noida to subscribe to the Page if you liked The Video then subscribe to the Page if you पिचर गिफ्ट है कि स्टर्ट एंड विच दोस नहीं इस है कि स्टर्ट एंड विच दोस नहीं इस नॉट नॉट नॉट similarly destroy and talk to oo that and end debate on news9 decision no tomorrow morning minutes not possible then why friend daw or returning -1.2 hai you start and ignoring and I ok sun Quality Quality Quality of life by c-voter Hello how can they of life by c-voter Hello how can they return 120 se subscribe kar do ho gaye return 120 se subscribe kar do ho gaye ind 2nd feb 7 same din can they ind 2nd feb 7 same din can they return 120 defensive and 120 b our map ok return 120 defensive and 120 b our map ok so now 2019.com सित्छे इडली इडली सुस्क्रिबे subscribe and subscribe the subscribe subscribe subscribe I just started the hotspot of my map.net contact is contact is that encephalitis vote then share that encephalitis vote then share according to going to determine it's written a map don't get started that started that chart get and focus on twitter real chart get and focus on twitter real life to IDBI that subscribe 100 schools subscribe to That the way you tell about the last elections, more than 90 subscribe The Amazing Thursday Video Subscribe Now that boat circular diet that Ayodhya 9 and travels and the possibility of midnight fall for boys in two were double were double In The Map Don't Get Started In The Map Don't Get Started Days Instant Map Scientific Entry Set Of Days Instant Map Scientific Entry Set Of The Movies Scene Setting Show The Map Election The Movies Scene Setting Show The Map Election Banyan Tree Your Hair Right Now Right I Am You Through Which Banyan Tree Your Hair Right Now Right I Am You Through Which Everything Is E Will Check Only Will Check Only Will Check Only That I Entry's Body Engaged David Is Particular Knotted This Entry Also Ko This Entry Also Ko Start Get Start Get That Dry Vyas Twilight Its Contents That Dry Vyas Twilight Its Contents Not Interested Not Wanted To Leave It Is Not Interested Not Wanted To Leave It Is Not Go Into Bill Hans Tell Me The Map Not Go Into Bill Hans Tell Me The Map Not Go Into Bill Hans Tell Me The Map so it is not considered Sudhir Mishra of this particular notes to visit so I will take only temporary is absolutely double s declared double dip tell me I will my tab where hair oil this a middle class with Roti Ko Kah And Dar Indian Roti Ko Kah And Dar Indian Roti Ko Kah And Dar Indian Women Se Bigg Boss Minute Two Drops Steel Women Se Bigg Boss Minute Two Drops Steel 10 Se Zinc Shampoo According To Two Five Withdrawals 10 Se Zinc Shampoo According To Two Five Withdrawals Current Contents Only One Not Hidden Current Contents Only One Not Hidden From National Subscribe Button - Features - From National Subscribe Button - Features - The Video then subscribe to the Page if The Video then subscribe to the Page if you liked The Video then subscribe you liked The Video then subscribe you liked The Video then subscribe In the Destroyed Household Vitamin E Store Vouchers Defiant Sports Ministry Done Something 1992 Because Divya Badminton Something Radhe Radhe Shyam Conflict and So They Can Return - 148 Singh Datas President She Results for Not a Good Sunhra Kapil Free Things on Time Is Trick Pawan Singh Is The First Woman President Seduction Hearing Result And Chronic And Subscribe Subscribe To Ok Figure Services Accept So Let's Check The Midning Us Loud And Subscribe The Channel To Subscribe And Subscribe The Amazing Video Subscribe Nishan Nishan Nishan Dedh Map And 118 Dars Id The Video then Dedh Map And 118 Dars Id The Video then subscribe to the Page if you liked The subscribe to the Page if you liked The Video then subscribe to subscribe our Video then subscribe to subscribe our Channel subscribe and subscribe and subscribe the Video then subscribe to the Ki Wah Diya Bisht and United of BSNL Rights Have Have Have Video not support Were Fighting for a Two See Video not support Were Fighting for a Two See Ride Soil and Will Have Two One Say ZuluTrade 2098 Setting of the Day Every Twelve Years Only One Will Be the That Wishes Paste Absolutely December Subscribe to Simply This Hair Mask Were Will Be See and Be Amazed 10 Subscribe Incident Question Is The Meaning Of This | 2024-03-24 12:19:11 | 399 | Evaluate Division LeetCode 399 September Challenge |
|
9q0k3OyCKPY | hey what's up guys it's Nick white - tech encoding stuff on twitch and tech encoding stuff on twitch and YouTube do all the leak out stuff so if YouTube do all the leak out stuff so if you would do leak code check out my you would do leak code check out my other videos this is just the explore other videos this is just the explore page which helps you learn like page which helps you learn like everything you need to know pretty much everything you need to know pretty much it gives you like good tutorials so a it gives you like good tutorials so a binary search is one of the most easy binary search is one of the most easy and commonly used algorithms in like all and commonly used algorithms in like all these problems and interviews it might these problems and interviews it might be one of the first things you're asked be one of the first things you're asked so one of the first things you learn in so one of the first things you learn in class so given a sorted in ascending class so given a sorted in ascending order integer array gnomes and n order integer array gnomes and n elements in a target value are to elements in a target value are to function to search for targeted gnomes function to search for targeted gnomes so yeah basically you're just given an so yeah basically you're just given an array of numbers like this one and then array of numbers like this one and then you're given a number that you want to you're given a number that you want to look for and you just return the index look for and you just return the index that it's at so zero one two three four that it's at so zero one two three four would be nine and if you don't find it would be nine and if you don't find it then you return negative one so it's then you return negative one so it's pretty easy binary search is just pretty easy binary search is just searching the middle so it's like when searching the middle so it's like when you look for someone in a of a page in a you look for someone in a of a page in a book you open in the middle and then you book you open in the middle and then you you know keep opening in the middle so you know keep opening in the middle so let's just write this so if gnomes dot let's just write this so if gnomes dot length is equal to zero we're just going length is equal to zero we're just going to return negative one we're not gonna to return negative one we're not gonna be able to find it because the array is be able to find it because the array is like the length of it isn't zero so like the length of it isn't zero so there's nothing in the array and then there's nothing in the array and then otherwise we're just gonna have our left otherwise we're just gonna have our left bound zero go right down so beginning bound zero go right down so beginning and ending in that seat indices then and ending in that seat indices then we're gonna have our main loop so I'll we're gonna have our main loop so I'll left is less than or equal to right left is less than or equal to right we're just gonna do calculate our we're just gonna do calculate our midpoints so the middle of the array was midpoints so the middle of the array was the left our left boundary plus our the left our left boundary plus our right minus left boundary to be accurate right minus left boundary to be accurate and then we have our conditions here so and then we have our conditions here so if our numbers of midpoints if the if our numbers of midpoints if the middle of our array is equal to the middle of our array is equal to the target so first place we're gonna search target so first place we're gonna search it directly in the middle if that's it directly in the middle if that's equal to what we're looking for then the equal to what we're looking for then the great we're just gonna return let's great we're just gonna return let's actually in the midpoint will be the actually in the midpoint will be the index so perfect index so perfect else if numbers of midpoints it's else if numbers of midpoints it's greater than target that means that the greater than target that means that the target is gonna be on the left side it's target is gonna be on the left side it's binary search only works on sorted binary search only works on sorted arrays guys so that means yeah numbers arrays guys so that means yeah numbers of midpoints greater than the target so of midpoints greater than the target so we're gonna want to keep going on the we're gonna want to keep going on the left side so we're gonna get rid of the left side so we're gonna get rid of the right side so to get rid of the right right side so to get rid of the right side we're gonna make our right bound side we're gonna make our right bound equal the midpoint minus one that'll equal the midpoint minus one that'll eliminate the whole right side of our eliminate the whole right side of our search base it's basically just cutting search base it's basically just cutting the array the search base in half each the array the search base in half each loop through this while loop else we're loop through this while loop else we're gonna do left equals left is equal to gonna do left equals left is equal to midpoint plus one because that would midpoint plus one because that would mean that we're gonna go on the right mean that we're gonna go on the right side and that's pretty much it I'm gonna side and that's pretty much it I'm gonna need just do return negative one if you need just do return negative one if you can't figure out can't figure out so submitted it accepted first try there so submitted it accepted first try there we go really easy simple there's a lot we go really easy simple there's a lot of talking around me because there's I'm of talking around me because there's I'm in a library but yeah that's binary in a library but yeah that's binary search you're just searching the middle search you're just searching the middle of the array eliminating the half that of the array eliminating the half that it won't be on each time because it's it won't be on each time because it's sorted so you know that when you search sorted so you know that when you search the middle if your target is less than the middle if your target is less than the middle it's gonna be on the left the middle it's gonna be on the left side so you can just delete everything side so you can just delete everything on the right and keep going on the left on the right and keep going on the left and in a sorted array that's gonna be a and in a sorted array that's gonna be a way faster way to find what you're way faster way to find what you're looking for then you know a linear scan looking for then you know a linear scan where you go through every element where you go through every element because instead of you know looking if because instead of you know looking if you're looking for the number 10 in a 10 you're looking for the number 10 in a 10 LM in an array and it's sorted binary LM in an array and it's sorted binary search you're gonna go 5 you know 8 and search you're gonna go 5 you know 8 and then 10 or something like that 5 7 10 or then 10 or something like that 5 7 10 or something something in a linear scan you're gonna go one two in a linear scan you're gonna go one two three cross 79 times so it's a lot three cross 79 times so it's a lot faster in some cases thank you guys for faster in some cases thank you guys for watching and check out my other videos watching and check out my other videos and I'll see | 2024-03-21 10:21:28 | 704 | LeetCode Binary Search Explained - Java Solution |
|
wKe4uy2rw_o | hi friends welcome back today we are going to solve one very interesting and going to solve one very interesting and hard coding question it's on lead code hard coding question it's on lead code 928 928 minimize malware spread 2. so as you can minimize malware spread 2. so as you can see this is quite likeable problem from see this is quite likeable problem from life dislike ratio life dislike ratio so we will understand this problem uh we so we will understand this problem uh we will uh with couple of examples in will uh with couple of examples in today's session um today's session um and i'll explain you the logic how we and i'll explain you the logic how we can solve this problem and we'll also go can solve this problem and we'll also go through the java solution for the same through the java solution for the same in today's session in today's session uh before we start uh just wanted to uh before we start uh just wanted to mention that this channel is to help mention that this channel is to help people in their java jk and coding people in their java jk and coding interviews interviews on this channel you will find more than on this channel you will find more than 400 different varieties of solved coding 400 different varieties of solved coding problems problems that can help you in your coding and that can help you in your coding and java interview preparation java interview preparation so please subscribe to this channel now so please subscribe to this channel now also whenever i solve any interesting also whenever i solve any interesting and coding questions important uh and coding questions important uh problem problem i often create videos on this channel so i often create videos on this channel so that others can benefit by watching that others can benefit by watching those videos they can also understand those videos they can also understand the logic behind the problem the logic behind the problem and they can also understand the java and they can also understand the java solution so make sure you click on the solution so make sure you click on the bell notification icon bell notification icon so you won't miss any important future so you won't miss any important future videos videos so let's start with this problem 928 on so let's start with this problem 928 on lead code this is a hard coding problem lead code this is a hard coding problem minimize malware spread 2 minimize malware spread 2 so so what they are saying here is uh what they are saying here is uh basically uh is they are going to give basically uh is they are going to give us a adjacency graph right and there us a adjacency graph right and there will be some initial nodes that are will be some initial nodes that are infected by malware right some initial infected by malware right some initial nodes which are infected my malware so nodes which are infected my malware so for example i created one sample graph for example i created one sample graph here so we can use this graph uh here so we can use this graph uh for our uh explanation so you will for our uh explanation so you will understand it more this is a big graph understand it more this is a big graph so i uh so i uh specifically created so that i can specifically created so that i can easily explain this problem so this is easily explain this problem so this is what the input is given to us so graph what the input is given to us so graph input is given this is the adjacency input is given this is the adjacency matrix right so it means that which node matrix right so it means that which node is connected to each other nodes it is is connected to each other nodes it is given here right given here right so they are just saying that some nodes so they are just saying that some nodes are initially infected by malware are initially infected by malware whenever two nodes are directly whenever two nodes are directly connected and connected and at least one of those two nodes is at least one of those two nodes is infected by malware both nodes will be infected by malware both nodes will be infected by malware this spread of infected by malware this spread of malware will continue until no more malware will continue until no more nodes can be infected nodes can be infected in this manner so what they are saying in this manner so what they are saying basically is for example let's just basically is for example let's just assume uh that um assume uh that um if let's say node 2 is infected if let's say node 2 is infected basically let's say right so what they basically let's say right so what they are saying is whatever is connected to are saying is whatever is connected to node 2 will also get infected so it node 2 will also get infected so it means that 1 will get infected from 1 0 means that 1 will get infected from 1 0 will get infected will get infected on this side uh on this side uh 2 will in fact 3 3 will in fact 4 4 will 2 will in fact 3 3 will in fact 4 4 will infect 5 five will infect six like this infect 5 five will infect six like this right so this is how the malware is right so this is how the malware is spreading basically right so one spreading basically right so one infection will be spreading to the infection will be spreading to the adjacent nodes adjacent nodes and this is kind of a chain reaction and this is kind of a chain reaction basically right so that's what they are basically right so that's what they are saying so suppose there are uh initial saying so suppose there are uh initial uh like final number of nodes which are uh like final number of nodes which are infected with malware in the entire infected with malware in the entire network after the spread of the malware network after the spread of the malware stops stops we will remove exactly one node from we will remove exactly one node from this initial this initial infected nodes infected nodes completely removing it and any completely removing it and any connections from this node to any other connections from this node to any other nodes nodes so what they are saying is let's say for so what they are saying is let's say for example in this case the two node is example in this case the two node is infected let's say for example right so infected let's say for example right so they are saying that they are saying that um we will let's say remove this node um we will let's say remove this node from this network so from this network so if we remove this node then what will if we remove this node then what will happen in the network so i'll just happen in the network so i'll just erase something so you will easily erase something so you will easily understand how what happens right so um i don't know if there is a any eraser here uh yeah i think this one is the eraser maybe yeah this one is the eraser let me just erase this for example 2 is infected if we decided to remove this node 2 basically from this from this one right so now we we don't have a node 2 because we removed it right then what they are saying is after this removal we want to find out how many nodes will be infected right so that's what they are saying and return the node if removed would minimize the m initial uh if multiple nodes could be removed to minimize m initial return such a node with smallest index let me just put it back so basically let me just put it back so basically what we are doing is what we are doing is this is the graph that is given to us as this is the graph that is given to us as an input and initially they have given an input and initially they have given us us what nodes are infected so in this case what nodes are infected so in this case node two and node four are infected node two and node four are infected these no two nodes are infected these no two nodes are infected basically right basically right so um let's just first understand how so um let's just first understand how the adjacency graph works right so this the adjacency graph works right so this is important because this is the is important because this is the graphical representation i created using graphical representation i created using the input graph right so for example if the input graph right so for example if we are looking at this 0 row 0 right so we are looking at this 0 row 0 right so 0 is connected to 0 which is obvious 0 is connected to 0 which is obvious right this node 0 is connected to 0 right this node 0 is connected to 0 because each node is obviously connected because each node is obviously connected to itself so 1 means it is connected to itself so 1 means it is connected right then we go to this point basically right then we go to this point basically so 0 is connected to 1 so we put a h so 0 is connected to 1 so we put a h between 0 and 1 right then that's it 0 between 0 and 1 right then that's it 0 is not connected to anything else right is not connected to anything else right now we go to the next one now we go to the next one so we come here right now um so we come here right now um this is node 1 basically right this is this is node 1 basically right this is node 0 this is node 1 because we are node 0 this is node 1 because we are start uh using it with zero based start uh using it with zero based indices right so now node 1 is connected indices right so now node 1 is connected to node 0 that's why we put 1 here so to node 0 that's why we put 1 here so you can see that node 1 is connected to you can see that node 1 is connected to node 0 and obviously node 1 is connected node 0 and obviously node 1 is connected to itself because every node is to itself because every node is connected to itself and apart from that connected to itself and apart from that node 1 is also connected to node 2 so as node 1 is also connected to node 2 so as you can see node 1 is connected to node you can see node 1 is connected to node 2 right 2 right so like this we will go through this so like this we will go through this this is the adjacency graph that is this is the adjacency graph that is given to us this is for node two right given to us this is for node two right this is for node two so node two is this is for node two so node two is connected to node one as you can see connected to node one as you can see node one right one is here so node two node one right one is here so node two is connected to node one is connected to node one node two is connected to itself which is node two is connected to itself which is obvious that's why one is there and node obvious that's why one is there and node 2 is also connected to node 3 right so 2 is also connected to node 3 right so node 2 is connected to node 3 and that's node 2 is connected to node 3 and that's all for node 2 right there are no other all for node 2 right there are no other connections for mode 2. so i just took connections for mode 2. so i just took this graph and i just graphically this graph and i just graphically created this uh graph so you can created this uh graph so you can understand uh the solution in a better understand uh the solution in a better way way right so what the problem is saying is right so what the problem is saying is this is our network let's say and these this is our network let's say and these are our nodes from 0 to 6 right and are our nodes from 0 to 6 right and these are the connections that we have these are the connections that we have shown here shown here so initially node 2 and node 4 they both so initially node 2 and node 4 they both are infected are infected so so if we remove if we remove the node 2 how many nodes will be the node 2 how many nodes will be infected infected so let's say if we remove node 2 from so let's say if we remove node 2 from this one right this one right so i'll just uh so i'll just uh use the eraser use the eraser to show you how the to show you how the we will just kind of simulating that we we will just kind of simulating that we are removing node 2 are removing node 2 right so let's just remove this node 2 right so let's just remove this node 2 for a minute so node 2 is not there now right so now we have to find out how many nodes are infected so now node four will in fact basically node four will infect node three node four will infect node five five will infect node six so total how many nodes are infected four nodes are infected if we remove node two right if we remove node 2 total 4 nodes are infected these nodes are outside so infection will not reach them because they are not connected now to this network right so now we will simulate removing node four now right now let's remove the node four so we removed node two we saw that there are total four nodes that will uh be infected if we remove node two now we will remove node four and see how many are infected basically after removing of node four right so let me show you that we removed node four right now let's take a look how many are infected now so now two will infect one one will infect zero in fact 3 3 will infect 6 right and 6 will infect 5 so how many nodes got infected 1 2 3 4 5 and 6 total 6 nodes are infected if we remove 4 if we remove 4 total number of infections are six right so you got this much actually right so you got this much idea so now let's put it back so let's just quickly write what happened actually right so removal right removal let's say removal removal of two how many nodes got infected if we remove two four not got infected what happened when we removed fourth sixth node got infected right if we remove four so basically what the problem is asking us to find out is we have to find out a node which will do the minimum infection right minimum infection that is what is important right minimum minimum malware malware infection basically or malware spread right so minimum malware spread which one is giving minimum 2 is giving minimum right if we remove 2 we are getting only 4 nodes which are infected so this is the minimum so we have to return 2 as the answer basically for this problem right so we wanted to remove node 2 because that will create minimum number of infections right so this is what the problem is asking us to find out minimum malware spread right so um if multiple nodes now one there is one catch here right there is possibility that there will be multiple nodes which are causing the same number of infection spread right or malware spread same number so what should be written in that case then in that case we should return the node which has with minimum index right minimum index we should return in that case so uh so for example if let's say in one example let's say there are two nodes one and two which are causing minimum in uh in infections for it so which should we return we should return one because it is minimum index right so that's what so um i hope you got the return with the so um i hope you got the return with the smallest index right so i hope that you smallest index right so i hope that you are getting the idea uh what the problem are getting the idea uh what the problem is and uh is and uh that we are trying to solve in this that we are trying to solve in this decision this is a hard problem decision this is a hard problem so um so um whenever there are hard problems it whenever there are hard problems it becomes easy when you actually plot a becomes easy when you actually plot a graph like this right when you create a graph like this right when you create a graphical representation it becomes easy graphical representation it becomes easy for you to understand when there are for you to understand when there are hard problems many times right hard problems many times right so now we understood the problem so how so now we understood the problem so how we will solve this problem so what we we will solve this problem so what we will do is we will do we will use a very will do is we will do we will use a very famous techniques called as dfs right famous techniques called as dfs right depth first search or depth first depth first search or depth first traversal traversal and how dfs works is uh it actually will and how dfs works is uh it actually will use dfs on this adjacency graph use dfs on this adjacency graph so we will simulate that we are removing so we will simulate that we are removing a node for example let's say we remove a node for example let's say we remove this node let's say right then what we this node let's say right then what we will do is we will kind of removing this will do is we will kind of removing this node and whatever node and whatever nodes are remaining that are infected we nodes are remaining that are infected we will do dfs on them right will do dfs on them right so how the dfs will go now for example 4 so how the dfs will go now for example 4 is remaining node if we remove 2 2 and 4 is remaining node if we remove 2 2 and 4 are infected now we are kind of removing are infected now we are kind of removing two so now we have to go through all the two so now we have to go through all the remaining infected nodes so for example remaining infected nodes so for example in this case we will start doing dfs in this case we will start doing dfs from node 4 and we will do like we will from node 4 and we will do like we will do dfs right so four to three then three do dfs right so four to three then three two six and then six to five so all two six and then six to five so all these nodes are connected they will get these nodes are connected they will get infected because four is infected and we infected because four is infected and we will keep count of how many nodes are will keep count of how many nodes are getting infected using this dfs right getting infected using this dfs right so now as you can see four node got so now as you can see four node got infected once we do the dfs right so infected once we do the dfs right so this one we applied dfs this one we applied dfs uh when we are removing node two now uh when we are removing node two now let's say that we are removing node four let's say that we are removing node four right we are removing this node four right we are removing this node four let's say let's say right we are removing this node four right we are removing this node four so now we will have to do the dfs on the so now we will have to do the dfs on the other infected nodes so other infected other infected nodes so other infected nodes is what two is other than infected nodes is what two is other than infected node so we will do dfs on two how dfs node so we will do dfs on two how dfs will go so two will infect one one will will go so two will infect one one will infect zero so again the call so because infect zero so again the call so because we are going in depth right going in we are going in depth right going in depth that's why it is dfs so now now we depth that's why it is dfs so now now we cannot go any further right we are at cannot go any further right we are at the end so the call goes back here and the end so the call goes back here and it it explores other path now what is the explores other path now what is the other path 2 2 3 other path 2 2 3 so 2 to 3 and then 3 to 6 and six to so 2 to 3 and then 3 to 6 and six to five right five right so this is how the dfs go again the dfs so this is how the dfs go again the dfs call now will go back from five to six call now will go back from five to six and six two three and three two one and and six two three and three two one and we will keep count of how many nodes got we will keep count of how many nodes got infected in this process right how many infected in this process right how many nodes so one two three four five six so nodes so one two three four five six so six node got infected basically right six node got infected basically right because four we will not consider because four we will not consider because four is now removed right so because four is now removed right so apart from that six node got infected apart from that six node got infected right right so six nodes so six nodes so i'll just write six nodes so i'll just write six nodes so so this is how we will use our dfs and we this is how we will use our dfs and we will keep track of the minimum number of will keep track of the minimum number of nodes that gets infected right so now in nodes that gets infected right so now in this case the minimum number of nodes this case the minimum number of nodes when we are removing node 2 correct when we are removing node 2 correct because 4 is the minimum then 6 so we because 4 is the minimum then 6 so we will consider whatever is the minimum will consider whatever is the minimum right right so this is the approach we will take to so this is the approach we will take to solve the problem this is the logic solve the problem this is the logic using using bfs um bfs um so i i hope you are clear on the logic so i i hope you are clear on the logic uh how we will be implementing the logic uh how we will be implementing the logic right right so we will actually so we will actually take this in initially infected nodes take this in initially infected nodes for example two and four are infected for example two and four are infected nodes right we will simulate by removing nodes right we will simulate by removing uh one so we remove this one we go uh one so we remove this one we go through the remaining and we will do the through the remaining and we will do the dfs then we re like we remove two then dfs then we re like we remove two then we remove 4 we will go through the we remove 4 we will go through the remaining infected nodes we will do the remaining infected nodes we will do the dfs right so dfs right so one other thing before we actually start one other thing before we actually start looking the logic is looking the logic is if in this example you can just consider if in this example you can just consider that let's say that let's say let's just uh consider for a sake of let's just uh consider for a sake of explanation that there is one more node explanation that there is one more node for example which is infected let's say for example which is infected let's say node six is also infected so we have now node six is also infected so we have now total three nodes which are infected two total three nodes which are infected two comma four comma six right these are comma four comma six right these are three infected nodes which are initial three infected nodes which are initial right so this is initial right so this is initial so now how our approach will work we so now how our approach will work we will first remove two we will go through will first remove two we will go through this four and six both nodes which are this four and six both nodes which are infected right and we will try to see infected right and we will try to see how many total node gets infected but how many total node gets infected but with four and six right with four and six right then we will calculate that now after then we will calculate that now after that we will remove four we will take that we will remove four we will take the remaining nodes which are infected the remaining nodes which are infected what are remaining nodes now 2 and 6 we what are remaining nodes now 2 and 6 we will take and we will calculate how many will take and we will calculate how many total nodes get infected after only total nodes get infected after only removing 4 right with node 2 and 6 after removing 4 right with node 2 and 6 after that what we will do is we will remove that what we will do is we will remove six and we will go through the remaining six and we will go through the remaining infected nodes so remaining infected infected nodes so remaining infected nodes is what two and four so we will go nodes is what two and four so we will go through them and we will through them and we will calculate how many calculate how many uh nodes are infected with two and four uh nodes are infected with two and four because of two and four right because of two and four right and then we will decide which node to and then we will decide which node to remove actually right which will remove actually right which will minimize the malware spread right so minimize the malware spread right so this is what our approach is actually so this is what our approach is actually so we are going through all the remaining we are going through all the remaining nodes right all the remaining nodes so nodes right all the remaining nodes so for example if we are removing things we for example if we are removing things we are going through all these remaining are going through all these remaining nodes not just one mode right so you got nodes not just one mode right so you got the idea basically the idea basically so now so now um this is the um this is the idea of our logic idea of our logic so we can just go ahead and i can show so we can just go ahead and i can show you the java code now so once you you the java code now so once you understand the logic then it's not very understand the logic then it's not very difficult the implementation so this is the big graph that i was just testing actually is the same test case that i shown you uh so let's take a look at the minimal marker spread so graph 2d matrix is given to us this is the adjacency graph right so um and initial is the nodes uh this is the array of initially infected nodes right so this is the adjacency graph as you can see this is the adjacency graph right so this is given to us and i already explained you how that adjacency graph we can use to plot this graph basically right so first thing we wanted to check if the initial has a length 1 then we will just return initial 0 basically because there is only one node which is there in the initially infected nodes so we can just directly written initial 0 in that case right then we will create a min value variable it is of integer.max value will initialize it and minimum index we will create it is 0 because that is what we wanted to return at the end right minimum index so that variable we created here after that we are going this is our main for loop which will go from the initial dot length right so initially whatever is infected this is this for loop ends here and this starts here right so initially we are going through like uh basically all these infected nodes one by one right we are going through one by one this infected nodes we will create a set of integers to capture what nodes are infected because of that node actually right so um after that what we are doing here in this for loop is we are actually so for example um i was just showing you this example right when we assume that there are three nodes initially infected right so let's just take that same example two comma four comma six so this is the initial nodes what are infected right so what we are our approach is doing is we are going through this initially infected nodes one by one so we are first we are going through this node right and now we are going through all these nodes which are actually remaining right so um as you can see 0 to initial dot length we are going again and if i is not equal to j means if that node is not we are considering what what we are doing here is we are simulating that we are removing that node basically correct i is not equal to j means and then we are passing uh we are calling our dfs function right so what we will do is we we have a dfs function let's say right so dfs function we will call on 4 and six right first we will call it and four then our dfs will get called on the other other one right six basically right so we will not call it for two basically that's what we are doing right when next time when we are doing it for four when we are doing it for four next time our dfs will get called for two and six right two and six and a six right so this is what because we are trying to simulate that we are removing this node basically for example right and then we will try to calculate how many nodes are getting infected after that removal so so that's what we are doing in this for loop right uh so once this dfs is done for all the remaining nodes in the initially infected list then we now know that how many nodes are infected by because our infected set will get populated with all the nodes that are infected because of this dfs right after the removal of that node so i'll just do a print out here to show you how it uh works in detail when we execute the code here what we are doing it we are checking the in infected set size now if we are seeing the infections are less than our minimum value it means that we are finding a node which is uh infecting less number of nodes basically then we wanted to take that node right because it is spreading less number of infections so in that case we will just update our mean value to infected set size correct and the mean index will be initial of i that we are actually looking at this i is the one that we are actually simulating that we are removing the i th node basically correct initial of ith node right so initial of i is the index of that we will update that minimum index now there is another case where we are actually seeing the uh infected site size it it is equal to the same as the minimum value we had seen before it means that this node that we are actually processing is also infecting same number of nodes that we had previously seen so which one should we take then in that case we should take the one which has smaller index right so this is what we are doing here it will take the smaller index because math dot mean of initial of i and min of index will take the minimum right mean index here because this is given in the problem that if multiple nodes could be removed to minimize then we have to return the node with smallest index so this is what we are actually implementing there right so this is what we are implementing here so we will keep doing it uh in this for loop we will simulate that we are actually basically we are removing node four node two then we are removing node four then we are removing node six and we will at the end we will get the value a minimum index here that is the node that will cause the minimum number of infection spread right because of the logic that we have implemented correct now um this is the overall logic we will look details of our dfs method which is important method now right so this method returns void and it takes graph which is the which is input graph that is given to us then this is the infected set that we wanted to capture all the nodes that are infected after removal of the node right the current node is the current node that we are processing and remove node is the re the node that we are actually removing for this simulation right so for example so for example what i am going to say is when we start we will start simulating that we are removing node 2 correct so this is that removed node right this remove node is that node 2. so here what we check is if infected does not contain the current node right means it the set already should not contain that node right and our current node is not should not be equal to remove node if this is the case then we will add this current node into our infected set correct because it will get infected so we'll add it to our infected set the current node and what this one we are doing is we are going through the um graph right which is now correct connected to the current node right the current current node which are connected to the current node we are going and if there is an h between the current node and the node that we are looking it it is equal to one means there is h means they are connected then we will recursively call our dfs on it right we will recursively call now the current node will be j basically right because j is the one that we are processing so current node we will pass this j here when we are recursively calling the dfs function right so what we are doing is when we are actually let's say we are um let's say we are uh removing node two basically right we are removing node two so we will go through node four let's say right and we will call uh we will go to from four to three and four to five because they are connected to four right again we will go from three to six because three is connected to six right so this is kind of a recursion right it's basically a chain reaction you can call or you can call it recursion right recursion so this is what we will keep calling whenever there is a h we will keep calling dfs right so this is how the dfs works so it will ultimately get all this infected set will get populated with all the infections uh infected nodes basically right at the end of the dfs and after after the end of the dfs which will happen after this for loop we know by this infected size how many nodes got infected after we removed that initial of i node right so uh we will just print it out to show you how it works also so um and then this is our logic that i explained we will check the infected size with the minimum value right so i think this is pretty detailed explanation of how our dfs works and how we can solve this problem the malware spread problem so we should just go ahead and take a few test cases to execute the code so this is the test case that i was showing you so now here two and four nodes are getting infected correct so we'll take our original uh case so now we have seen that two if we remove two four nodes will be infected if we remove four six nodes will be infected so which one we should prefer number two right so let's go ahead and so as you can see 2 node 2 is the so as you can see 2 node 2 is the correct answer because it is also correct answer because it is also telling us what happens right after we telling us what happens right after we remove 2 how many nodes are infected 4. remove 2 how many nodes are infected 4. if we remove 4 how many nodes are if we remove 4 how many nodes are infected 6 right as we have seen here so let us also modify this example little bit and test the example with modify modified example let us say instead of 2 4 let's say we have um or we can just remove this edge right we can remove this edge so we are modifying this example little bit for our testing so we will remove this edge right so from this edge three to six we will remove okay so what we have to do is we have to go here uh we have to go to the third one zero one 2 3 and 3 2 6 edge is there right so this one we will put 0 here so now there is no edge between 3 to 6 and our initial we will put as let's say our initial we will modify this initial as uh two and three right so if we remove two what happens and if we remove three what happens right so let's uh update this to two and three and rerun this example oh actually once we remove the edge from oh actually once we remove the edge from 3 to 6 we have to also remove from 6 to 3 to 6 we have to also remove from 6 to 3 right so 6 2 3 also we have to put 0 3 right so 6 2 3 also we have to put 0 here we forgot that so we will just put here we forgot that so we will just put 0 here now right 0 here now right so let's rerun so now they are saying that after we remove node two we will get four nodes so we have seen that after removing node two we will get four nodes uh let's just quickly see that so you will know so let's simulate that we are removing node two right now how many we will get three is infected so three four five six so total four are infected right so total four are infected which is correct now let's remove node three so now if we remove node three how many gets infected two only two is infected now right so two will in fact two one and zero so total three are infected right so three are infected so we will take three basically which is because it is causing minimum number of infection spread so um so i think you are clear with this we can just go ahead and take a couple of examples from them uh their examples here so let's take the third one first so third one we are expecting one as the so third one we are expecting one as the output so we are getting one which is the correct answer because one is causing only one node to be infected right and zero is causing three nodes to be infected so this is the example that actually we are looking at i think uh uh this one this is the example actually that we are looking at right so 0 and 1 are infected so if we remove node 0 then how many infections will happen if we not remove node 0 1 2 3 will happen right if we remove zero what if we if we remove node one how many infections will happen only one because zero will be infected two and three two it cannot reach because we removed one right so only one so we should remove one correct so that's what that's why we should remove one it is only causing one infection if we remove zero it will cause three infections right if we remove zero it will cause three infections because one one will affect two and two will affect three right so um let's just go ahead and do a so um as you can see we are putting 0 1 so um as you can see we are putting 0 1 1 0 1 1 which are correct answers we 1 0 1 1 which are correct answers we will remove our system out it is not will remove our system out it is not required it is just to show you required it is just to show you uh the stack trace so now we are good to go we can just so our solution got accepted by lead so our solution got accepted by lead code it is uh almost 23 percent uh code it is uh almost 23 percent uh faster than other submissions which are faster than other submissions which are done online done online and 24 percent better on the memory and 24 percent better on the memory usage usage so this is the way so this is the way we can solve this lead code heart we can solve this lead code heart problem 9 28 minimize malware spread 2 problem 9 28 minimize malware spread 2 this is also quite likeable problem and this is also quite likeable problem and this is also this is also one of the hard problems on lead code so one of the hard problems on lead code so um um as i recently solved this problem i as i recently solved this problem i found this problem quite interesting and found this problem quite interesting and i just thought that it's worthwhile to i just thought that it's worthwhile to create a video to share the logic and create a video to share the logic and the solution in java the solution in java so others can see how to solve this so others can see how to solve this problem and they can also learn from problem and they can also learn from this uh video about this problem this uh video about this problem if you are new to my channel there is a if you are new to my channel there is a dedicated playlist on my channel called dedicated playlist on my channel called as lead code and lean code solutions it as lead code and lean code solutions it has all sorts of different problems that has all sorts of different problems that includes breadth first search depth includes breadth first search depth first search matrix problems graph first search matrix problems graph problems binary search tree problems problems binary search tree problems coding questions related to strings coding questions related to strings linked list optimization problems linked list optimization problems dynamic programming problems and lots of dynamic programming problems and lots of logical questions and those are the logical questions and those are the questions previously asked by big questions previously asked by big technical companies technical companies so if you are preparing for any coding so if you are preparing for any coding rounds of interviews make sure you go rounds of interviews make sure you go through those videos that will through those videos that will definitely uh help you in your definitely uh help you in your interview preparation interview preparation to become more and more confident in to become more and more confident in your coding uh interviews try to your coding uh interviews try to practice different varieties of problems practice different varieties of problems try to use different techniques try to use different techniques so that will boost your confidence so that will boost your confidence if you like this video if you find this if you like this video if you find this video helpful and if you like the way video helpful and if you like the way the video has been created with this the video has been created with this whiteboarding session examples and java whiteboarding session examples and java code then please give it a thumbs up to code then please give it a thumbs up to this video give it a like to this video this video give it a like to this video also subscribe to this channel your also subscribe to this channel your subscription to the channel is really subscription to the channel is really important because that is the way the important because that is the way the videos can reach to more people videos can reach to more people goal of the channel is to help as many goal of the channel is to help as many people as possible in their coding people as possible in their coding interviews interviews uh many people struggle in their coding uh many people struggle in their coding uh interviews so i just wanted to help uh interviews so i just wanted to help them by showing them how different them by showing them how different problems can be solved using different problems can be solved using different techniques techniques so they can also learn from these videos so they can also learn from these videos more about problem solving um they can more about problem solving um they can also get confident also get confident in their solving uh interviews uh by in their solving uh interviews uh by looking at these different varieties of looking at these different varieties of problems that typically appear in the problems that typically appear in the coding rounds of interviews also one simple tip i wanted to share is when you are practicing for your coding rounds of interviews make sure you practice using some whiteboarding websites there are lots of whiteboarding websites nowadays you can choose one of them and you know practice your solutions a practice to explain your solution step by step and why it's important because in real interviews uh it's more about your communication skills how well you can communicate how well you can explain your solutions to a team of people to a group of people how well you can go step by step uh so you know the more you practice the more confident you will become and that will certainly help you in your interviews if this tip and if this videos are helping you then please comment about it on these videos that encourages us to create more such a good content of videos so others can benefit from it so uh do comment on these videos how the videos and how the tips are are helping you whenever i solve any important and interesting coding questions i always create videos on this channel that i often create and post so make sure you click on the bell notification icon so you won't miss any important postings here keep coding keep learning keep practicing and thanks for watching these | 2024-03-25 11:29:29 | 928 | Leetcode 928 Minimize Malware Spread II - Hard Coding Problem Solved |
|
p2UDld3rM_Q | hey what's up guys this is chung here so today uh let's take a look at this so today uh let's take a look at this number 974 number 974 subarray sums divisible by k so basically you're given like array a of integers and you need to return like the sub array right which means the contiguous uh non empty list arrays that have a right so for example we have this uh right so for example we have this uh this array a here and the k is five this array a here and the k is five so we have seven sub-arrays in totals so we have seven sub-arrays in totals which is which is divisible by by five right so divisible by by five right so this one this one this one this one this one this one this one this one yeah so remember zero is also divisible yeah so remember zero is also divisible by by k by by k because right so zero divided by k is because right so zero divided by k is also also also equals to 0 that's why 0 is also also equals to 0 that's why 0 is also like a another value right so here's the constraints right so the length of the two three three thirty thousands right so for this kind of problem you know the uh you know every time when you see like this continue contiguous like sub arrays you know it's always it's very common to use a prefix solution for it you know so let's see how can we solve this kind of problem and assuming we have a running sum right so because you know it's very like i said it's very common to have maintained revenue sum right at at the cardinal current location let's see we have the the current random sum equals to x right and then let's say we have some numbers here right be before this this current the first card number here so let's say the current running sum for so let's say the current running sum for this one is x this one is x so how can we know if for at so how can we know if for at the current at current locations let's the current at current locations let's say say if there's any uh if there's any sub if there's any uh if there's any sub rate right that can basically that a sub rate end with the end with the current so how can we calculate that i mean the so how can we calculate that i mean the brutal force was that we basically we brutal force was that we basically we look through look through all the previously all the other other all the previously all the other other presumps right all the presump presumps right all the presump in the in the previous location right in the in the previous location right and then if there's a location basically and then if there's a location basically if the we have if the we have x and let's say for this kind of x and let's say for this kind of the previously uh pre-sum is sum someone right let's say this is sum someone right let's say this is someone here so basically we need to loop through all the previously previous uh prisms right and then we we need we need to know let's see we have a sum sum two here we need we want to check if the sum one can be divided by by k right so if we if can be divided by by k right so if we if it can then we know okay we have we have it can then we know okay we have we have find find like uh like a valid sub array right like uh like a valid sub array right but as you guys can see so this is like but as you guys can see so this is like a like a like o of n square time complexity even o of n square time complexity even though we're using like this kind of though we're using like this kind of prism prism we're maintaining like this kind of we're maintaining like this kind of presump right in the in the hash table presump right in the in the hash table but still we have to look throughout all but still we have to look throughout all of the uh of the uh the previously present to get the the the previously present to get the the the subaru is that right ending with the the subaru is that right ending with the current number current number so so how can we do it how can we do it so so how can we do it how can we do it in better uh in better uh in a more performant way right so let's in a more performant way right so let's try to draw some like numbers here let's try to draw some like numbers here let's say say we have some pre-sums right let's say we we have some pre-sums right let's say we have pre-sum two have pre-sum two and then and then we have some pre-sum and then and then we have some pre-sum like like let's say we have set 17 right and then let's say we have set 17 right and then we have pre-sum we have pre-sum 20 26 and then we have pre-sum point 20 26 and then we have pre-sum point 35. so 35. so as you guys can see here right i mean as you guys can see here right i mean let's say oh and also the let's say oh and also the um assuming the k is equal to three in um assuming the k is equal to three in this case this case okay so when we're at when we are at okay so when we're at when we are at the pre-sum two here right so these are the pre-sum two here right so these are the presump the presump so of obviously two cannot be divided by so of obviously two cannot be divided by three right so that's why we just three right so that's why we just skip that and then skip that and then but when we when we add this uh pre-sum but when we when we add this uh pre-sum 17 here you know as you guys can see we 17 here you know as you guys can see we have like a difference right have like a difference right sp basically 17 minus 2 equals to 5 to sp basically 17 minus 2 equals to 5 to 15. 15. right so we have a between the 2 and the right so we have a between the 2 and the 17 we have a 17 we have a 15 here so the 15 is divisible by 15 here so the 15 is divisible by divisible by divisible by 3 right so this is one of the sub array 3 right so this is one of the sub array right that can right that can can be divided community visible can be divided community visible is divisible by by this k here is divisible by by this k here now later on we have another like now later on we have another like pre-sum like which is pre-sum like which is 20 26 right so between 20 26 right so between 17 to 26 this is what this is nine 17 to 26 this is what this is nine right so okay nine is also another right so okay nine is also another another one another one all right similarly for this one it's all right similarly for this one it's also a nine right so nine is also a nine right so nine is also another like prefix prefix sum also another like prefix prefix sum but you know when we add when we are at but you know when we add when we are at 20 26 here 20 26 here so how many how many more sub arrays we so how many how many more sub arrays we have find out here have find out here not only this two here right not only this two here right we also find uh basically we find this this night here and we also find an another one basically another sub array between 2 and 16 which is 24. so this one is all is also another sub array community is divisible by by three right similarly at nine here so by having 35 as a as a new prefix here we have basically this is going to be one plus two plus three right because by having 26 here we we have we we find two more uh subarrays and when we're at 35 here actually we're finding three more basically this is this is the the first one and then from 17 to 3 35 this is the second one right this is like the basically here's the 18 and then from 2 to 35 this is the third one this that's the third 33. right so then what's in common so what are what what are the common thing with those force prefix right so if we do a prefix prefix sum right divided uh do a modular with k here they are all end up with the same number which is two right so two uh dual modular with k which has two same thing for 17 26 and third and 35 and then it leads us to like two uh to another solution basically we can just use like a hash table or dictionary to store the uh the key basically to store the uh the the values for each prism to uh after modular by k right and then every time we have like a new new key here basically we increase that count of that of that dictionary right basically at the beginning that that count is one right we have let's say we have dictionary right and the key is two right and the value at the beginning it will be it'll be zero so when we are two here we we don't we don't add anything but after processing two here that value becomes one right and then we are when we add 17 here basically the new answer will basically do an answer to a plus of this dictionary of of key here key so when we add 17 here right so this basically we are increasing one and after that we also uh increase this dictionary of the key by by one right you do this one do a plus one so that you know we had 26 here you know this one becomes a two right so that's why we can uh add two same thing for 35 we add three yeah so basically that's the that's the idea here so let's use the dictionary to maintain the uh the frequencies the frequency basically how many times this this key has appeared and then that's going to be the uh the values we're going to use to accumulate to the final result right oh and one more thing so when we define these hash tables these are like edge cases which means that you know the zero right so let's see the k is three and what if the first number is three the so in this case right three modular so in this case right three modular by do a modular b3 we have zero by do a modular b3 we have zero right but three itself in this case it's right but three itself in this case it's also like array here also like array here right so which means that when we create right so which means that when we create this dictionaries here we need to this dictionaries here we need to initialize this initialize this this at 0 and 1 this at 0 and 1 in this dictionary so which means that in this dictionary so which means that you know at the beginning we assume that you know at the beginning we assume that you know with zero you know with zero of a zero as a key it appears once of a zero as a key it appears once so that we can handle this uh corner so that we can handle this uh corner case here uh yeah i think enough talk so actually after figuring out the pattern here the code is it's very pretty simple here so we have a running sum and then we have answer equals zero right now like i said we have dp i'm using dp here so uh i mean i initialized from zero uh with zero key is zero and the count is one so for num in a right so first we have running sum uh updated and then we have the key right so the key will be the running sum divided by k and then if key in the dictionary right which accumulate this answer by is the is the the frequency of the current key right then after that we increased by one else right if the we increased by one else right if the key key is not in this dp we simply insert is not in this dp we simply insert this one right insert the key with one this one right insert the key with one yep and then in the end we simply return yep and then in the end we simply return the answer yep i think that's it so run the code okay accept it i mean so for this one as you guys can i mean so for this one as you guys can see the time complexity see the time complexity is obviously so often right because we is obviously so often right because we only have a single for loop here only have a single for loop here and to maintain this dictionary it's and to maintain this dictionary it's just like the uh just like the uh uh um uh um o1 time right both the insert and o1 time right both the insert and updates updates one and space complexity of course is one and space complexity of course is also also often because we need to maintain uh often because we need to maintain uh basically the key for each of the well basically the key for each of the well actually no actually no actually the the sorry actually the the sorry the time the space complexity is not all the time the space complexity is not all of n is of n is o of k in this case because we do a o of k in this case because we do a modular modular right with the k here so the key is right with the k here so the key is bounded with the with how big the k bounded with the with how big the k is yeah is yeah so this is the time complexity right so this is the time complexity right this is space this is space time complexity here yeah i think that's pretty much i want to talk about for this problem and how to stop here thank you for watching this video guys stay tuned see you guys soon | 2024-03-25 14:12:32 | 974 | LeetCode 974. Subarray Sums Divisible by K |
|
USBfGahfimE | okay hi guys welcome to the channel this is vaca is vaca we are going to do another leech good we are going to do another leech good question and the question in question question and the question in question is number 10 regular expression marching is number 10 regular expression marching right right uh pretty straightforward okay it's not uh pretty straightforward okay it's not pretty straightforward the number of pretty straightforward the number of edge cases you have to look at in this edge cases you have to look at in this question question are absolutely uh it's absolutely are absolutely uh it's absolutely crazy the number of edge cases but um crazy the number of edge cases but um if you work through it it's pretty if you work through it it's pretty simple and you can solve it with um simple and you can solve it with um recursion right so what we're going to recursion right so what we're going to do is um first let's go through every do is um first let's go through every test case right test case right or let's go through the instructions or let's go through the instructions right so you're supposed to you're given right so you're supposed to you're given an input string s and the pattern p an input string s and the pattern p you're supposed to match s and p and uh you're supposed to match s and p and uh they're two they're two uh wild wildcat there's the period uh wild wildcat there's the period character which can match any single character which can match any single character and the star character character and the star character which can match zero or more of the which can match zero or more of the preceding element right preceding element right so the best thing to do is to go through so the best thing to do is to go through every example so that you can understand every example so that you can understand every single case right so in this case every single case right so in this case if we have if we have um let's come and copy this code essay um let's come and copy this code essay and pa rebels and um let's get our ripple rebels and um let's get our ripple started and uh started and uh this is for another question i was doing this is for another question i was doing and so we have sa and so we have sa and pa and when you try to match sa and and pa and when you try to match sa and pa the answer is of course not right pa the answer is of course not right because you can't make because you can't make uh you can't match the pattern from the uh you can't match the pattern from the string right in this case string right in this case so in such a situation we can just get so in such a situation we can just get rid of this right rid of this right but now we go to a situation where we but now we go to a situation where we have um we have uh a a and p a basically that let's paste them now these two strings match because remember as we said um the star element can match either zero or more of this so the star character can essentially make p be a or it can be um a a or it can be a aaa or it can be a you get the point right it can either match zero or more of the preceding character right let me just check it of the preceding element right so um the preceding character can be matched either zero or more times by this so these are all the possibilities um atc right so if you look at this situation the pattern at p and the pattern at s can match in such a situation right because of the the fact that um the star character can do this right so we can get rid of this and go to the next example this right so this is going to be dot this right so this is going to be dot star right star right so in this situation return true because so in this situation return true because remember remember the dot can stand for any character so the dot can stand for any character so the possible universe of characters if the possible universe of characters if you can you can put all the possible characters it could put all the possible characters it could be a to z right could be a to z be a to z right could be a to z and then the star matches anything in and then the star matches anything in the the previous element by either zero times previous element by either zero times or either matches it zero times or the or either matches it zero times or the exact number of exact number of um whatever is zero times or an infinite um whatever is zero times or an infinite number of times right number of times right so basically you could have a to z and so basically you could have a to z and um um a to z right so from picking a to z a to z right so from picking a to z you can you can create a b from that you can you can create a b from that string right so from a b string right so from a b uh from a to z and a to z you can create uh from a to z and a to z you can create a b so basically that one is a b so basically that one is um that one this should return true um that one this should return true right and in another situation right and in another situation this one is pretty difficult right so we paste this one right so we have a a b and c star a star b right so the first thing you need to know is that um we could um match a character zero times right so in such a situation like this we could just ignore matching the [Music] we could ignore matching the the the c right imagine there's an um there's a i pointer here right there's an i pointer here and there's a j pointer here right so uh we check and we see i and j are not alike so we could move the j to the next one and we could match the preceding element exactly zero times right so in such a situation let's make a possible universe of all our characters that can be matched from um b to a so we could in this situation ignore c we don't have to um copy c right so we could just have an empty string like so right and then um when we come to a a and we move i up to i could remain there right a and a match so we have an a and then we move i to the next a and we move j to the next element which is going to be this right we'll move from a and if we look at j j is going to be jesus the star character matches the previous element x number of times right or zero number of times as you can see from what it did to c right so another situation where you can return uh the previous element which is a and the a and then finally we have b if we move our i element up one i and we move j up one j we have a a b right so we have matched we have potentially created a match for um the first element which is a a b you can match it using this element right by moving to pointers so we go to uh description and um i've gone through the examples and the first thing we need to do is we could create um a function that will do this right we're just going to pass in the the i and the j of the the i pointer the i pointer correlates or will work on the s point on the s string which is the input string and the p and the j pointer will correlate to the p string right so and remember what we're doing here if i could just go over it again we are ensuring that um we can match the input string in the pattern right so the person might still have some things as long as we match the input string that's all that is required in the button right so we could come here and we could call it maybe um i think we could call it is it a depth first search or a breadth first search okay let's just call it bfs like so right and it's going to take in the i and the j and i i corresponds to s j corresponds to p i think we've gone over that and now um the first thing we need to check we need to check that the i pointer and the j pointer are both valid right so for that we just say if i is greater than um the length of s and j is greater than the length is greater than or equal right it's not just greater it could be out of bounds greater or equal to we could say the length um and the length of the pattern the length of the pattern will return true right if both of them have crossed over because you're going to progressively move them over each letter right we're going to loop through our strings our pattern string and our input string right so if both of them have crossed uh greater than or equal to the length of s that means that we have gone through every character and we have similarly it has passed all the tests and it has also gone through every pattern character so in this situation what you're supposed to return is obviously true right now the next situation we um we check whether or not we have hit the out of bounds of the pattern string right if we run out of characters or elements in the pattern string and the i has not been exhausted that means that we can't match everything in i in p right it follows right so the next thing we just do is if j is greater than or equal to the length of the pattern string that means um we have gone through uh that means we have gone through s and we have not found everything we're looking for that that can only mean one thing right we just have to return here false like so right so after that we check if the first characters match so we start at the very beginning right so we could put this in a variable because we're going to use check the match we're going to use this a couple of times right and to check the match is pretty straightforward right we first check that i is within bounds and um we say i is less than the length of s we check that the element at i is we check that the element at i is exactly exactly the same as the element of j right in the same as the element of j right in this case this case we have um let's say a a right we have um let's say a a right so let's just come here and say this is so let's just come here and say this is going to be a a going to be a a and p is maybe a a right so in this and p is maybe a a right so in this situation check i situation check i is equal to p right so we say is exactly is equal to p right so we say is exactly the same as p the same as p j or r or remember if it's a dot it matches any single character right because the dot is from any character from a to z right i'm guessing we're only using uh is it alpha numerical okay a matches anything right let's just agree a matches anything right so um if the element at j is exactly equal to the dot character the period character that that can match any letter so if this matches we have a match if we have either the characters at s at position i and the character at p at position j or the character at p position j is a dot right in such a situation we have a match and we can continue from there um we check the next character we move um we check the next character we move we go to the next character we go to the next character and um there are a few things we have to and um there are a few things we have to check there right check there right so we we know that as you know so we we know that as you know uh if a star is the first character then uh if a star is the first character then um it should be ineffectual right um it should be ineffectual right so um astar can't be the first character so um astar can't be the first character because the star only works on because the star only works on uh the preceding element right so if i uh the preceding element right so if i start the first character start the first character it's possibly useless so we don't have it's possibly useless so we don't have to consider start that's why to consider start that's why i've only considered the dot here and i've only considered the dot here and not the star but now not the star but now for so this will only work this will for so this will only work this will work quite possibly on the first element work quite possibly on the first element this is what is going to randomly get to this is what is going to randomly get to our first element right our first element right and this this two up here at our base and this this two up here at our base cases right when we have cases right when we have exhausted everything and we've gone over exhausted everything and we've gone over it these are basically is the if it these are basically is the if the length checking the lens right so the length checking the lens right so the next thing the next thing in the next line we have to consider the in the next line we have to consider the fact that we use a stop because the star fact that we use a stop because the star will match either zero will match either zero of the preceding element or possibly of the preceding element or possibly an infinite number right so we have to an infinite number right so we have to consider this when we're doing consider this when we're doing in the second when you're considering in the second when you're considering the second element right so the second element right so how we do that is we say if how we do that is we say if j plus one if j plus one is less than j plus one if j plus one is less than uh the length of p if we are still uh the length of p if we are still within bounds in our pattern within bounds in our pattern right and um and p and right and um and p and let's just spell and correctly am i let's just spell and correctly am i spelling this incorrectly spelling this incorrectly and the p um and the p um and the character here is our and the character here is our is it a star whatever it's called um is it a star whatever it's called um and the character here is a star if j and the character here is a star if j plus one plus one if j is within bounds and the character if j is within bounds and the character at j at j at j plus one is uh the p dot star at j plus one is uh the p dot star uh we actually have two choices right we uh we actually have two choices right we can either ignore it can either ignore it right in such a situation like when we right in such a situation like when we came here and um came here and um we basically ignored c right we copied we basically ignored c right we copied it zero times right it zero times right so in this case you can either copy it so in this case you can either copy it and you remember i say there's zero or and you remember i say there's zero or more proceeding right so we're going to more proceeding right so we're going to consider both consider both instances where we copied zero times or instances where we copied zero times or we copy it we copy it an infinite number of times as many as an infinite number of times as many as required right what we do in such a situation is we um what we do in such a situation is we um where they have where they have d fs we call dfs on i d fs we call dfs on i and we move j by one in such a situation and we move j by one in such a situation if we move j if we move j plus one by one it becomes j plus two plus one by one it becomes j plus two right in this situation what we're doing right in this situation what we're doing is we're ignoring it right we leave i is we're ignoring it right we leave i where it is where it is but we move j because we're ignoring it but we move j because we're ignoring it right so we ignore j right so we ignore j plus one right in the case and this plus one right in the case and this worked for when we were doing the worked for when we were doing the the c this right so we can ignore it if the c this right so we can ignore it if we want right so we ignore it in the we want right so we ignore it in the pattern string right or and if we match we call the we call the depth first such on i plus 1 because you've moved i on i plus 1 because you've moved i and j right and j right so basically that this line does like so basically that this line does like i've explained is that it checks i've explained is that it checks um if we're using it uh if we're using um if we're using it uh if we're using the star the star um you it has to match and in such a um you it has to match and in such a situation if it matches situation if it matches we move our eye to the next level and of we move our eye to the next level and of course we can leave our j where it is course we can leave our j where it is and um if we don't use it we just move and um if we don't use it we just move our j to the next our j to the next character right so basically that's character right so basically that's understood and the next thing we need to understood and the next thing we need to do do is um we just need to call we need to is um we just need to call we need to check match right check match right so um if we do have a match if we so um if we do have a match if we if match right we just need to if match right we just need to recursively return the and we call this dfs instead of bfs right we should call it i think this is a breadth first such rather than the depth first starts right so what we do here is we return b we want to return um if we have a match we want to return um if we have a match we move to the next letters and we we move to the next letters and we repeat the whole uh process right so repeat the whole uh process right so it's i plus one it's i plus one j plus one so we move it up one level j plus one so we move it up one level and if we move it up one level what and if we move it up one level what we're supposed to do is we're supposed we're supposed to do is we're supposed to come here and we say to come here and we say return false like so and return false like so and afterwards what you're supposed to do is afterwards what you're supposed to do is um we are supposed to return um we are supposed to return uh dfs and um bfs rather uh dfs and um bfs rather bfs and what we call it on we call it on bfs and what we call it on we call it on uh uh s and p and we call it at position zero s and p and we call it at position zero in each right so we call in each right so we call zero and zero like so right so zero and zero like so right so basically that so this is our basically that so this is our we could call this our naive solution we we could call this our naive solution we need to make sure that need to make sure that we check that j is equal to the length we check that j is equal to the length of p right and of p right and um that we return after um that we return after we check our wildcard we need to return we check our wildcard we need to return whether this is evaluated to true whether this is evaluated to true and finally we need to make sure that and finally we need to make sure that this if blocks match right this and if this if blocks match right this and if and if much so and if much so just correct your code like that and just correct your code like that and when you run your code when you run your code it's hopefully going to be accepted and it's hopefully going to be accepted and if we submit it if we submit it it's also hopefully going to be accepted it's also hopefully going to be accepted so basically that is our code so basically that is our code um our time complexity is going to be o um our time complexity is going to be o of of n our space complexity is going to be um n our space complexity is going to be um we don't create any structures right so we don't create any structures right so we're just going to have an o we're just going to have an o one space complexity right if i'm not one space complexity right if i'm not wrong we do not create any structures wrong we do not create any structures yeah yeah so this is going to have a time so this is going to have a time complexity of o of n and a space complexity of o of n and a space complexity of o complexity of o one right um you could also use caching one right um you could also use caching but i'm not going to go into that but i'm not going to go into that but you could you you could use caching but you could you you could use caching to make um to make um our our code move a bit faster but the our our code move a bit faster but the space complexity calculating it is going space complexity calculating it is going to be exactly the same right it's not to be exactly the same right it's not going it's going to be going it's going to be maybe a significant increase in our maybe a significant increase in our speed but it's not going to change it speed but it's not going to change it into it's not going to make it better into it's not going to make it better than oven than oven the time complexity thank you for the time complexity thank you for watching subscribe to the channel and watching subscribe to the channel and i'll see you in the next video | 2024-03-19 12:17:33 | 10 | Leetcode 10 Reguar Expression Matching in Python |
|
viEZPE6i2B8 | cool cool largest sub matrix with three arrangements you're given a binary matrix of size n times n and you're allowed to rearrange columns of matrix in any order turn the area of the largest sub matrix with the matrix every element of the sub matrix is one after reordering the columns optimally up to ten to the power five elements okay so i had to look at the hint first hint for each column find the number of consecutive ones ending at each position so we go through each column and account number of consecutive ones when we reach a zero we restart the count from zero but then how does that help us find the answer okay so here we go the white board let's say um you have a bunch of columns and these are all consecutive ones down these columns and we've counted how many ones uh ending at the last position here we do this for each row of the matrix given this row for this row what's the maximum area well if we sort all of these numbers so let's say this is five three four two five two let's say we are sorting it in decreasing order so that means we get five five four three two two and to find the maximum area i could possibly get from this is something like uh let's say for example the indexes are zero one two three four five so that's the index these are the number of consecutive ones the answer would be well i would go through each of these then i'll do the min so far the mint so far is actually the item at the current position because it's decreasing so it's actually going to be whatever this value is let's call this a value array it's going to be a value of i times i plus one that's the area i'm gonna take the max out of all these or all i in the range is zero to five so in this case what's the max area well let's calculate one by one so we have um five times one that's going to be five or we could have five times two which is ten or we can have um four times three which is twelve we have three times four which is also twelve or we have 2 times 5 which is 10 or you can have 76 which is 12. and we take the max out of all these it's going to be 12. that's the answer for one row and we do this for all possible rows and then we'll have our answer let's give that a go so i want a bunch of vectors a vector of vectors let's call it ones number of rows would be matrix.size they want to go through each column one at a time and then go through each row at a time so matrix i j will give us the current value in the column we're looping through and keep track of let's call it dp0 uh if current value is equal to zero and on db equal to zero i also want plus plus db we just restart the count and then set ones at the current row and they'll push back the current dp value cool and then we can go through each of the rows and just sort the row i kind of want to sort it in reverse order so once i've done that i could go through each of the rows put an answer here and then and then we can go through j is equal to 0 j less than matrix at let's do actually one's not size and then we can do ones at i dot size plus plus j keep track of a is equal to the maximum of the row is equal to the maximum of the row answer and whatever answer and whatever ones at i ones at i j is times the current index plus one j is times the current index plus one and then at the end i wanna do answers and then at the end i wanna do answers equal to max of the answer and the row equal to max of the answer and the row answer answer and at the end just return the answer okay that's four let's try a different that's that's working working cool cool cool cool let's submit that and see if that works let's submit that and see if that works awesome awesome that does work that does work sweet um thanks for watching like and sweet um thanks for watching like and subscribe and i'll see you in the next subscribe and i'll see you in the next one one don't forget to keep eating the code | 2024-03-20 17:34:30 | 1,727 | 1727. (Medium) Largest Submatrix With Rearrangements - Daily Leetcode (Day 78) |
|
Xi6DdOFUpAg | Hello friends welcome to coding First Youtube channel in this video I will explain you Elite code problem set Matrix zeros so in this question we will have a m into an integer Matrix and if an element is 0 then we have to set its entire row and column to zeros so you can see here in this example one this is our Matrix in which we have zero in the middle so this is our second column and this is our second row so in the second row and the second column we have to make all the elements as zero so this is our output Matrix same you can see here in this example 2 we have this Matrix so you can see here this is 0 is present in Faster row and First Column so this whole first row and First Column will become zero and this second zero is also present in first row but it is present in the last column so ball first row and last column will become zero so for this question I will explain you two approaches first is Brute Force approach and second is optimized approach but in this video I will only going to explain you the Brute Force approach but there is one limitation of that Brute Force approach you can see here the range of elements in this Matrix so it is starting from negative to positive so that Brute Force approach is only applicable for positive elements so that's why we cannot use that Brute Force approach to write the program for this question in the lead code but only for interview that if in the interview they will tell you that the Matrix will only have positive elements then you can apply that approach that's why I will explain you the Brute Force approach in this video so you can see here I have taken here some sample test cases so this is our test case one first we will see the approach and then we will write the program so what I will do is we already know how we can Traverse in in a matrix so we know that we have to take two for Loops so first for Loop is for the rows and then inside this for Loop we have a another for Loop for the columns so using this for Loop we can easily Traverse in The Matrix to every element then what we are going to do so you can see this test case one we are traversing in The Matrix so this is 0 is present at index 1 comma one so what I will do is add this index we will call a function that Mark this row and column with zero so suppose if you find a zero and then you just mark this row and column with zero what will happen so when we are on the index one by one so we are calling a function to make this row and column as 0 so then this row and column will become 0 but you can see here we are not going to stop this for Loop because we don't know if we have more 0 in the Matrix or not so next time when this Loop will run again so we will reach at indexes 1 comma 2 so you can see here when we reach 1 comma 2 at this index so here it will again find element zero so then it will again call that method to make this row and column as 0 so you can see that because of that this column will also become zero so this is wrong so what we are going to do is initially we are not marking the row and column as 0 we will mark them as negative so we will mark them as minus one so you can see that suppose this was our Matrix and when we are finding 0 here so we are marking this wall row and column as a minus one so you can see here we also have to use a if statement when we are marking the row and column as 0 because at the index where we are finding the original zero we have to keep it as 0 we do not have to mark it as minus one when we reach on the last index and this nested for Loop will break then after that we will use a next message for Loops to check that if we find any minus one element we will make it as 0 so next time we will use next sheet for Loops again to make this negative ones to zero so this is our Brute Force approach so this is all our sample test case I will write the program in the IntelliJ IDEA and I will run all these test cases to check that if the Brute Force approach is working or not so now let's write the program so you can see that in the program this is our Matrix then we have to use nested for Loops so for end I equal to 0 and I less than a DOT length and I plus plus and inside this we have to use a next for Loop 4 into J equal to 0 and J less than a of 0 dot length and J plus plus so now we have to use a if statement here if array of I and J equal to 0 so when we are finding any element as zero so then we have to call a function so I will make a function here set Matrix minus so we know that initially we do not have to mark row and column is 0 we have to mark them negative so I will name this function as set a matrix minus and inside this function we will pass array and this I and J because this I and J will tell us that which row and which column we have to mark after that here I will make a function public static void so we do not have to return anything we only have to mark this original array with negative elements so that's why we will use here void return type method name is set Matrix minus so now in this method I will make this parameters array a and end column and int row so here you can see that one thing that is this I4 Loop is for rows and this j4 Loop is for column but you can see here when I am passing these values here I am storing this I in the column variable and I am storing this variable J in the row variable y so I will tell you later why we are doing this so now in this method we have to take two for Loops first for making the row as minus 1 and second four making in the column s minus 1 so 4 and I equal to 0 and I less than a DOT length and I plus plus so here I will use the if statement if a of I and rho not equal to 0 so we know that we do not have to make this original 0 as negative 1 so using this first folder we are marking that column as minus one so array of I and rho equal to minus 1 and after that we have to make a next for Loop to change the row to minus 1 4 into I equal to 0 and I less than array of 0 dot length and I plus plus so here you can see that in the starting we are taking a DOT length but here we have to take a is zero dot length for column we have to take a of 0 dot length you can see that we have to make some changes here in the if statement if so you can see that what we have to write here First Column or I suppose if we have to move in this world Row from this here to here so X actually what is changing here the value of this row will remain same only the value of column is changing here so actually this column variable which is changing this is our variable I and this row variable it is our column variable so that's how we have to write so if a of column and I not equal to 0 so then we have to make it as 0 so a of column and I equal to 0 so we have to make that column and I equal to minus 1 so you can see that what we are doing right now we have written this nested for Loop two Traverse in The Matrix so traversing Matrix then what we are doing is we are calling this set Matrix minus function to make that element row and column as negative one where we are finding zero so this is our method so this first for Loop is for making column as minus 1 and the second for Loop is for making the row as minus 1 you can see that we also have have to make that negative 1 back to zero but before that we will see that if this method is working fine or not if it is making row and column as minus 1 or not so I will print the elements of so you can see that this method is so you can see that this method is working fine we had 0 in the center so working fine we had 0 in the center so this wall column is minus 1 here and this wall column is minus 1 here and here and this row is also has become -1 here and this row is also has become -1 so now only the one step remain is that so now only the one step remain is that we have to make this negative one back we have to make this negative one back to zero so before printing this array I to zero so before printing this array I will use this nested for Loops here and will use this nested for Loops here and inside this so here I will write if inside this so here I will write if statement if array of I and J equal to statement if array of I and J equal to minus 1 then array of I and J equal to 0 minus 1 then array of I and J equal to 0 and we are using this next for Loop to and we are using this next for Loop to print our Matrix so now let's say run print our Matrix so now let's say run this program so you can see that this program is working fine we are getting this second row and second column as 0 and 0. so I will show you a quick Dryden of this program so let's see how this program is working so you can see that in the question we have a matrix of 3 by 3 and in the second row and the second column at this index we have zero so we have to make this volt 11 row as zero so then what we are doing is we are traversing in The Matrix using the nested for Loops so this first folder will start from index I so I is zero inside it we have this next for Loop J so J will also start from index 0. so you can see that at index 0 and 0 it will check that if we have 0 you can see no at this index 0 and 0 we have one so then nothing will happen J Will increment so it will become one then it will check at index 0 and 1 do we have zero you can see at index 0 and 1 we have one so this if statement is false then J Will increment so it will become true you can see at this index 0 and 2 we have one again this if statement is false then you can see J will not increment because in the Matrix we only have three columns then this row will increment so I will become one so now again J will start from zero now it will check at index 1 and 0. now it will check if at index 1 and 0 do we have zero you can see at index 1 and 0 we have one again this if statement is false J will become one now you can see here at index one and one we have zero yes now this if statement will execute and it will call this set Matrix minus function so here we are passing this three parameters first is array then these two values I and J so in the column variable we will store I and I is 1 and in the row variable we will store J and J is also one so now what will happen you can see we have this first for Loop and in this first for Loop we have two values I end row so this I is starting from 0 so this is our I I is starting from 0 but this row variable will remain as it is and row is one so index 0 and 1 so it will check that if at this index 2 we have 0 you can see no so this condition is right here we have one we will make it as minus 1 then I will increment so it will become 1 then it will check at this index one and one at this index we have zero so this if statement is not going to execute here then I will increment so it will become 2 you can see at index 2 and 1 we have one it will make this index element as minus one so here it will become minus 1 then index will become 3 so then this folder will break here so this follow will stop here then this next follow will start so this first for Loop has made our second column as minus one now this next four Loop will make this second row s minus one this folder will start from zero so this is is our I which is starting from 0 and we have this column variable so here we have column variable which is one so it will check this first index 1 and 0 so at index 1 and 0 is the element not equal to 0 you can see yes here element is one so we will make it as minus one so it will become -1 then I will increment so it will become one you can see at index 1 and 1 we have zero so this if statement is false and it will not execute then I will increment so it will become 2 at index 1 and 2 we have one so this if statement is right and it will execute so we will make this element as minus one so after that I will increment you can see that in the Matrix we only have three column so then this folder will also break from here so then we will go back in in this nested for Loops so in the last we were at this index one and one index will increment so J Will increment it will become two now it will check if at index 1 and 2 do we have zero so you can see that now this is our array we have modified our array by making the elements as -1 so now you can see here at index 1 and 2 element is 0 no here we have minus one so here nothing will happen but you can see here if initially we have made this volume row and column as 0 so next time this function will again make this column as 0 which will make our output force so this time nothing going to happen then J Will increment so it will become 3 and we know that then this J folder will break then I will increment so it will become 2 now from here J will again start from 0 at index 2 and 0 we have one so this if statement is false then J will become 1 at index two and one we have minus one again this if statement is false nothing going to happen then J will become 2 so at index 2 and 2 we have one again this if statement is false so in the last this both in a state four Loops will break so so you can see that this next next sheet for Loops will start it will start from index is zero so we are using this next Nesh it follows to making this minus one element as zero so you can see that I will start from 0 and J will also start from 0 so at index is 0 or 0 do we have minus one no nothing going to happen then J Will increment then it will check if at index 0 and 1 do we have minus one you can see yes so it will make this element as zero then J Will increment so it will become two so at index 0 and 2 do we have minus one no nothing going to happen then I will increment so it will become one again J will start from zero so at index one and zero do we have minus one you can see yes so we will make this element as zero then J Will increment so it will become one you can see at index one and one we have zero nothing going to happen then J Will increment so it will become two so at index 1 and 2 at 1 and 2 we have minus one yes so this if statement is right and then it will make this element as zero so after that I will increment so it will become 2 and J will start from 0 at index 2 and 0 we have one nothing going to happen then J Will increment so it will become one so at index two and one we have minus one yes so then it will make this element as zero then after that J will become 2 so at index 2 and 2 we have one and nothing going to happen and in the last this folds will also break and then we will print our Matrix so this is our final output this second row and second column has become zero so if you want to know the time and space complexity of this program so what is that we are using nested for Loops so because of that time complexity of this program will be bigger of n Square so you can see that we are only using these four Loops but we are not making the exact same array to make the changes so because of that phase complexity of this program will be big of one so in the next video I will explain you the optimize approach for this question [Music] | 2024-03-20 11:34:02 | 73 | Set Matrix Zeroes | Leetcode 73 | Set Matrix Zeroes java |
|
iPwjEFR-FSY | hey what's up guys babybear4812 coming at you one more time at you one more time uh trying to get one more video in uh trying to get one more video in before the sun goes down so it's a bit before the sun goes down so it's a bit dark dark uh today we got 10 29 two city uh today we got 10 29 two city scheduling and i think this will be scheduling and i think this will be relatively quick i'm going to keep relatively quick i'm going to keep peaking over there at the uh so i see peaking over there at the uh so i see the cn tower from here and i think the the cn tower from here and i think the light show hasn't started yet so we're light show hasn't started yet so we're good so that's going to be like my good so that's going to be like my my proxy for if this video is going too my proxy for if this video is going too long but this will be a quick one long but this will be a quick one uh bloomberg likes this one a lot as of uh bloomberg likes this one a lot as of recent and and the problem states is recent and and the problem states is states the following a company is states the following a company is planning to interview planning to interview two n people given the array costs where two n people given the array costs where cost the bias equal to cost the bias equal to a cost and b cost the cost of flying the a cost and b cost the cost of flying the i person i person to city a is a cost and the cost to city a is a cost and the cost applying to city b applying to city b is b cost we need to return the minimum is b cost we need to return the minimum cost to fly every person to the city cost to fly every person to the city such that exactly n people arrive in such that exactly n people arrive in each city each city so what we're told for sure is that so what we're told for sure is that before we dive into an example we're before we dive into an example we're told that there are told that there are an even amount of people and there's an even amount of people and there's there's at least two entries so we don't there's at least two entries so we don't need to do any error checking need to do any error checking and uh we have some positive uh cost and uh we have some positive uh cost between between one and one thousand so if we had one and one thousand so if we had we have this array 10 20. so person we have this array 10 20. so person person one or person zero let's call person one or person zero let's call them it would cost us ten dollars to fly them it would cost us ten dollars to fly them to or them to or choose your favorite denomination cans choose your favorite denomination cans of beans get ten cans of beans to fly of beans get ten cans of beans to fly person zero to city a and twenty cans of person zero to city a and twenty cans of beans to fly into the beans to fly into the city b or you know 30 and 200 for person city b or you know 30 and 200 for person one one 450 per person too uh 30 and 20 per 450 per person too uh 30 and 20 per person person three the output is 110 and the weight three the output is 110 and the weight we'll figure out how to get to the 110 we'll figure out how to get to the 110 but that's composed of but that's composed of uh sending this person right over here uh sending this person right over here uh to city a uh to city a and and the second so people zero and and and the second so people zero and one will go to one will go to city a and then did i get that right yep city a and then did i get that right yep and then and then uh people three and four will go to city uh people three and four will go to city b so b so city a city a city b city b so that city a city a city b city b so that cost will be 10 plus 30 is 40 plus cost will be 10 plus 30 is 40 plus 50 zero in a city b that's 90 plus 50 zero in a city b that's 90 plus another 20 is 110. another 20 is 110. we get a couple more examples but i we get a couple more examples but i think it's pretty self-explanatory i'm think it's pretty self-explanatory i'm going to dive into this example a bit going to dive into this example a bit further further just to see how we'd how we'd work it just to see how we'd how we'd work it through so through so a couple ways that you could start a couple ways that you could start thinking about this and this problem thinking about this and this problem usually trips people up usually trips people up a bit at least right off the bat because a bit at least right off the bat because one at least where my head went the one at least where my head went the first time that i tried to solve this first time that i tried to solve this was in taking a bit of a greedy approach was in taking a bit of a greedy approach and saying let me and saying let me find the cheapest route find the cheapest route per person so or rather by city and per person so or rather by city and maybe this example would be maybe this example would be um a bit better if i did something like um a bit better if i did something like this i'm going to change this to 40 just this i'm going to change this to 40 just so the numbers work out a bit nicer so the numbers work out a bit nicer let's pretend that i i told myself okay let's pretend that i i told myself okay let me figure out if i need to send let me figure out if i need to send half and a half so how many people city half and a half so how many people city have my people to city b have my people to city b let me figure out who i want to send to let me figure out who i want to send to city a city a and you know by looking at this list i and you know by looking at this list i can say hypothetically let's sort it can say hypothetically let's sort it um if we were to sort it in increasing um if we were to sort it in increasing order of cost order of cost the reason i maybe want to do that is to the reason i maybe want to do that is to say well the cheapest cost to get people say well the cheapest cost to get people to city a whatever combination so the to city a whatever combination so the cheapest way to get people to city a cheapest way to get people to city a will be in increasing order this way so will be in increasing order this way so it'd be like 10 30 40 400 it'd be like 10 30 40 400 imagine these two were swapped so these imagine these two were swapped so these two were swapped if we were to have two were swapped if we were to have sorted this and if that's the case we sorted this and if that's the case we would send this person city a would send this person city a this person to city a and that cost will this person to city a and that cost will be 10 be 10 and this will be 30. that's cool um and this will be 30. that's cool um then we would want to send i think that then we would want to send i think that i i i i may have messed up this example here um let me do this i'm going to change it up a bit more yeah sorry um let me see if i can i tried to erase this before let me do this i'm going to make this 150 i'm going to make this one 400 so the the example can be a bit more illustrative if i was to tell myself what's the cheapest way to get people to city a this would still be it if we were to sort this list by by city a and by it from lowest to highest cost we would grab these two then we're left with these two guys and gals and and they would be sent to city b so these would be their their relevant costs the issue is that this person would now cost 400 this person would cost 20 and overall the cost here would have been what is that 40 60 400 and 60 yikes 460. so this is what would have happened if we sorted people by the cost of city a and we said let's just let's get them out the city a as cheap as possible um and and in this case you know there was a better answer here because maybe we could even do something like well let's send now let me think here maybe let's send uh this person sorry let's send let's send these two people to city if we send these two people to city a we'd have a cost of of 80 and then these two people would go to cdb and that would get us to 120. so all the you know all of a sudden we can tell by account for example that there's a way to do this that's better than just saying let me sort people by city a so i'm gonna unwind that now let's say i'm gonna i'm gonna undo this example here and i'll leave it back for the 450 how we how we had it before and let's say we we said okay well what if we tried the same tactic but for city b and i i somehow grabbed people to go to city b and i basically sorted by this half here and i said well by that methodology i'd have these two people to go to city b would only cost me 40 and that leaves these two to go to city a the problem is again now i've got this one's really expensive here for 400 so all of a sudden we're not doing what we optimally optimally could have because this would cost us uh 470 whereas potentially what we could have done was we could have said let's take these guys for 40 and these guys were 70 and that only would have cost 110 so way less how then do we actually determine how to pick and choose who's one where well let's think about it this well light show is starting all right we'll get there quick um let's think about the following why is it that i think let's think about this last example we just had why did we oops why were we unhappy with with our selection here so i think we we sorted them and we said these two would go here and then and then these would go here what we failed to take into account is the following so we said sure city b is really cheap and we found it the cheapest possible city b combination um when we did the first example we found the cheapest possible city a combination what we didn't take into account is how these two cities um what the total cost is with respect to each other and that's the key to this this question to really getting down to the bottom of it let's say that i wanted to drill in a bit deeper and i wanted to say how can i think about the cost to get to one city while taking into account let me get the light on um while taking into account uh the cost of the other city so namely how do i actually keep one city with respect to the other in mind when i'm going through this and it's the following way we can think about it in in the following way it's a pretty simple trick but it's a neat one what if i ask myself what is the the value of the differential from one to another for instance if i was to go to city a instead of city b for for this person over here what benefit would i derive so if i was to fly this person to city a over city b i would save maybe oh i'd save 10 i'd say the cost of 10. so that's good it's cheaper for me to send this person to city a than the city b i don't know what it costs everybody else yet but just this person alone that's what they that's what they're going to cost me the next person over here well if i send them to city a instead of city b i would save 170 dollars cans of beans euros whatever whatever your favorite denomination is goats um person c versus the third person if i was to send them to city b that's that's awful it's like that would set me back i would lose 350 bucks incremental um if i had sent the city instead of city okay so that's good to keep in mind and then with this one over here it would cost me an extra extra 20 bucks to send them to city a what now if we reframe the question is that it's it instead we said what is it instead of saying what does it cost me to go to city a versus what is the cost of city b and i ask myself what does it cost me to send somebody to city a with respect to how much it would have costed me to send this to city b okay and that's how we're going to reframe the question to actually make this work in this case we we really if we think about this now if i just was to send everybody to city a where i would get the the biggest delta like i would be happiest to send the city a because that's my best option when comparing the two cities then in fact i'm gonna get my optimal solution so imagine sorting this image imagine sorting this array now except we sorted it by the delta in terms of like the benefit that we get from from going to city a versus city b of course you could do the same logic the other way around you can figure out what the benefit is to send city b instead of city a and sort it that way the two methodologies are completely synonymous i also sort this now well i noticed that at the top of my list are these two guys and and these two tell me that i have the biggest benefit of going to city a with respect to city b i would save the most i would have the most positive benefit by setting the city a versus city b even if i was at a loss so let's say even let's imagine this was negative let's say it was more expensive for me to send everybody to city b instead of city a and so city a would cost me more i still need to split them 50 50. since these two would result in the lowest loss i would still go with with these two maybe you know this would have to be a 30 this would have to be 217 for these numbers to work out um like with this example i just made them negative but regardless that would actually get us to our optimal solution what we then need to do is just say well let me sort this array based on how good my benefit is of sending the city a let's say and you know whatever that benefit is for for cda i'm going to send the first half of the people there and the second half people are going to go to the other city again you can flip the order around if you know that tickles your fancy i'm uh i'm not going to push you either way but i i hope that explanation made sense the code is going to be really short and the logic itself i think is is quite manageable what we're going to do is we're going to do this we're going to sort this using a in python it's a lambda function uh in some other languages like javascript it would be an anonymous function you can use whatever whatever your language offers but the way we're going to sort this is we're going to sort it by taking five some element um i'll call it i i'm gonna take the the benefit we're gonna get is is gonna be i naught so this first entry minus i one okay so really i i kind of i made these values positive here but really they should be the other way around where it costs me ten dollars less to go to city over city 170 less to go to city average city b for the second person it's an extra 350 to go to city a an extra 20 to go to city a for these two people that way when we sort it so if i kind of sort with um with this in mind i'm going to sort uh in an ascending order and and the first half is going to be all the lowest numbers the most negative ones or the least positive ones which are going to be the ones uh where i derive the most net positive welfare or benefit with respect to the rest of the list when when sorting it in this way so i hope that explanation uh made sense i think it's not too difficult to prop the grasp again the code is going to be super short so uh yeah let's dive in if you have any questions drop them down below as always we don't need to do any error checking like i mentioned because we've we're given a legitimate length here what we will need to do though of course is is like i said sort first and foremost so we're going to sort this and we're going to use the lambda function so we're going to say p equals a lambda and for any arbitrary item x so this item x is one of these they're not tuples but one of these uh arrays array items within the bigger array and we said we want to sort them in ascending order by finding the benefit from city a from going to city a with respect to city b meaning that i'm just going to take i'm going to sort it by taking x naught minus x1 these numbers are going to go in in increasing order and so the first half that we find is going to be like the city a the second is going to be going to city b all i really need to do is to say um i'll find some total cost variable not find it i'll declare it set it equal to zero and i'll say that for the first um [Music] i'll say for for cost and costs uh we want to say or let me do this brian range in the length of of cost so that's the entire length of the array and we're going to divide it by two non-inclusive so imagine this imagine that costs like right here is a is a length of four okay it's gonna give us the length of four divided by two will get us two since this is uh the upper bound of this range non-inclusive we'll we're gonna go up to index one meaning index zero and index one and that'll be the first two elements out of four and so when we do that we're gonna say that we wanna increase our total cost by costs at i and we want to go to city a for this first half that's how we sorted it so we're going to take the the first cost right over here we're going to take the 10 and we're going to take i guess it'll be one of these 30s after it'll be this one here i'm then going to loop through the second half the array so for i and range from the length of costs divided by two so from index to all the way to the end uh so that will take us to the length of costs i'm going to say total cost plus equals cost of i one so you know the folks going to city b we're going to take we're going to take the cost it takes to get them to city b this is one walk through one calculation we return total cost total cost we run that i'm going to submit it and make sure that i haven't made it funny and there we go 85th percentile it's as quick as it's gonna get um i believe unless there's like a another hidden trick that i don't know about let me know down below if there is but but yeah this will get you guys definitely across the line uh it's a cheeky solution but i think it's a good one for the two city scheduling problem that again bloomberg's been asking i think it's a decent problem uh if you liked it if you found it useful smash like button comment share subscribe uh share with everyone and i will see you guys in the next | 2024-03-25 15:19:15 | 1,029 | TWO CITY SCHEDULING (Leetcode) - Code & Whiteboard |
|
cMIS8CCIUU8 | lead code problem number 115 distinct 115 distinct subsequences so this problem gives us subsequences so this problem gives us two string string s and string T and the two string string s and string T and the goal is to return the number of distinct goal is to return the number of distinct subsequences of s which equals to T subsequences of s which equals to T here's some information about the test here's some information about the test cases and here's an example right so we cases and here's an example right so we have rabbit here with three Bs and for have rabbit here with three Bs and for string T it'll be a rabbit with two BS string T it'll be a rabbit with two BS so the output is three because we can so the output is three because we can create three rabbits by excluding any create three rabbits by excluding any one of the BS right so here I have an one of the BS right so here I have an example and the approach I'm going to example and the approach I'm going to use is by using dynamic programming to use is by using dynamic programming to cach the previous result as we iterate cach the previous result as we iterate through the string so DP will equals to through the string so DP will equals to m+ one m in this case would be the size m+ one m in this case would be the size of T which is four so we have four + 1 of T which is four so we have four + 1 five zeros and here the first zero will be one right now I iterate through the two strings I have J which starts at one and increments as long as is smaller than the size of s which in this case is five next I have I which starts at the back of P so we have four as long as it's more than one you will keep on decrementing now let me do a pointer so it's easier now let me do a pointer so it's easier to follow so now here I have a e statement which basically checks J minus one right so this character is this character the same as I minus one right so I is four 0 1 2 3 4 minus one is T so if they are the same we increment by the previous result but since R and T are not the same so what happens is I will decrement inant so I decrements we're looking at B now still not the same decrement not the same decrement now when both I and J are one the characters matches right R and R so what happens here is DPI which is over here right 01 will plus equals to IUS one which is the previous result which is one then J Will increment I will reset back to four and we repeat the same thing again right so now for b b does not equal to T so I decrements and now over here since this B is equal to this B so what happens is DPI I again is three 0 1 1 2 three right plus equals to the previous number which is zero right so 0 plus 0 is still zero nothing changes there t will decrement again not t but I will decrement again two now since they are the same we check again DPI plus one right on the previous calculated one this will give us one okay next I will decrement once more but since now we are targeting R which is not the same as B so we're going to skip it J Will reset not J reset J Will increment to three I will reset to four then we start from the back move on up then we start again right so we check TT not the same decrement move the pointer since now they are the same I for three 0 1 2 three this will plus one from the result result decrement now for this B it's still the decrement now for this B it's still the same so over here same so over here one plus this one will give us one plus this one will give us two decrement R is not the same as B so two decrement R is not the same as B so reset everything again save increment to four so again they don't match decrement now we're looking at this character they match right so I3 0 1 2 3 this will 0 1 2 3 minus two 0 1 2 3 this will three three decrement decrement to this one since they're the same 0 one to this one since they're the same 0 one 2 + 2 + one give us give us three decrement one give us give us three decrement again this will give us R which does not again this will give us R which does not equals to B right so J increments one equals to B right so J increments one more time looking at this last more time looking at this last character I will back to four and here character I will back to four and here since at the start they match so 0 + 3 since at the start they match so 0 + 3 this will give us three and we know what this will give us three and we know what happens to the rest because none of this happens to the rest because none of this matches with P so we can basically skip matches with P so we can basically skip this entire for Loop here meaning that this entire for Loop here meaning that what we' have done so far in this DP uh what we' have done so far in this DP uh caching if we were to return the length caching if we were to return the length of M so M if you remember is 4 0 1 2 3 4 of M so M if you remember is 4 0 1 2 3 4 which is the result we will get that we which is the result we will get that we will get three which is the result we will get three which is the result we can generate rbb BT from the string s of can generate rbb BT from the string s of r with three Bs one t basically the same r with three Bs one t basically the same thing with the example shown over here thing with the example shown over here right when there's three right when there's three Bs so here 3B and 2B 2B I just shorten Bs so here 3B and 2B 2B I just shorten it to make the video not too long Yeah it to make the video not too long Yeah so basically that's what the code does so basically that's what the code does that's what how that's how you can cach that's what how that's how you can cach what you have done especially when you what you have done especially when you start from the back it makes it slightly start from the back it makes it slightly more efficient and I think that's all I more efficient and I think that's all I have to show thanks | 2024-03-21 10:53:28 | 115 | Distinct Subsequences - LeetCode #115 - C++ |
|
sTgIU6KVztI | hello and welcome in today's video we are going to solve in today's video we are going to solve the word break which is a quite popular the word break which is a quite popular problem it was asked frequently by meda problem it was asked frequently by meda amazon microsoft and google amazon microsoft and google let's look at the first example we are giving an input string s containing lead code and the list of the strings in the word dictionary the required function should return true because we can find a way to segment s into the parts that are present in the word dictionary and the same result also in the example 2 however in the third example send or or and consumes d so the remainder will be string og which is not present in the dictionary therefore the answer will be false this problem can be solved by a variety of the techniques including a recursive function dynamic programming or graph traversal approaches basically we need to scan through the s and cut segment from its beginning so that those segments are in the given dictionary then we recursively search on the remainder part of the string this time from the letter after ending position to the end of the string this knife solution works but will not pass test cases in which the input size is very long because the timer complexity is order of the two power n to improve to improve this knife approach we can use dynamic programming to avoid repetitive steps by reusing saved computation with dp the time complexity will be dropped to the order of the end power 3 which is good but we can do event better especially with the companies like meta they usually expect more non-dp solutions our approach is using a breath first search which requires the transfer problem into the tree's tree space let's consider the string s as a root note every note represents the remainder of the string after cutting some prefix segments which is in the dictionary two notes are connected let me show this let me show this graph graph here here [Music] as you can see in this graph two notes a and b are uh connected only if the prefix of the first node is a valid string present in the dictionary list of the words to implement this idea we start from to implement this idea we start from the first letter of the input string s the first letter of the input string s and look for and look for every possible substring that is in the every possible substring that is in the dictionary we push back the substring dictionary we push back the substring starting from the next letter after starting from the next letter after previous segment to the to the queue to previous segment to the to the queue to use in the pfs process so for all nodes in the queue we apply this process if we reach the end of the given string and all segments found in the dictionary then we return true otherwise result okay let's idea and add given string s and add given string s to the key to the key and for and for avoid uh avoid uh visiting nodes multiple times we visiting nodes multiple times we we use we use hashtag hashtag to remember them so while rev reward in the given rev reward in the given word dictionary as starts with with that word then we need to create a if if we reach to the end of string s this is our terminated condition this is our terminated condition condition so we just need to return true if not we need to check that if this new string is new we never [Music] we never visited before that we need to add it to the queue and if and if we haven't we haven't returned from the termination condition returned from the termination condition then we need to return then we need to return files files then okay there's a problem here false should be true let's check the code string f forward in the dictionary if s start oh we need one more english okay let's submit as you can is as you can see it's accepted and pretty thank you for thank you for watching this video and i hope watching this video and i hope it was helpful it was helpful thank you | 2024-03-21 12:24:57 | 139 | Word break - Leetcode 139 |
|
590RVX1JoM8 | Hello everyone Welcome to my channel here they solve problems Lead code channel here they solve problems Lead code today task number 1026 maximum today task number 1026 maximum difference between node and difference between node and parent level medium Yes the root of a parent level medium Yes the root of a binary tree we need to find the maximum binary tree we need to find the maximum maximum value V so which is the nodes so the difference between nodes A and B nodes so the difference between nodes A and B such that the difference in such that the difference in modules modules modules difference b so the value is a bit of a description a little b so the value is a bit of a description a little confusing but in general the point of the problem is confusing but in general the point of the problem is that we need to that we need to return the return the maximum maximum maximum difference maximum difference between the nodes and their parents, moreover, between the nodes and their parents, moreover, the parent can be not only the parent can be not only immediate but also any parent immediate but also any parent above node is the parent of the one node is the parent of the one below. That is, for example, node 3 1 6 7 and so below. That is, for example, node 3 1 6 7 and so on. That is, you need to on. That is, you need to find the maximum absolute find the maximum absolute maximum absolute Difference between maximum absolute Difference between any two nodes that are in the any two nodes that are in the same relationship as parent Descendant, same relationship as parent Descendant, that is, exactly in the first that is, exactly in the first example example example is two nodes 1 and their maximum differs in the answer. What will we do? Well, firstly, we have a problem with binary trees, that is, accordingly, the easiest way to solve this is to use recursion. Next, we need to decide under what conditions we get the maximum the difference, that is, the maximum The difference between some current node and any of the parents above can be in two cases: this is if some parent has a minimum value relative to the current node. And the second option is value, that is, in theory, this is the meaning value, that is, in theory, this is the meaning that for each node we that for each node we check the maximum and minimum maximum and check the maximum and minimum maximum and minimum values of the minimum values of the parents and as soon as some difference is greater than the previous one, we update this value, taking into account that we use recursion, this is described as simply as possible in the code, it will be more clear, we need an auxiliary function we need an auxiliary function that will just be a that will just be a recursive recursive lane What will be in the hepe hepe there will be the lane What will be in the hepe hepe there will be the current node itself and also two current node itself and also two values These are the minimum and maximum I will call them min and max val this means the minimum and maximum value of the parents, that is, initially these values will be equal value of the root and then, when passing through each node, the value will be updated accordingly for each node, we will difference, so for now we will skip the difference, so for now we will skip the implementation and immediately enter this function, implementation and immediately enter this function, that is, how we will call it. The that is, how we will call it. The first parameter is the first parameter is the root, then root, then we pass the value of the root Now let's implement this since this will be a recursive since this will be a recursive since this will be a recursive function We need a base case; in our function We need a base case; in our case, the base case is the case when the case, the base case is the case when the node is empty. That is, if an empty node is passed, then we assume that the difference is zero. Next, we need to return the maximum possible the maximum to determine what options the maximum to determine what options are possible, that is are possible, that is are possible, that is node For example, we have a current node, let’s say three Maxi the maximum minimum value of the parent is eight because we only have the root, that is, what we need, we value of the current current value of the value of the current current value of the current node current node minus minus NBA one of the options could be like this NBA one of the options could be like this that is, we compare the difference between the current that is, we compare the difference between the current node and the node and the minimum. That is, this is the case minimum. That is, this is the case when the current node is large; the second option, on the contrary, if we assume that the current node is small, then its difference with the maximum parent could potentially be Maxima; these are two options; the next option is a recursive tree That tree That tree That is, we have a recursive is, we have a recursive function, so function, so we call the same function for left we call the same function for left and right under the tree. Moreover, when calling a and right under the tree. Moreover, when calling a recursive function, we need to update the recursive function, we need to update the minimum maximum value of the minimum maximum value of the parents, that is, parents, that is, in the same example with a triple, in the same example with a triple, that is, for a triple, the maximum that is, for a triple, the maximum minimum value of the parent is - minimum value of the parent is - minimum value of the parent is - for example for the left under the tree the minimum value will be three since the current value of three is less than in and accordingly here the logic is like this, that is, we will take the minimum and the value of the node is the same for the and the value of the node is the same for the maximum maximum makva right right right under the tree, so it may be that for the current node the difference may already be maximum, or this maximum maximum, or this maximum difference will be somewhere in the child difference will be somewhere in the child nodes. Let's try to run tests nodes. Let's try to run tests and see if this and see if this solution is suitable. The tests passed, we try to send it, so the decision is made and it is clear that it is only in time, but also in memory, this problem is quite simple, that’s all for today, thanks | 2024-03-25 15:13:16 | 1,026 | LeetCode 1026 Maximum Difference Between Node and Ancestor - python |
|
jQ79UYPyqRA | all right let's talk about the prison cells after 10 days so you have a cells after 10 days so you have a person's cells a rate and an integer n person's cells a rate and an integer n and for every for every single day you and for every for every single day you need to just follow the constraint so if need to just follow the constraint so if a cell has to adjust neighbors they are a cell has to adjust neighbors they are both occupied or both vegan right it both occupied or both vegan right it becomes occupied so becomes occupied so uh uh what it means is like if there is a what it means is like if there is a uh sorry give me one sec so if this is uh sorry give me one sec so if this is day zero right so day zero right so at least at this day i mean at this at least at this day i mean at this index for the first day since the index for the first day since the neighbor are the same so you need to neighbor are the same so you need to just just change the change the cell's value to occupy the occupied cell's value to occupy the occupied value is one and the basis value is value is one and the basis value is actually zero so actually zero so so we know like what so imagine we don't so we know like what so imagine we don't know the value know the value for the for the for the day one they just follow for the day one they just follow so since stay zero the the first value so since stay zero the the first value is zero then we don't change anything is zero then we don't change anything and then now uh the day the index one and then now uh the day the index one for day zero the both are actually what for day zero the both are actually what are the same right the the neighbor are are the same right the the neighbor are the same so it's one the same so it's one and for these ones neighbors are the and for these ones neighbors are the same and one same and one this one neighbor another saying zero this one neighbor another saying zero neighbor are not the same zero neighbor are not the same zero and zero and zero right so uh they're and zero and zero right so uh they're just making sure my answer is correct so just making sure my answer is correct so zero one one zero one and four zero zero one one zero one and four zero right and then right and then and i miss another zero which is at the and i miss another zero which is at the end so this is going to be the end so this is going to be the exponential exponential so so uh what do i need to do so you want you uh what do i need to do so you want you want to return the state of the prison want to return the state of the prison after and days okay so after and days okay so at this point right at this point right so at this point you have to know at so at this point you have to know at some point some point uh day x uh day x a x a x might be repeatedly uh might be repeatedly uh beforehand right so we need to know like beforehand right so we need to know like we need to store all of the value we need to store all of the value into the set into the set so we will be able to understand okay so we will be able to understand okay this this uh this date is already uh this date is already happened before so we can actually just happened before so we can actually just pull out the record out and then pull out the record out and then calculate calculate the the uh the state for the prisons uh the state for the prisons and then and then so if so if there is a if there's a day so if so if there is a if there's a day we already use right we just have to we already use right we just have to calculate the the risk calculate the the risk so if if there's a fun day right so if so if if there's a fun day right so if there there is a day that we happen in previous so is a day that we happen in previous so it's going to be x so we just have to it's going to be x so we just have to minus x basically minus x be on this so minus x basically minus x be on this so we find out the y so we just have to we find out the y so we just have to traverse the y iteration and to find out traverse the y iteration and to find out if there is something if there is something um happening by the state updating then um happening by the state updating then you just turn away and this is going to you just turn away and this is going to be pretty much it so uh it's definitely be pretty much it so uh it's definitely not a minus x it's going to be a mark not a minus x it's going to be a mark on my x so i would i would on my x so i would i would i'll explain later but uh definitely i i'll explain later but uh definitely i will just will just uh uh you know you know try to stop for it so i had i need a try to stop for it so i had i need a hashtag hashtag i need to have forward into a string you i need to have forward into a string you can say in the picking array doesn't can say in the picking array doesn't matter but i would like to use a string matter but i would like to use a string just in case uh this is more easier to just in case uh this is more easier to read read and then i will have i will have a cycle and then i will have i will have a cycle count right except for accounts starting count right except for accounts starting from zero from zero and now i'll say dates uh they're able and now i'll say dates uh they're able to run and i need to have a boolean to run and i need to have a boolean function to make sure there's a cycle so function to make sure there's a cycle so uh it's going to be false so i'll say i uh it's going to be false so i'll say i will say while this is actually work will say while this is actually work base is greater than zero right i was base is greater than zero right i was just making sure and then basic just making sure and then basic increment every single time i iterated increment every single time i iterated you can use for loop doesn't matter so i you can use for loop doesn't matter so i have the next have the next so next array represents so next array represents uh uh the array half the array i calculate for the array half the array i calculate for the previous uh the current state the previous uh the current state so i'll have a helper function that's so i'll have a helper function that's going to go next day going to go next day i will pass in while passing the cells i will pass in while passing the cells right right and let me just quickly write my helper and let me just quickly write my helper function function next state next state and now let's say what uh cells right and now let's say what uh cells right i need to create a temporary array which i need to create a temporary array which is going to be update version after i is going to be update version after i type it right so i'm going to say 10 type it right so i'm going to say 10 click on the new games the lens is going click on the new games the lens is going to be the same all right to be the same all right and i'll continue right and i'll continue right then i need to update it and then for then i need to update it and then for for every single time this is on viewer for every single time this is on viewer for india for india than ten thousands than ten thousands i plus over so temperature i tend the i i plus over so temperature i tend the i right right so do we have to take care about zero so do we have to take care about zero index no right because index no right because uh if you notice the zero index is uh if you notice the zero index is always the same so if i didn't assign uh always the same so if i didn't assign uh for the next iteration for the in array for the next iteration for the in array i would just basically just by default i would just basically just by default it's going to be zero and for the it's going to be zero and for the uh and also for the n right the first uh and also for the n right the first one is definitely one but i didn't one is definitely one but i didn't assign assign the the last last index for the next the the last last index for the next phase right so you would just by default phase right so you would just by default it's going to be zero right it's going to be zero right uh sorry yes if i didn't change anything uh sorry yes if i didn't change anything it's one bit it's gonna be by default it's one bit it's gonna be by default it's gonna be zero it's it's not one it's gonna be zero it's it's not one sorry i just have a sorry i just have a um um typo i mean not typo just a wrong typo i mean not typo just a wrong statement right so i would just have to statement right so i would just have to go through the cells for a neighbor so go through the cells for a neighbor so if they're starting from one right if they're starting from one right i need to know zero and two right so i need to know zero and two right so cell if the cell cell if the cell i minus one is equal to cells if i i minus one is equal to cells if i perform right if they are equal i'm perform right if they are equal i'm gonna assign one if they are not i'm gonna assign one if they are not i'm gonna assign zero right gonna assign zero right so okay so i have a i have a heaven in so okay so i have a i have a heaven in the ring next i'm going to convert to the ring next i'm going to convert to the the string so you can say string so you can say eraser to string eraser to string if passing the next or you can say you if passing the next or you can say you can say what string uh can say what string uh it's a new frame right new string and it's a new frame right new string and then sounds right doesn't matter it then sounds right doesn't matter it doesn't matter how you use right but i doesn't matter how you use right but i will say okay do i have it in the set will say okay do i have it in the set subset content subset content data contains valve right if i don't data contains valve right if i don't have it i'm going to have it i'm going to say that say that about right and i will just about right and i will just cheat chocolate flour comes cheat chocolate flour comes and if i and if i okay if i don't have it i okay if i don't have it i i into the same and i keep travel of the i into the same and i keep travel of the account so if i if i do have it account so if i if i do have it i will have to make my cycle a little i will have to make my cycle a little true true right now bridge right now bridge right operate and then right operate and then so i would say if so i would say if if the cycle i will do something right if the cycle i will do something right but beforehand i need to update my cells but beforehand i need to update my cells for for every single day right i will for for every single day right i will just just update my cells and then cells update my cells and then cells you'll just need to set equal to an x you'll just need to set equal to an x for the next iteration and then we'll for the next iteration and then we'll just stick them in my base just stick them in my base all right if this is happening this all right if this is happening this cycle then we just have to calculate the cycle then we just have to calculate the n n uh for the rest of the uh for the rest of the cycle contract cycle contract and then and then traverse forwards of the traverse forwards of the uh uh updating right updating right for the cells for the cells so cells equal to the next state so cells equal to the next state itself itself and at the end you will just return and at the end you will just return cells right so i'm going to explain uh cells right so i'm going to explain uh what happened so what happened so um um i have a set i sorting i store into the i have a set i sorting i store into the string string and i convert the inc array into the and i convert the inc array into the string later so i have a psycho count to string later so i have a psycho count to choco flow count choco flow count after after every every every iteration right and i have a base every iteration right and i have a base temporary variable temporary variable and then i have a cycle boolean just and then i have a cycle boolean just making sure i know uh there's a cycle making sure i know uh there's a cycle so i'll create a temporary in array it's so i'll create a temporary in array it's going to call next going to call next so i will i'll just have to generate a so i will i'll just have to generate a new in array based on the this helper new in array based on the this helper function function so this is checking the neighbor if they so this is checking the neighbor if they are the same then one not not the same are the same then one not not the same zero so it's going to be like this but zero so it's going to be like this but the problem is i don't need to traverse the problem is i don't need to traverse anything right anything right but you have to say but you have to say one one right so uh you don't need to traverse right so uh you don't need to traverse again you just have to traverse at this again you just have to traverse at this point right and then temp will just point right and then temp will just update it update it all right so uh this is a typo for sure all right so uh this is a typo for sure all right and let's move on so all right and let's move on so i will convert to the string follow in a i will convert to the string follow in a rate and then i check do i have it in rate and then i check do i have it in the set if i don't have it i will add the set if i don't have it i will add to the string and then i will just kick to the string and then i will just kick off to increment my tones if i off to increment my tones if i if i do have there's a cycle for sure if i do have there's a cycle for sure right and i'll break out the side a right and i'll break out the side a regular well loop regular well loop and then and then for every single time i need to update for every single time i need to update my current cells to the latest you know my current cells to the latest you know rate uh rate uh latest cells right so if i if i saw this latest cells right so if i if i saw this day zero i need to update to day one for day zero i need to update to day one for next iteration next iteration right now i need to just making sure do right now i need to just making sure do i have a cycle if i do have a cycle i have a cycle if i do have a cycle which mean which mean i didn't finish the iteration i didn't finish the iteration because i need to just finish because i need to just finish until until uh day seven right if i break out early uh day seven right if i break out early break earlier then i need to traverse break earlier then i need to traverse rest of the days rest of the days uh if if that's happening so i would uh if if that's happening so i would just use in the mall just use in the mall mall will just give me like uh give me mall will just give me like uh give me kick track of the racing uh for the rest kick track of the racing uh for the rest of the days right so i'll just traverse of the days right so i'll just traverse the rest of the days for the next day the rest of the days for the next day and then i will return the final and then i will return the final solution for sales solution for sales and let me run it oh i do have a typo and let me run it oh i do have a typo cycle pump right cycle pump right okay sorry okay sorry and and missiles no all right let me submit all right so let's talk about time and space so for the space this is space this is space this is space but uh this one is the most important they should be like how many iterations you can happening in the cells right so it's going to be uh all of um right uh times what the number of cells right so uh it's going to be all of m times c and for the for the time this is time this is time this is time it looks like this is always always what always uh land of eight so loaf eight right but the problem is what the n right the sun could be larger right so uh this is all of n base all of n times uh all of seven i mean sorry all of h all over h right so uh so it's going to be all of n and it's full time again all of n and this older thing is definitely shorter because you use more so i'm going to ignore this time time complexity i'm going to use the worst case all of n and represent this one and if you want to be more on detail you can say all of n times h right and then for the space this is a space how and you have to store how many time uh string you need to store the number of time for the cells right so it's going to be all of c times n right and this is a solution | 2024-03-25 12:17:19 | 957 | LeetCode 957 | Prison Cells After N Days | HashSet | Java |
|
zYOGwEl_F-w | That will be the morning to day to ask question is jump we six Soviet Union to Soham told jump we six Soviet Union to Soham told by name came out if your initial by name came out if your initial futile effort heroine we here to Vijendra futile effort heroine we here to Vijendra young adult most cases forward so and young adult most cases forward so and placid inside Sadher Lau example placid inside Sadher Lau example can go Vaastu study can go Vaastu study can go Vaastu study we have to click the like share and subscribe button here we can go here we can go here but 101 - 2 - so I will do this here we will go from here If it was If it was If it was zero then it is zero - if it is 2070 plus 4 then zero then it is zero - if it is 2070 plus 4 then maximum will get justice, after that maximum will get justice, after that we are here as we are, so we could go to the last, we are here as we are, so we could go to the last, now we will not go to apply, we will go to now we will not go to apply, we will go to Fida Dedar, if there will be margin of sleeper and four plus Fida Dedar, if there will be margin of sleeper and four plus then this then this then this then basically if I understand then I can go in the hands of two options for those who have eggs, then they can go with the second option and basically we have to vitamin in some maximum then this cup is If it seems If it seems If it seems like a one week solution, then what will we like a one week solution, then what will we do, for this we will take this school, do, for this we will take this school, what should we do, we were also told that after this we will what should we do, we were also told that after this we will see here, let's try that - 509 have been done so that you will get the fiber here. that you will get the fiber here. that you will get the fiber here. if we count this volume then tension will be done here, we will have the option to go to the pipe, there will be international debit, then here the answer will be 8 app, for all this, it has to be flat like this, the Here Here Here and here fry luck will come to us here and here fry luck will come to us here eighth if we give it a ball eighth if we give it a ball this hair if you have a group then it will be added either seven will be this hair if you have a group then it will be added either seven will be 100 this is our 100 this is our answer sheet for this no subscribe can't take answer sheet for this no subscribe can't take subscribe subscribe subscribe can say that can say that half a minute from now, there will be another 911, so this is what you see half a minute from now, there will be another 911, so this is what you see every day, let's look at this once, every day, let's look at this once, welcome back to the, to understand this. welcome back to the, to understand this. welcome back to the, to understand this. happening, how are you, basically we have this less, that is why we have found its maximum, if we look at the time for this, like if we go from equal to one to equal to k, then we will have to take one ruby Debiting us for doing vitamins in the name of Vikram will be Debiting us for doing vitamins in the name of Vikram will be Debiting us for doing vitamins in the name of Vikram will be yours and the complexity yours and the complexity of *K but here it will of *K but here it will not be the head and asked for a difficult English, not be the head and asked for a difficult English, then if you will regret the problems, then if you will regret the problems, you must know that Tanglish to you must know that Tanglish to Bigg Boss for 9 months. Bigg Boss for 9 months. Bigg Boss for 9 months. competition is shown to a normal PCs in one second, because of this, our basic here is that bell * only approach will work, song will end and login, either we will have to think something like this, then what will we do to login. Reminder use max, maximum volume, then whey login in it will kill the bike, and then in doing Namaskar tower, if Mara and Pintu will give camera, then they can see the coat quickly in the process, so for that we will have to take a note first. So class node in this, what happened to you, this will be our indication, this is to do induction stove because we need to check thing, our basically what we will check is one to three, we set it only in the end position, Ca Ca Ca n't take the maximum right five n't take the maximum right five minutes to the value of the and also minutes to the value of the and also indicators so one by one will make the lower part of it indicators so one by one will make the lower part of it these are Indian XXX XXX So n Indian postal new mint So n Indian postal new mint namaskar lens ka namaskar lens ka dp koi abusi basically mi uie name wali wali ke dp koi abusi basically mi uie name wali wali ke zero so sad image complaint zero so sad image complaint singh table hain singh table hain now we have to now we have to make a CM in private max key we will use it because make a CM in private max key we will use it because maybe not only to make maybe not only to make maybe not only to make use this for primary fuel soap opera here was the daughter she was Entries word max only question you are often positive why am I now that we have a servant Entries we need a note we have to compare according to the value of this note Index of note Our maximum Index of note Our maximum Index of note Our maximum should try the value of note of intestine should try the value of note of intestine So for this we will use function by keeping name So So for this we will use function by keeping name So here we will take notes in lineage 9 here we will take notes in lineage 9 end to end It will return us end end to end It will return us end against aluminum zinc wanted owner against aluminum zinc wanted owner What should we do here What should we do here What should we do here first one is of value, so if we have air to check, then for that, if we were to become the president, then what will we do? The channel of * key is there - if we do, then Wali this will be mature example Wali this will be mature example Wali this will be mature example if and 210 is n 184 test minus plus two if and 210 is n 184 test minus plus two vagina tells positive trends that vagina tells positive trends that element small entry se and similarly you can element small entry se and similarly you can be a great art for the second that when in be a great art for the second that when in 110 and this then Lakshmi pendant and * - click 110 and this then Lakshmi pendant and * - click We will subscribe to the maximum, this was our now we have to pay the payable bill, we were looted and with these efforts, Amazon Radhe and I were looted and with these efforts, Amazon Radhe and I 75 questions, first we will check Narayan 75 questions, first we will check Narayan that it will not be like you, that we will that it will not be like you, that we will enter the valid key. enter the valid key. enter the valid key. appointed as another person against that access Sibal has also seen from the social media that the mobile has been given by us as to why it is not there and our basic value which will come is at our maximum only The The The maximum element is one of ours which we will use, maximum element is one of ours which we will use, so at least that is so at least that is our come - how is it small or not, I will our come - how is it small or not, I will go to the maximum about it when we will go to the maximum about it when we will do the boxing of the court, so if it is so do the boxing of the court, so if it is so then basically let us take out that black, then basically let us take out that black, ginger and that mileage. that after this, we have to that after this, we have to click on the Sacrifice table, Samaj click on the Sacrifice table, Samaj Namaskar Lee, along with that, we have to add it, Namaskar Lee, along with that, we have to add it, which will be at the top of the marksheet, that is, it will be the which will be at the top of the marksheet, that is, it will be the maximum one, maximum one, and we have to add it. and we have to add it. and we have to add it. in our interest Should they be in the dark world Nude Nude DP Aaye Earns An American Will See Lowest Glycemic An American Will See Lowest Glycemic Reach So That's Why We DP Reach So That's Why We DP That Kalyan Singh Ne Theater Will Do The Day That Kalyan Singh Ne Theater Will Do The Day On YouTube Ishwar Allah And His On YouTube Ishwar Allah And His On YouTube Ishwar Allah And His and Kheda's and Kheda's obscene abuses of our robbers have been made nice. I have just compared them. Thank you, I have made it a posting it here, so we have already posting it here, so we have already handled the zero-valued thing. handled the zero-valued thing. Subscribe to the song. Subscribe to the song. Subscribe to the song. done that point, we will do that point again there was a suicide note knotted scientist is talking about this so let me scientist is talking about this so let me explain to one of the drops so basically what explain to one of the drops so basically what we did here is this we did here is this we did here is this Planets has just become Asaf Khan, two basic aspects are there only this much are there, stand a product of Europe, Jai Hind, this orange which is Bollywood, loot words loot words which are your special mission that he slept right now that he slept right now that he slept right now what are we doing now, we went to the high cost one, that is, we basically went to this volume, now what we have to do is here, we checked whether our person is an MP, he is not, 2010, we have to see that when our amnesty is on. Which is the maximum potato's link, how is the wireless small, what Dr. So, the age is 40 minutes, 512 - free is - 200 notes, notes from very dangerous, so killed, made sure to put it in the dpi of the brothers, hello, volume plus, this which is At the top of the volume At the top of the volume At the top of the volume maximum will be looted solid 20 plus minus five and maximum will be looted solid 20 plus minus five and night and the name of this church we came try is broken if we will check by going here that brother high cost for that they him but like that or not so if Our two is like this okay so Our two is like this okay so Our two is like this okay so here we have like subscribe now to check the volume maximum volume 98100 Noida two minus minus one not to where so we will make it - 28 200 this will work Switch Switch Switch first, how will we check, even now the navi first, how will we check, even now the navi chatting is not broken, dance and why is this chatting is not broken, dance and why is this indiscriminate correct order indiscriminate correct order that we are justified in this to show's glory, that we are justified in this to show's glory, Shri Mahima people, Shri Mahima people, I am still at the same time, forced to go, I am still at the same time, forced to go, Sukshma will go to high cost, this is ours. Sukshma will go to high cost, this is ours. Sukshma will go to high cost, this is ours. it is free but on high cost method, our mango will be checked that this is Jayesh Jain Free - 30 Aug 09 This is not Fruits Sexual So on this we will basically find out that we have set the maximum N plus minus On Eggs And Not Adding That In Correct Quantum Jatt Flying Instructor To So You Think This Expression Hair Treatment Maximum In Next Video Icon To 400 Witnesses In Snow Line This Zinc Noida Office - Before PIMS Is Equal To One So We Basically Have To Rally Till then we will Till then we will Till then we will not be able to do this, this will have to be removed here, not be able to do this, this will have to be removed here, basically it will be that A basically it will be that A and Navami's relation is on five, now the and Navami's relation is on five, now the maximum has been contacted maximum has been contacted that due to which Aalu * 90001 is two places in that due to which Aalu * 90001 is two places in five. five. five. point to so we will check it that maximum okay here we had to debit one glass one that for this set we have to love index one so normal note 4 which retrieve from the kinnars one so normal note 4 which retrieve from the kinnars Hoga word, both are necessary and Hoga word, both are necessary and both are belts, then for that we will check. both are belts, then for that we will check. Here, take out eight, one plus Here, take out eight, one plus three, Lud 5911 Sir, subscribe to the channel here, I am three, Lud 5911 Sir, subscribe to the channel here, I am not able to understand anything | 2024-03-20 14:31:51 | 1,696 | June - 9 2021 Leetcode Solution: Jump Game VI EASY Solution! |
|
ci4PIq1NWoU | [Music] hey guys welcome back to another video hey guys welcome back to another video and today we're going to be solving the and today we're going to be solving the lead code question longest palindrome lead code question longest palindrome so in this question we're given a string so in this question we're given a string which consists of lowercase which consists of lowercase or uppercase letters and we need to find or uppercase letters and we need to find the length of the longest palindrome the length of the longest palindrome that we can build using those letters that we can build using those letters and note that this is case sensitive so and note that this is case sensitive so capital a and small a is not considered capital a and small a is not considered a palindrome a palindrome and assume the length of a given string and assume the length of a given string cannot exceed this number cannot exceed this number thousand and ten okay so what exactly is thousand and ten okay so what exactly is a palindrome and how can we solve this a palindrome and how can we solve this question question so let's just take a quick look at that so let's just take a quick look at that so let's say that we're given so let's say that we're given these letters as our input so we have these letters as our input so we have a b c c c c d d okay so what is a a b c c c c d d okay so what is a palindrome palindrome a palindrome is let's say you have this a palindrome is let's say you have this over here a over here a and a and a okay and when you read it and a and a okay and when you read it from left to right you go from left to right you go a then you get n then you get a but when a then you get n then you get a but when you read it from right from left you read it from right from left so right to left you get a then n and so right to left you get a then n and then a then a again so a palindrome is when you read again so a palindrome is when you read it from left to right it from left to right or if you read it from right to left or if you read it from right to left it's the same but in this case we need it's the same but in this case we need to make sure to make sure that the letters are case sensitive so that the letters are case sensitive so for example if we had capital a for example if we had capital a big n and small a this is not a big n and small a this is not a palindrome but this is palindrome but this is so it is case sensitive in this case so it is case sensitive in this case okay so now let's see okay so now let's see how can we find the length of the how can we find the length of the longest palindrome longest palindrome given a string so to do this what we're given a string so to do this what we're going to do is we're going to going to do is we're going to count the frequency of each of our count the frequency of each of our letters so i'm going to do this inside letters so i'm going to do this inside of a dictionary of a dictionary so first we have the letter a and it has so first we have the letter a and it has a frequency of a frequency of one it only appears one time then we one it only appears one time then we have the letter b have the letter b sorry which also has a frequency of one sorry which also has a frequency of one and we have the letter c and this has a and we have the letter c and this has a frequency of frequency of one two three four so let's add that one two three four so let's add that and finally we have the letter d which and finally we have the letter d which has a frequency of two has a frequency of two so this is going to be our dictionary so this is going to be our dictionary right where we're holding all of the right where we're holding all of the frequencies frequencies actually for the purpose of this video actually for the purpose of this video i'm going to add one more d i'm going to add one more d over here so i'm just going to change over here so i'm just going to change this value over here to three this value over here to three so instead of two we're going to have a so instead of two we're going to have a value of three value of three okay so we have a b c and d and d has a okay so we have a b c and d and d has a value of three so let me just add that value of three so let me just add that here there's a third d here there's a third d okay so how can we find out what the okay so how can we find out what the length of this palindrome is going to be length of this palindrome is going to be and the answer to that is pretty simple and the answer to that is pretty simple we're going to start off by we're going to start off by looking at everything that is even so looking at everything that is even so what is even over here what is even over here c is even so let's just go to c and c is even so let's just go to c and we're going to add c on each side we're going to add c on each side so for every c we have on the left hand so for every c we have on the left hand side we're going to have a c side we're going to have a c on the right hand side so as it is it's on the right hand side so as it is it's a palindrome cc a palindrome cc so let's do it again so we have two more so let's do it again so we have two more left so we add one over here left so we add one over here we add one over here so so far we got we add one over here so so far we got four letters down and as it is it's a four letters down and as it is it's a palindrome palindrome so we took care of c now let's go to d so we took care of c now let's go to d so d has three letters and the thing is so d has three letters and the thing is uh we can't use all three letters but uh we can't use all three letters but we could use some of it so what we're we could use some of it so what we're going to do is we're going to use going to do is we're going to use how many ever possible to make it a how many ever possible to make it a valid palindrome valid palindrome and the answer to that is we can use two and the answer to that is we can use two parts so we can only use two d's parts so we can only use two d's so we can use one d over here and one d so we can use one d over here and one d over here over here so we're going to have c c d and then d so we're going to have c c d and then d c c over here c c over here now the remaining letters all have just now the remaining letters all have just a frequency of one a frequency of one and note that over here we used up two and note that over here we used up two and d and d currently has a frequency of one so what currently has a frequency of one so what we can do over here is we can do over here is these three on the left and these three these three on the left and these three are are on the right are always going to be on the right are always going to be constant constant but we can have one letter over here it but we can have one letter over here it could be could be anything so we can have one letter over anything so we can have one letter over here this letter can either be a here this letter can either be a so if you check this this is palindrome so if you check this this is palindrome or this letter can be b or this letter or this letter can be b or this letter can be d can be d any of them work so the answer for this any of them work so the answer for this is is we have a frequency of 1 2 3 4 we have a frequency of 1 2 3 4 which can be any letter over here and we which can be any letter over here and we have 5 6 have 5 6 7 and just to clarify when i say any 7 and just to clarify when i say any letter letter it means any letter which has an odd it means any letter which has an odd frequency so in this case a frequency so in this case a b and d since it has a frequency of one b and d since it has a frequency of one since we used up two of its letters since we used up two of its letters so the answer for this is going to be so the answer for this is going to be seven so the answer is seven and we're seven so the answer is seven and we're going to output that going to output that so let's see how we can write this in so let's see how we can write this in code it should be pretty simple to code it should be pretty simple to understand understand all right so we could do so all we need all right so we could do so all we need to do in the beginning is we need to to do in the beginning is we need to find out some sort of way find out some sort of way to store everything in a dictionary per to store everything in a dictionary per se and we could use the se and we could use the counter from collections but instead counter from collections but instead we're just not we're not going to use we're just not we're not going to use any libraries and we're just going to do any libraries and we're just going to do it it using pure python so i'm going to create using pure python so i'm going to create a a dictionary called letters and it's going dictionary called letters and it's going to store all the letters and what we're to store all the letters and what we're gonna do is we're gonna go gonna do is we're gonna go through each character so for character through each character so for character in our string in our string s and if i not s and if i not in our if i not in letters so if it's in our if i not in letters so if it's not in our dictionary not in our dictionary then in that case we're going to add it then in that case we're going to add it to our dictionary to our dictionary with the frequency of one so it's going with the frequency of one so it's going to be letters to be letters i equals to one else so this is not the i equals to one else so this is not the case case that means that it is inside of our that means that it is inside of our dictionary and we're just going to dictionary and we're just going to increase the count by one so we're going increase the count by one so we're going to go to letters i to go to letters i and we're going to increase its and we're going to increase its frequency by one so plus equals one frequency by one so plus equals one so now we have our dictionary ready and so now we have our dictionary ready and over here i'm gonna uh over here i'm gonna uh set two variables so one is going to be set two variables so one is going to be our result our result and over here i'm going to have a and over here i'm going to have a variable called odd which is going to variable called odd which is going to count the in count the in the number of instances of odd values we the number of instances of odd values we have have okay so now that we have that i'm also okay so now that we have that i'm also going to have a going to have a if statement so if the length of our if statement so if the length of our letters letters is equal to one so what does this mean is equal to one so what does this mean so whenever length of the letters so whenever length of the letters is equal to one that means that there's is equal to one that means that there's only one letter only one letter and let's say there's only one letter and let's say there's only one letter and you have it repeated nine times or a and you have it repeated nine times or a thousand times thousand times how many of our times it's always going how many of our times it's always going to be a palindrome to be a palindrome since there's only one letter so in that since there's only one letter so in that case no matter what case no matter what we're just gonna return the length of we're just gonna return the length of that so we're gonna return that so we're gonna return letters and the values so it's just letters and the values so it's just going to be s0 going to be s0 okay so uh this is the key s0 is going okay so uh this is the key s0 is going to be the key to be the key and we're going to return whatever value and we're going to return whatever value that is so that's going to be our answer that is so that's going to be our answer but if that is not the case if the but if that is not the case if the length of our letters is more than one length of our letters is more than one in that case we're going to iterate in that case we're going to iterate through all of the values so for through all of the values so for i in letters dot values i in letters dot values okay so this gives us all of our values okay so this gives us all of our values and over here we're gonna have a if and over here we're gonna have a if statement which checks statement which checks whether this value is greater than one whether this value is greater than one so if it's equal to so if it's equal to two or more than that so if that is the two or more than that so if that is the case we're going to go into two if case we're going to go into two if any of the two if conditions so if i any of the two if conditions so if i mod 2 is equal to 0 so in this case mod 2 is equal to 0 so in this case it is an even number and in that case it is an even number and in that case we're just going to we're just going to add the value of i to our results so add the value of i to our results so that's pretty straightforward that's pretty straightforward but if the value of i mod 2 is but if the value of i mod 2 is not 0 so in this case it's an odd number not 0 so in this case it's an odd number and we can make it even and we can make it even by just subtracting it by 1. so we can by just subtracting it by 1. so we can add add all of those numbers to our results all of those numbers to our results so in this case all it's going to be so in this case all it's going to be it's going to be results it's going to be results plus equals i minus 1 since we're going plus equals i minus 1 since we're going to remove one of its numbers to remove one of its numbers one of its letters and what we're also one of its letters and what we're also going to do here going to do here since now since we've removed one of since now since we've removed one of them it's going to be them it's going to be remaining with one odd character so remaining with one odd character so we're going to we're going to add that to our odd list so odd we're add that to our odd list so odd we're going to increase its value by one going to increase its value by one and we're also going to do that one more and we're also going to do that one more time if our so if our value time if our so if our value is not is not greater than one and in is not is not greater than one and in that case we're going to that case we're going to increase the odd value by one again increase the odd value by one again and now finally for our last step and now finally for our last step so over here if our odd value is greater so over here if our odd value is greater than zero than zero right if it's greater than zero so that right if it's greater than zero so that means that we do have an odd value means that we do have an odd value remember that we can add one of the one remember that we can add one of the one of those values of those values in between right so we're going to add in between right so we're going to add that to our results the results plus that to our results the results plus equals one equals one and then we're going to end up with uh and then we're going to end up with uh returning our results so returning our results so return result so this should be our return result so this should be our answer so let's submit it and let's see answer so let's submit it and let's see what happens what happens okay submit okay sorry i called it i okay submit okay sorry i called it i over here this is supposed to be over here this is supposed to be character so for character character so for character this is character again this character this is character again this character okay okay here we go okay submit all right and as you can see our submission did get accepted and finally do let me know if you have a better solution to solve this and thanks a lot for watching guys and don't forget to like and subscribe if this video helped you thank you | 2024-03-15 16:46:14 | 409 | Longest Palindrome | Leet code 409 | Theory explained + Python code |
|
gZ8veQvEaYU | today we will try to solve lead code easy problem 1920 so we'll try to build easy problem 1920 so we'll try to build array from permutation so let's see how array from permutation so let's see how is this problem okay so i'll try to do i will try to challenge this problem in javascript because that's my programming language which i like to code in so what we have to do so we have got here basically is the input which is 0 to 1 5 3 for its array of numbers and the output is this so they already say uh how this output we get it so what they're trying to do basically for each index so basically for num of zero you have to take again a index of that number so basically num of zero is zero right so then you again take an index of this zero so what's on the zero it's zero so you print zero here then you go on the num of two of two so when you do that num of two here what's number of two here so zero one two right so it's one so you print one so on you go with num of one then you again take one so that would be this so you print it like this and when you take number five and you again take the fifth element of this array which will be zero one two three four five which will be four so we'll print four here so that's how the array we get the output so how we'll gonna how we're gonna tackle this so we're gonna write our input and we're gonna write our output it's just gonna comment this and then now i'll make one more comment that how i'll tackle this so basically i'll have to run a for loop so run a for loop nums nums array array right and right and so that i can iterate over the all so that i can iterate over the all elements so elements so i'll try to teach all of you guys from i'll try to teach all of you guys from basics here right so basically for each basics here right so basically for each i i i is basically all i is basically all element inside that array we will be element inside that array we will be putting putting we will be we will be putting the new with putting the new value we'll get and replace it with i the new value replace it with i right replace it with i right and we'll just return and we'll just return the output array or the error which you the output array or the error which you get in the beginning right okay so that's how i try to solve the problem so i just try to write it down before and then try to solve it so see how we're going to tackle it so what we want we want a fresh output error right so we'll create output array which is which will be empty so then what can we do so i'll create a for loop so i try to use classic for loop so for i equals zero i should be less than numps you want to look through nums right so nums.length we don't want to go over it i plus plus easy uh now so now what do i want is i want to go to that output array each index of it and i want to replace it with nums nums is what the array which we've got and what do i want i want the letter what letter i want to put that output at i is nums of i but then i want to put the letter then the integer which is on there so this one if you see and when i do this i don't need to do anything else that's it i can return the output so i'll return the output right so how it's working basically let me explain you from here when let's say i zero right so i zero so output at zero would be nums at num set 0 so num set 0 num set 0 is 0 and then they ask okay what's at 0th index 0th index is 0 so we'll get 0 then when it goes to let's say when i is was the output.length one two three four five six so let's say the fifth element when i will be five right so when i will be five it will say okay num set num set five so num set five will be this thing fourth right and they say okay what's at the fourth element the fourth index so fourth index is zero one two three four three so then we got three at the end if you get what i'm trying to say then if you try to return the output and if see we got the answer because run 1067 see we got the answer because run 1067 and you can submit the solution as well and you can submit the solution as well so so it should work yeah it passed all the it should work yeah it passed all the use case test cases so our solution was use case test cases so our solution was faster than 33 percent and only 46 mb faster than 33 percent and only 46 mb less than 26 percent solution so it was less than 26 percent solution so it was a good solution a good solution thank you so much come back on my thank you so much come back on my channel for easy solutions like this | 2024-03-25 13:07:30 | 1,920 | LEETCODE SOLUTION 1920 | Build Array from Permutation| Leetcode for BEGINNERS | EASY | Javascript |
|
Qg7Zc4YIuE0 | hello there so today's li coding challenge question is implementation of challenge question is implementation of tri prefix tree yeah that's finish the tri prefix tree yeah that's finish the question we have to support three question we have to support three operations insert which is memorize a operations insert which is memorize a word search is to find we do we have the word search is to find we do we have the word thirdly is the star Swit it's a do word thirdly is the star Swit it's a do we have a partial March for the searched we have a partial March for the searched word so that's pretty much these three word so that's pretty much these three method that try data structure should method that try data structure should support and and if you don't know try support and and if you don't know try it's basically a em wait trees so can it's basically a em wait trees so can contrast it to binary tree only have two contrast it to binary tree only have two children's in Tri can have n different children's in Tri can have n different arbitrary number of children's so if you arbitrary number of children's so if you look at the string API ohyeah you can look at the string API ohyeah you can think that they're gonna be rude to know think that they're gonna be rude to know the points that has a child with a the points that has a child with a character with a key value of character character with a key value of character a and that node will have a bunch of a and that node will have a bunch of child and one of the child there is child and one of the child there is going to be the character P and you were going to be the character P and you were just you know you imagine there is this just you know you imagine there is this tree kind of structure from the root tree kind of structure from the root towards the leaf it's gonna be towards the leaf it's gonna be representing a path that reads like a PP representing a path that reads like a PP le so I just draw this some kind of a le so I just draw this some kind of a like a picture they're gonna have if we like a picture they're gonna have if we insert Apple in here so it will be a the insert Apple in here so it will be a the P Elle and finally II before you insert another word which is maybe something like a dog so it will be a child to the road with this which is carp to D and it will also be a reference to contain a pointer to the child node o and G so so basically when we insert a word into this tri data structure we are populating a route to leave past if it's if the node are not there otherwise we're just traversal through this tree and you know creating nodes as necessary there is something that we need to indicate we need to indicate at the end of the world so for each node here beyond the reference to the next node there actually also have a termination flag to indicate that this is the end of word so you can imagine with a bunch of Fortran fours for every node here that's just indicating the way have a word at the ends here so to search for word we basically just traversal through this tri data structure character bar character from using the search term search word and once we reach the end we want to check do we have a flag in there so if we insert Apple and dog and search for a P P this P here will have F flag which is false so there is no such word in there if we insert a P P will be you know traversal through this tree and turn this flag to be true and if we do the starts with search partial marching it's also the traversal through the tree as long as we don't find a dead end somewhere in the middle of the search traversal then we can return true otherwise it will be false so that's how we support starts with so by using this data structure the insert search and starts with they all be the time complexity are all linear with respect to the number of characters in the tree in the word so it's basically rude to leave in the worst time was case and for space search and starts with they don't create anything so it's gonna be constant but the insert it's gonna be in the worst case every character we have to create a you know allocate some memories for that so it's gonna be linear respect respect to the the lens of the word so that's the worst space requirements for insert and and yeah that's pretty much the quick explanation about what is try and how it works so I'm just gonna start and code this up so the try structure is as a is holding this whole thing together but for each individual node in there it's a it's a smaller data structure I'm just gonna have a separate one to make it a bit cleaner fundamentally this tri node here who holds two things one is the boolean flag indicating whether this is a end of award the other thing is this parent or child kind of relationship and and you will be able to access the child by the character so you could it gonna be it would be a key value mapping with the key be the character and the value be the pointer to the actual child node object and you could use use eraser as well because we are dealing with a fixed letters A to Z but but in the case that if you have caronian vocabulary how this to be fixed that might not be a good idea so I'm gonna use a hash map for this purpose so we have two data items here where the first thing is the boolean flag and the second thing is the map that's called a child children then that's called a child children then we're going to have some popular message we're going to have some popular message for accessing this okay first thing for accessing this okay first thing first this constructor which just set a first this constructor which just set a flag to be false and the children to the flag to be false and the children to the empty then we need the setters to turn empty then we need the setters to turn the FAC flag to be true when we reach the FAC flag to be true when we reach the end of the word and we also need to the end of the word and we also need to be able to access the flux value so we be able to access the flux value so we have a getter and setter for the flag so have a getter and setter for the flag so this will just be returning the return this will just be returning the return the flag value setters of void just are just indicating this is the end of word therefore the children we need we need a setter to create a new character to node mapping and we also need a membership checking do we have a do we have a character a node with associated with this character so that if it's not there we can do the insert if it's in there we can just Traverse us through that node so we need not not us not a getter but a membership checking let's call contains which takes a it character and you just you just check whether we have a character in the children so it's a children see greater lastly is the Center for the children which takes a character and the actual [Music] [Music] create this association genes and that's create this association genes and that's pretty much the final class pretty much the final class fundamentally it has the flag and the fundamentally it has the flag and the child to parent to child relationship child to parent to child relationship where each child is identified by the where each child is identified by the character and that's the try note and character and that's the try note and let's work on the Twilight instructor so let's work on the Twilight instructor so for we're gonna have a root note here for we're gonna have a root note here which is going to be initialized to be a which is going to be initialized to be a empty try note in the beginning so it's empty try note in the beginning so it's it's going to be a pointer to try note it's going to be a pointer to try note in the constructor would basically set in the constructor would basically set this to be a new try Note 4 insert we this to be a new try Note 4 insert we have to process the word character part have to process the word character part captor so we're gonna have a for loop captor so we're gonna have a for loop [Music] for each character we're gonna check do we can tell do we have that if we have that we don't create create a new note if the if we don't have that note character yet like like the first a if we if there's a fresh fresh try we only have a root when we see the first record a we're gonna actually create that try node and establish the parent to try out the relationship so if it's if it's not in there then we should do this which is so we should we can grab a reference to if we don't have the key then we're if we don't have the key then we're gonna use the set child copy please to gonna use the set child copy please to be the character C and a new note so be the character C and a new note so that's if we don't have the note that's if we don't have the note otherwise we'll just follow that note otherwise we'll just follow that note and process forward which is going to be and process forward which is going to be known equal to oh we need a getter I'm sorry we need a getter - - traversal inside this inside this tree so good child takes a key and we should return the child does it look look right yeah it takes a key and return the children with that key so so that's the insertion once we process that once we are done with this full loop we should flag the very last node to be true so it's a despite it's done by calling the set fly so that's insertion search is pretty much a the only thing difference is that if we the only thing difference is that if we if we don't have that character we if we don't have that character we return false otherwise we shall keep return false otherwise we shall keep traversals through the Twilight data traversals through the Twilight data structure and in the end we should structure and in the end we should return whether that no determination return whether that no determination node has a flat and starts with a say node has a flat and starts with a say it's also very similar to this so we're it's also very similar to this so we're working with some prefix rather than working with some prefix rather than word now if we just don't have that word now if we just don't have that character we should return false character we should return false otherwise we should keep traversal going otherwise we should keep traversal going down into the towards the leaves and if down into the towards the leaves and if we don't return false in the middle of we don't return false in the middle of the search values we can successfully the search values we can successfully you know process all the character in you know process all the character in this prefix so in the end we should this prefix so in the end we should return true so that's pretty much the return true so that's pretty much the logic the three parts are really really logic the three parts are really really similar it's a it all starts with this similar it's a it all starts with this route and just going down the path route and just going down the path towards the leaves in in the insertion towards the leaves in in the insertion or check if the note is nothing there it or check if the note is nothing there it will actually create the node and will actually create the node and establish the parent to child establish the parent to child mapping otherwise you would just in the mapping otherwise you would just in the case of search and starts with it just case of search and starts with it just traversal through the tree the only traversal through the tree the only difference between search and the starts difference between search and the starts with is search for search you want to with is search for search you want to grab the flag for the realistic grab the flag for the realistic character associated with the node of character associated with the node of the realistic character before starts the realistic character before starts with as long as we don't terminate early with as long as we don't terminate early we should return true so that's the only we should return true so that's the only difference between search and starts difference between search and starts with with so let's quickly check do I have some so let's quickly check do I have some stupid mistakes it looks looks okay yeah so let me try to run through some examples No Carol uh I sure no not this one this one it's a boolean but I'm not returning the returning listed this condition checking okay let's submit all right so that's okay let's submit all right so that's the implementation of try yeah that's the implementation of try yeah that's pretty much the question they're just pretty much the question they're just very happy that I can cut this thing up very happy that I can cut this thing up easily now compared to two years ago I easily now compared to two years ago I don't even know this thing existed yeah don't even know this thing existed yeah so that's all | 2024-03-22 10:04:06 | 208 | Leetcode 208 Implement Trie (Prefix Tree) |
|
HoH9BdYBYIg | hi everyone welcome back for another video welcome back for another video we are going to do another decode we are going to do another decode question question the question is the question is h h index given a array of integers citations where citations i is the number of citations a researcher received for their i've paper return compute the researchers age index according to the definition of age index on wikipedia a scientist has an index age if age of layer and papers have at least age citations each and the other n minus age papers have no more than age citations each if there are several possible values for age the maximum one is taken as let's let's walk for the code walk for the code we first sort the array citations we first sort the array citations in ascending order in ascending order we land it away fully away if a array element at index i is greater than the citations the length minus i then other elements to right of index i must also satisfy the condition since they are greater than the element at index i return citations the length minus i if there is no element that satisfies the condition thanks for watching thanks for watching if this video is helpful if this video is helpful please like and subscribe to the channel please like and subscribe to the channel thank you very much for your support | 2024-03-22 12:32:47 | 274 | H-Index - LeetCode 274 - Java Solution |
|
5Pvm0rEMYJw | hi all welcome to learn code repeat so today we will be looking at day 4 of so today we will be looking at day 4 of the october lead code challenge the october lead code challenge the name of the problem is remove the name of the problem is remove covered intervals let's look into the covered intervals let's look into the problem problem so the problem says given a list of so the problem says given a list of intervals remove all intervals that are intervals remove all intervals that are covered by another interval in the list covered by another interval in the list interval a comma b is covered by interval a comma b is covered by interval c comma d if and only if interval c comma d if and only if c is less than equal to a and b is less c is less than equal to a and b is less than equal to d than equal to d after doing so written the number of after doing so written the number of remaining intervals remaining intervals so basically the question asks is if so basically the question asks is if there is an overlapping interval there is an overlapping interval then all the sub intervals inside that then all the sub intervals inside that needs to be needs to be not considered and only the main not considered and only the main overlapping that is the superset overlapping that is the superset interval needs to be considered interval needs to be considered and give the count of that so let us and give the count of that so let us look into the first example here look into the first example here we have 1 4 3 6 and 2 8. so let us plot we have 1 4 3 6 and 2 8. so let us plot this example this example so 1 4 will be like this so 1 4 will be like this this is the interval 3 6 is this is the interval 3 6 is from here to here and 2 8 from here to here and 2 8 is from here till here is from here till here right now if you see what the condition right now if you see what the condition it says is it says is the interval that is covered by a super the interval that is covered by a super interval right interval right so this is a super interval which covers so this is a super interval which covers this particular interval right this particular interval right so this should not be considered and so this should not be considered and then return the count of then return the count of whatever intervals are not covered right whatever intervals are not covered right so so this will be one this will be two so the this will be one this will be two so the output is expected to be two output is expected to be two right now if you see this once you plot right now if you see this once you plot it it looks like very simple to identify it it looks like very simple to identify the intervals that are not covered right the intervals that are not covered right the condition here was a comma b the condition here was a comma b c comma d and a is less than or equal to c comma d and a is less than or equal to c and b is less than equal to d c and b is less than equal to d right so if it is a comma b right so if it is a comma b and c comma d then c should be less than and c comma d then c should be less than or equal to or equal to a and b a and b should be less than or equal to d what should be less than or equal to d what this means is this means is this is my a and this is my b this is my a and this is my b right and this is my c and this is my d right and this is my c and this is my d so here so here c if you see c is 2 c if you see c is 2 and a is 3 so c should be less than and a is 3 so c should be less than equal to equal to a that is what is given here d is a that is what is given here d is greater than or equal to b greater than or equal to b or in other words b is less than equal or in other words b is less than equal to d right that is what is given here to d right that is what is given here so if this is a condition that means the so if this is a condition that means the c d is overlapping a b c d is overlapping a b right in that case we should not right in that case we should not consider a b ok consider a b ok so the reason once you plot it you are so the reason once you plot it you are able to identify able to identify is because you see this you visualize is because you see this you visualize this as a this as a sorted interval right so that is what we sorted interval right so that is what we can do here we can directly sort this can do here we can directly sort this array because array because this is unordered array we can sort this this is unordered array we can sort this interval array interval array and once you sort this you can see that and once you sort this you can see that based on this condition you can identify based on this condition you can identify if the interval is overlapping that if the interval is overlapping that means if this condition is satisfied means if this condition is satisfied that means the interval is overlap so that means the interval is overlap so when i sort this right when i sort this right this superset will come first and then this superset will come first and then this will be coming right in in this this will be coming right in in this case at least in this case right case at least in this case right so if this is my current i position so if this is my current i position right or right or let us say this is my previous interval let us say this is my previous interval which is i position and this is my which is i position and this is my current interval which is j position current interval which is j position right so i just need to check whether right so i just need to check whether interval of my interval of my previous position which was i of 0 previous position which was i of 0 is less than or equal to i am using the is less than or equal to i am using the same condition a same condition a a is my current intervals position right a is my current intervals position right j comma 0 okay if this is the condition j comma 0 okay if this is the condition and here it will be b right b and here it will be b right b is this this is j so that is my current interval of sorry here it will be one interval of sorry here it will be one current one is less than or equal to current one is less than or equal to interval of interval of i one right so in that case if this is i one right so in that case if this is less than this less than this if that condition is satisfied then my if that condition is satisfied then my current current interval needs to be removed from the interval needs to be removed from the total length right total length right so let us say if i am having a count so let us say if i am having a count variable which is 0 right variable which is 0 right i can simply increment that count right i can simply increment that count right but if that is not the case right then but if that is not the case right then my overlapping right should be my overlapping right should be considered as my current so my previous considered as my current so my previous right previous right previous j or either previous i should be equal j or either previous i should be equal to to j i is my previous index right so i j i is my previous index right so i should point to j should point to j and that we can do it in the for loop and that we can do it in the for loop once we have the sorted array once we have the sorted array so this is a very simple algorithm that so this is a very simple algorithm that we can use we can use however there is a catch here the way we however there is a catch here the way we sorted is important sorted is important because we not only need to sort it by because we not only need to sort it by the starting index but we also need to the starting index but we also need to consider the ending index consider the ending index let us take another example so here i let us take another example so here i have plotted the graph have plotted the graph i will come to this part later on i will come to this part later on so here i have plotted the graph and if so here i have plotted the graph and if i see i see this particular interval this particular interval is overlapping this so i have crossed is overlapping this so i have crossed out this similarly this interval is out this similarly this interval is overlapping this one i have crossed out overlapping this one i have crossed out this and this interval is this and this interval is also overlapping this so i have crossed also overlapping this so i have crossed out this one as well so at the end we out this one as well so at the end we have only two have only two largest intervals so that is why the largest intervals so that is why the output is two output is two so here if i only sort by the starting so here if i only sort by the starting index right index right so if you see this can come first so if you see this can come first or this can also come first in the array or this can also come first in the array right if i sort the array only by start right if i sort the array only by start index and if that is the case index and if that is the case then a condition of c is less than or then a condition of c is less than or equal to a and equal to a and b is less than equal to d right to b is less than equal to d right to satisfy this condition we have to satisfy this condition we have to identify identify which of the interval is c right which which of the interval is c right which is a b and which is c is a b and which is c d it can be that this is a b and this is d it can be that this is a b and this is c d c d or it can be the other way as well right or it can be the other way as well right so to check that we have to also check so to check that we have to also check which one is having the largest n index which one is having the largest n index right which is the maximum right which is the maximum n index in that case and we have to take n index in that case and we have to take that as the c d that as the c d ok so to keep a track of that right we ok so to keep a track of that right we have to have to create one more variable to keep a track create one more variable to keep a track of which one is the largest index and so of which one is the largest index and so point that variable to that particular point that variable to that particular largest index so to remove all this largest index so to remove all this complexity while sorting we can very complexity while sorting we can very well sort by start index and end index well sort by start index and end index right right so what will happen in that case right so what will happen in that case right so when i sort with the so when i sort with the start index and an index i will sort by start index and an index i will sort by start index in start index in ascending order and by n index in ascending order and by n index in descending order descending order so my output will be something like this so my output will be something like this right so 1 7 will be first because right so 1 7 will be first because 1 and 1 is same but 7 is greater than 4 1 and 1 is same but 7 is greater than 4 because we are sorting the n index in because we are sorting the n index in descending order this will come first descending order this will come first right right so let me write down the index value so let me write down the index value here so this will be 0 here so this will be 0 this will be 1 this will be 2 this will this will be 1 this will be 2 this will be 3 and this will be 4 right be 3 and this will be 4 right so here i am making sure that the so here i am making sure that the largest overlapping largest overlapping interval will come first before its sub interval will come first before its sub intervals intervals which the largest may be overlapping which the largest may be overlapping with that right so once i have that with that right so once i have that order in place right i can very well order in place right i can very well say that my current interval if it is say that my current interval if it is largest that is a c largest that is a c and d value right so i can start with and d value right so i can start with saying that saying that i equal to 0 i is my largest overlapping i equal to 0 i is my largest overlapping interval and j is my current interval and j is my current counter which is the next interval right counter which is the next interval right and i can have this j and i can have this j in a for loop j equal to one till j in a for loop j equal to one till j is less than my length of the interval is less than my length of the interval and j plus plus and j plus plus ok now i can in my ok now i can in my for loop i can just do the do this check for loop i can just do the do this check right right that they have provided so i is my that they have provided so i is my largest interval right so i largest interval right so i of 0 is less than or equal to j of 0 is less than or equal to j of 0 okay so i am checking first this of 0 okay so i am checking first this particular condition particular condition and into now b b is my j and into now b b is my j value j of first index is less than or value j of first index is less than or equal to equal to interval of i of first index ok interval of i of first index ok if this condition is satisfied right if this condition is satisfied right that means my i that means my i index interval is overlapping my j index index interval is overlapping my j index interval interval right so i am incrementing the counter right so i am incrementing the counter okay however if this condition is not okay however if this condition is not satisfied right satisfied right so that means my current j interval is so that means my current j interval is not getting overlap not getting overlap by the i interval right so when i go to by the i interval right so when i go to the next counter the next counter my j interval may be overlapping the j my j interval may be overlapping the j plus 1 interval plus 1 interval that may be the case right so in that that may be the case right so in that case i need to case i need to assign i as the j value so basically i assign i as the j value so basically i is keeping the track of which interval is keeping the track of which interval may be may be overlapping the next interval so this is overlapping the next interval so this is the simple logic here the simple logic here now let us code this algorithm so first now let us code this algorithm so first i will i will get the length of the array now if my get the length of the array now if my interval is interval is zero length or even if its of size one zero length or even if its of size one right i can right i can directly return the output as the length directly return the output as the length value right value right so i will add that check here so i am so i will add that check here so i am assigning my i assigning my i index as 0 and my j will start with 1 index as 0 and my j will start with 1 i will also assign a variable counter to i will also assign a variable counter to count the total number of intervals that count the total number of intervals that are getting overlapped are getting overlapped so initially it will be 0 now the if condition will be there if this is a case then i need to increment my counter else my i will be equal to my g ok this will be my condition inside my for loop and before this i need to also sort my array so here i will do a arrays dot and the comparator will be my other 0th index in that case so if my my other 0th index in that case so if my a of 0 is not equal to b of 0 a of 0 is not equal to b of 0 that means my start index are not equal that means my start index are not equal then i can directly do a ascending order else i need to do descending order for else i need to do descending order for my end index my end index if my start index are same right so this is my comparator for the sorting order and once i have the counter incremented that means i am counting all the intervals that are getting overlapped by some other interval right so once i know that right i can very well return my length minus the count so this is the remaining value right so let us submit and the code is accepted so the and the code is accepted so the complexity of this algorithm will be complexity of this algorithm will be o of n log n the reason why it is of n o of n log n the reason why it is of n log n is because we are doing a sort log n is because we are doing a sort here here so sorting takes o of n log n and after so sorting takes o of n log n and after that we are going through the intervals that we are going through the intervals again again which will be o of n so it will be o of which will be o of n so it will be o of n log n plus n log n plus n which is same as of n log n n which is same as of n log n so the time complexity is o of n log n so the time complexity is o of n log n and since we are not using any and since we are not using any additional space so the space complexity additional space so the space complexity is o of one is o of one hope you like this video if you have any hope you like this video if you have any question please do write into the question please do write into the comment section comment section and if you haven't subscribed to the and if you haven't subscribed to the channel please do subscribe to the channel please do subscribe to the channel channel thank you | 2024-03-20 10:38:21 | 1,288 | Remove Covered Intervals | LeetCode 1288 | October LeetCode Challenge | Day 4 |
|
xqyTaBE6SSI | said today let's see this rotate an image romantics problem so it's a medium image romantics problem so it's a medium problem let's quickly jump into the problem let's quickly jump into the description so you're given an n into n description so you're given an n into n 2d matrix representing an image and we 2d matrix representing an image and we are asked to rotate the image by 90 are asked to rotate the image by 90 degrees clockwise okay and they're degrees clockwise okay and they're saying that you should have take the saying that you should have take the image in place which means we should not image in place which means we should not use extra memory you should use the same use extra memory you should use the same matrix and given this input matrix 1 2 3 matrix and given this input matrix 1 2 3 4 5 6 7 8 9 you have to rotate this 4 5 6 7 8 9 you have to rotate this matrix in clockwise also you should matrix in clockwise also you should rotate the matrix in place so how do you rotate the matrix in place so how do you rotate this matrix let's say you have a rotate this matrix let's say you have a point you're at 7 you have a reference point you're at 7 you have a reference point it's 7 let's pull this and rotate point it's 7 let's pull this and rotate this matrix so when you rotate it you'll this matrix so when you rotate it you'll get 7 on the top and 4 will come next to get 7 on the top and 4 will come next to it and then one will come next to it it and then one will come next to it right now whatever it is next to 7 will right now whatever it is next to 7 will come again at the top it in beneath 7 come again at the top it in beneath 7 and you will have 8 by 2 and then and you will have 8 by 2 and then beneath 8 fight you will have 9 6 3 so beneath 8 fight you will have 9 6 3 so that is how this rotated matrix is got that is how this rotated matrix is got so if you have we no trouble so if you have we no trouble understanding this maybe you can write understanding this maybe you can write all these numbers in a paper and then all these numbers in a paper and then try to treating the paper and you look try to treating the paper and you look so that seven you come to the top and so that seven you come to the top and four will come next to it and then one four will come next to it and then one will come next to it in other words you will come next to it in other words you can you know have a reference point at 7 can you know have a reference point at 7 and try imagining that you know you're and try imagining that you know you're pulling to rotate it clockwise so if you pulling to rotate it clockwise so if you pull this up right 7 well if you pull pull this up right 7 well if you pull this up so I'm come to the top and 4 this up so I'm come to the top and 4 will come next to it and one will come will come next to it and one will come next to it and whatever is beneath 8 next to it and whatever is beneath 8 right since you're pulling 7 to the top right since you're pulling 7 to the top it will also come to the turbit then it will also come to the turbit then since 7 is at the top it will be beneath since 7 is at the top it will be beneath it right so since we are rotating this it right so since we are rotating this in place right why the approach that you in place right why the approach that you going to employ is vivianne to transpose going to employ is vivianne to transpose the matrix so what is transpose of a the matrix so what is transpose of a matrix a transpose of a matrix is matrix a transpose of a matrix is nothing but you know you transform the nothing but you know you transform the rows into columns and columns into rows rows into columns and columns into rows so 1 2 3 is a row here in the input so 1 2 3 is a row here in the input matrix a 1 it will become a column and matrix a 1 it will become a column and the transverse matrix right and the transverse matrix right and two four five six as a row and then two four five six as a row and then it'll be gonna call him so four five six it'll be gonna call him so four five six and or three six seven eight nine is a and or three six seven eight nine is a row and it with McCallum and the row and it with McCallum and the transpose matrix and now if you observe transpose matrix and now if you observe the transverse matrix and the output the transverse matrix and the output matrix right you see that four five six matrix right you see that four five six the middle column is same and one two the middle column is same and one two three is the first column and this three is the first column and this intermediate matrix the transpose matrix intermediate matrix the transpose matrix and it is the last column the expected and it is the last column the expected matrix which is rotated matrix and seven matrix which is rotated matrix and seven eight nine is the last column and the eight nine is the last column and the transpose matrix whereas it is the first transpose matrix whereas it is the first column and rotated matrix so once you column and rotated matrix so once you get the transpose matrix what you have get the transpose matrix what you have to do is you have to just swap the first to do is you have to just swap the first and the last column so basically we're and the last column so basically we're going to employ you know the reverse going to employ you know the reverse approach here they're just going to have approach here they're just going to have a pointer pointing to this column and a pointer pointing to this column and then we're good to have another point of then we're good to have another point of entry to this last column and basically entry to this last column and basically we're going to just now swap these we're going to just now swap these values and if you observe right all test values and if you observe right all test input matrix and the transpose matrix input matrix and the transpose matrix one let's start I is equal to zero and I one let's start I is equal to zero and I will be less than the number of rows will be less than the number of rows which is two and say J is equal to zero which is two and say J is equal to zero and J is less than two and then three it and J is less than two and then three it is actually three sorry is actually three sorry so zero zero so initially I is zero and so zero zero so initially I is zero and J is 0 right 0 0 remains the same and if J is 0 right 0 0 remains the same and if you consider this as 0 1 0 1 is 2 0 1 you consider this as 0 1 0 1 is 2 0 1 will come to 0 1 will go to 1 0 right will come to 0 1 will go to 1 0 right let's come to 1 0 so if you see in 0 0 let's come to 1 0 so if you see in 0 0 it remains a sub 0 0 and then 0 1 come it remains a sub 0 0 and then 0 1 come to 1 0 and then 0 2 will go to 2 0 right to 1 0 and then 0 2 will go to 2 0 right so which means that the first iteration so which means that the first iteration itself we have transformed the first itself we have transformed the first column right one has come to one and two column right one has come to one and two which was here which was here let's come to here and three which was let's come to here and three which was here has come here right so in the next here has come here right so in the next iteration you should not start from J is iteration you should not start from J is equal to zero should actually start from equal to zero should actually start from T is equal to your row reverse I because T is equal to your row reverse I because if you start J is equal to 0 then we if you start J is equal to 0 then we will be potentially overriding it so will be potentially overriding it so next I Tricia you will actually start next I Tricia you will actually start with 1 and 0 right and 1 and 0 will be with 1 and 0 right and 1 and 0 will be replaced with 0 1 so 1 & 0 is now 1 0 is replaced with 0 1 so 1 & 0 is now 1 0 is what - and now when you replace it with what - and now when you replace it with 0 1 you're just making it the same 0 1 you're just making it the same matrix a and so we should not override matrix a and so we should not override the same matrix again so we should the same matrix again so we should actually start the second do the J is actually start the second do the J is equal to high let's transform the matrix equal to high let's transform the matrix and come back to the next step okay so and come back to the next step okay so let's transfer the right race into a let's transfer the right race into a transpose but simply say I'm going to transpose but simply say I'm going to have n rows equal to matrix dot the end have n rows equal to matrix dot the end and end and calls is equal to matrix of and end and calls is equal to matrix of 0 dot length so we are going to do a 0 dot length so we are going to do a transpose and true is equal to 0 Rho is transpose and true is equal to 0 Rho is less than number of rows and rows and 4 less than number of rows and rows and 4 and column is going to be row because and column is going to be row because when when you complete the first row at when when you complete the first row at iteration you have already completed the iteration you have already completed the first row column basically saying that first row column basically saying that you know when you complete the first row you know when you complete the first row you're ensuring that the first column you're ensuring that the first column elements are also in place they should elements are also in place they should start column is equal to column is less start column is equal to column is less than or false and contrast bus than or false and contrast bus so you have this will be doing a swap so you have this will be doing a swap mechanism you're saying row and then I mechanism you're saying row and then I think all okay I'm just going to copy think all okay I'm just going to copy this to just save time this row become this to just save time this row become parliament column will become Rho and parliament column will become Rho and transpose matrix is saying to this and transpose matrix is saying to this and it will become hard 10 okay so now we've it will become hard 10 okay so now we've got the transpose matrix right so we are got the transpose matrix right so we are here now if you see the first episode of here now if you see the first episode of your transpose matrix and the output your transpose matrix and the output rotated matrix we see that the first row rotated matrix we see that the first row has become the last column so basically has become the last column so basically what has happened is 0 0 has become 0 2 what has happened is 0 0 has become 0 2 and 0 1 and 1 0 this has become so 1 0 and 0 1 and 1 0 this has become so 1 0 is what - and very so 1 0 is what - is what - and very so 1 0 is what - right 1 0 is 2 and where is 2 here in right 1 0 is 2 and where is 2 here in the rotated matrix it is at 1 2 ok so the rotated matrix it is at 1 2 ok so basically if observe this pattern row is basically if observe this pattern row is saying because role is going to be the saying because role is going to be the same right the column is only different same right the column is only different so how do we get this column right 0 has so how do we get this column right 0 has become 2 and 0 has become - let's take become 2 and 0 has become - let's take another an example let's consider 3 another an example let's consider 3 element 3 element 3 is all let's element 3 element 3 is all let's consider that element 9 the element 9 is consider that element 9 the element 9 is at 2 comma 2 and where is that where is at 2 comma 2 and where is that where is that - the rotation matrix it is at 2 that - the rotation matrix it is at 2 comma 0 right so which means called row comma 0 right so which means called row is same column is different is same column is different so when basically how do you get this is so when basically how do you get this is number of columns which is 3 here - a number of columns which is 3 here - a current column minus 1 will be current column minus 1 will be this planet because here at current this planet because here at current columnist to number of columns is 3 so 3 columnist to number of columns is 3 so 3 minus 2 minus 1 isn't going to be 0 and minus 2 minus 1 isn't going to be 0 and same thing applies here the current same thing applies here the current column is 0 number of row columns is 3 column is 0 number of row columns is 3 so 3 minus 0 is 3 minus 1 which is 2 so so 3 minus 0 is 3 minus 1 which is 2 so the part with column is 2 and if you see the part with column is 2 and if you see in any reversal approach you have a in any reversal approach you have a pointer pointing to this and you have a pointer pointing to this and you have a pointer pointer to the last one 1 0 swap pointer pointer to the last one 1 0 swap these to the middle element will be these to the middle element will be already in place right and even and already in place right and even and stringer parish and interesting stringer parish and interesting reversion example also you see that the reversion example also you see that the first and the last will be swapped and first and the last will be swapped and by the time you reach the middle they by the time you reach the middle they will be already in place so we are just will be already in place so we are just going to I treat over columns and going to I treat over columns and columns by 2 because the middle column columns by 2 because the middle column will already be in place when we have will already be in place when we have required values so let's transform this required values so let's transform this transpose matrix into the expected transpose matrix into the expected rotated matrix and rose and o + + + 4 in rotated matrix and rose and o + + + 4 in column equal to 0 and call it's less column equal to 0 and call it's less than and calls all plus plus so again employ the swap approach you're going to have a temporary variable and just trying to say we may have copied this so this is going to be it tricks and so we saw that matrix o Row is going to be the same there is this is going to be n falls - 4 - 1 so let's put that value in the target was going to be the so let's run this code and as I said by so let's run this code and as I said by the time they reach the middle it will the time they reach the middle it will be able to identify be able to identify so we need no Intel they shall get the so we need no Intel they shall get the transpose matrix and then transform the transpose matrix and then transform the transpose matrix into the rotated matrix Andros this should end Rose this we have got that it is accepted submit this it takes so much of time okay so if you see it 18 minutes ago I submitted it it was due dry mess and now it is wanna miss I have no idea it was the same approach so there is something wrong with a lead code time calculation algorithm because the same approach you know it's 18 minutes back it was saying zero I miss consistently so say yeah that's it nice so this is the answer so basically when you rotate a matrix we're just going to do it transpose of the matrix and then you have to just transform the transpose matrix into a vegetable matrix by just reversing first in the last columns thanks guys I hope you'll like this | 2024-03-20 09:48:35 | 48 | RotateMatrixVideo - Solution to LeetCode 48 - Rotate Image |
|
PzKkjix7Mhk | hello everyone this is mustafa from the code show again with another lead code code show again with another lead code problem problem this one is a very popular dynamic this one is a very popular dynamic programming problem programming problem this name is it is a distance this name is it is a distance the problem statement is that we have the problem statement is that we have like two strings world one like two strings world one and world two and we need to find the and world two and we need to find the minimum number of operation minimum number of operation to convert world 1 to war 2 and we have to convert world 1 to war 2 and we have like like three operations only we can do on three operations only we can do on the world one to convert it to war two the world one to convert it to war two these operations these operations are insert character and delete are insert character and delete character and a replace character uh character and a replace character uh here we have like horse here we have like horse and we have rows and we have like uh and we have rows and we have like uh the minimum number of operations to the minimum number of operations to convert was into convert was into ros is only three operations ros is only three operations okay so we first thing we will replace h okay so we first thing we will replace h with with r others that we will remove the r from r others that we will remove the r from horse horse and then we remove the e from ours okay and then we remove the e from ours okay so so let's try to uh take a closer look so so let's try to uh take a closer look on this example on this example and let's assume we have like two and let's assume we have like two pointers first pointer on pointers first pointer on the first word another pointer also the first word another pointer also on the first character of the second on the first character of the second word so here you have like word so here you have like simple example uh we have our pointers simple example uh we have our pointers this one this one this one position one and position two this one position one and position two we have like the operation we already we have like the operation we already did and the first thing we would like did and the first thing we would like replace h with r and we have like replace h with r and we have like r o and our our r o and our our the first pointer now is pointing on o the first pointer now is pointing on o second pointer second pointer is pointing in o also so we don't need is pointing in o also so we don't need to to um to do any operation because the um to do any operation because the two characters are the same so we will two characters are the same so we will only increment only increment the the position one and position two the the position one and position two so we have like uh here here we have so we have like uh here here we have like r like r and we have also here s okay so we will and we have also here s okay so we will delete this r delete this r and increment the pointer here that and increment the pointer here that point point points to s right now after that points to s right now after that we have like 2s here here um we have like 2s here here um we don't need to do anything we will we don't need to do anything we will just increment the just increment the host pointers if we can so here we host pointers if we can so here we incremented this and we have like incremented this and we have like e and s so we will delete the e also and e and s so we will delete the e also and we have like three operations because we we have like three operations because we did did delete we did a decision here also delete we did a decision here also another deletion another deletion and we did replacement here to replace and we did replacement here to replace arms arms uh to replace h1 and that's it how we uh to replace h1 and that's it how we can can code these steps into an algorithm so here as we usually do we as usually do with the dynamic programming problems we do a backtracking we can start to solve uh create a solve function that would be our backtracking function or our recursive function so let's try with it so okay it will take two argument position number one and position position number two okay and [Music] let's try now think about our base case when we will stop doing this location over and over again i would say we need to stop if any of this of those pointers uh become uh like hit the end of its port like here we hit the end of the second word and here we have this at the end of the first one so whenever we if we have any of this position reached the end of its world that will be like um a base case or we need to stop doing the recursion so here let's try to do in this case position one is larger or equal and another base case if position two and another base case if position two this merger world this merger world 2 and 2 and yeah so if you repeat against example we yeah so if you repeat against example we had we had we had two s's here yeah and at the end we need to make that two strings equal so we need we need to delete the remaining part of the first word actually and each character will represent attribute operation so our base case would be the following if we reach it the end of the first word we will return the difference between the second word and its current position and the the same also for the second one okay so here we need to do something like this to to minus its current position minus its current position and we need to do same thing here and we need to do same thing here then word one minus its composition and that should be it uh now let's try to think about our recursive case so um we have like two recursive cases as we see here an example first one if the characters are equal okay we will need only to increment if they are not equal we will need to try we need to try to do an operation on the string okay so so if word one of position one not equal or two of position 2. what we will need to do is we need to to solve or try to solve with the replace operation so how we can represent the brace operation is by incrementing the position the two positions of that walls okay so this is the position one and this is position two plus one and here we have uh the operation we did we need to increment the operation counters this one and also we need to try to solve with the insertion operation so the insertion yeah the insertion operation will be yeah the insertion operation will be represented as we need to represented as we need to only increment the first position only increment the first position okay and we need to try from the same okay and we need to try from the same position position on the second word and we also increment on the second word and we also increment the operation counter the operation counter the last operation is the delete the last operation is the delete operation and we will need to try to solve from the current position we are we are at in our first world and we need to increment the position 2 for the second word also we need to increment the operation counter and at the end we need to use mass to find them which uh which will return us the minimum operation we need to use we need to return here so this is the first point if the word if the if this character are not equal the character from the second word if this if statement is not correct we will need to solve only from the next position so position one plus one and position two plus two we need to return it and that's it we need to return so we need to fall from zero and zero so that that is that is the recursion part or the backtracking part so actually i think we can try it now yeah it works fine now we need to add the memorization part let's try to make a 2d array that would cache the two parameters here so here we have like a be quite new array and the be quite new array and the reliance would be like word one reliance would be like word one prince one and we need to fill this prince one and we need to fill this array with array with uh another areas uh with the length of uh another areas uh with the length of wall two wall two okay so uh let's do it okay so uh let's do it so we need to for loop we have like four so we need to for loop we have like four i counter equal 0 and i counter equal 0 and i is the then minimum now we need to fill every array every position sorry was -1 so we need to use this inside our back tracking part so first thing if the memo of the current position if the memo of the current position in position 2 also is not equal in position 2 also is not equal minus one we need to return its value okay so also here we need to write into the array and also we need to right here in the array yeah so we said the value will ethernet yeah so we said the value will ethernet we also set the value and we return it we also set the value and we return it here here and uh yeah if we found the value of it and uh yeah if we found the value of it we will return it we will return it so let's try to run this this is a strange word also another type it seems that we don't return at some it seems that we don't return at some point point yeah we have like a type of another type yeah we have like a type of another type of here of here yeah yeah there's a typo i think we yeah yeah there's a typo i think we forget to add forget to add i here work is fine thanks for watching thank work is fine thanks for watching thank you | 2024-03-20 11:30:48 | 72 | Leetcode 72. Edit Distance (Dynamic Programming) - javascript |
|
TE41nLQG4cM | Hello friends, welcome, this is youtube1 linker challenge, the challenge is going very well, let's go straight to our screen and start, so here I am on the screen, the And the And the And the name of the question is 'Maximum Ascending Sub Array'. name of the question is 'Maximum Ascending Sub Array'. Okay, 'Maximum Ascending Sub Array'. Now let's Okay, 'Maximum Ascending Sub Array'. Now let's understand a little bit what is a sub array. It has understand a little bit what is a sub array. It has also been written here that also been written here that what is 'Sub Array'? A sub array is defined as a what is 'Sub Array'? A sub array is defined as a continuous sequence of a number. continuous sequence of a number. continuous sequence of a number. any continuous part of the array, we call it a sub array. Now what we have to find is that if the question is defining the whole in its name, what is doing is that the maximum ascending sub, we What is the maximum? What is the maximum? What is the maximum? We have to find out the ascending sub-ascending We have to find out the ascending sub-ascending part of the array, like if I talk about this part of the array, like if I talk about this example, in the first example, 10 20 example, in the first example, 10 20 30 5 10 50, then in this, two of my counts, ascending ascending sub- 30 5 10 50, then in this, two of my counts, ascending ascending sub- array, which one can array, which one can I see? One, I can see this. I see? One, I can see this. I see? One, I can see this. two are the biggest, however, this is also a sub continuous, this is also continuous, this is also continuous, this is also continuous, but the maximum, the more digits there are in it, the greater will be the maximum. Okay, in this we might have also given If we see positive numbers, then it is okay, then If we see positive numbers, then it is okay, then If we see positive numbers, then it is okay, then all the numbers are giving us positive all the numbers are giving us positive also. With this thing, it has become very easy to understand also. With this thing, it has become very easy to understand all the things. If the numbers all the things. If the numbers are positive, then the questions should become easier for us. Okay, now are positive, then the questions should become easier for us. Okay, now I can see this. I can see this. I can see this. look at the sum of this part, what will come is 10 p 20 30 30 p 30 60 6 and if I look at the sum of this array then 10 p 10 p 5 15 15 p 50 sorry this is 50 this is 50 What is What is What is coming is our 65 aha so which is bigger between 60 and 65 coming is our 65 aha so which is bigger between 60 and 65 65 what is it ok to return me the answer 65 what is it ok to return me the answer so we have to find the maximum so we have to find the maximum if I talk about this array the elements in this array if I talk about this array the elements in this array are my 10 20 30 40 and 50 so are my 10 20 30 40 and 50 so What is this entire array? A ascending What is this entire array? A ascending order. So the total sum of it will be order. So the total sum of it will be our answer. Let's see how 10 + 20 30 30 our answer. Let's see how 10 + 20 30 30 + 30 60 60 + 40 100 100 + 50 150 + 30 60 60 + 40 100 100 + 50 150 So this entire array is an ascending order. So this entire array is an ascending order. What is there, we have an array, so the What is there, we have an array, so the whole of it will be even, that will be whole of it will be even, that will be our answer. If I talk about this our answer. If I talk about this part, then what is there in it? 12 17 part, then what is there in it? 12 17 15 15 after 15 15 after 13 13 after 10 11 13 13 after 10 11 If I look in it If I look in it If I look in it see this, but no one is becoming all, even I myself am not becoming all, with anyone else and this we have one all, one we have all this, one we have all this If I look carefully, the one which will have the most If I look carefully, the one which will have the most If I look carefully, the one which will have the most numbers is ours. First of all, it will be the maximum. numbers is ours. First of all, it will be the maximum. Now, what is becoming the sum of this whole Now, what is becoming the sum of this whole and what is our and what is our 33, then 33, which is our sum, is the same. If we return it then it is the 33, then 33, which is our sum, is the same. If we return it then it is the maximum. maximum. maximum. maximum saber and elements, so how will we remove it, it is a very easy question, there is no very difficult question, it is a very easy approach, due to this, we have come directly here on the screen, now first of all From Let's I have From Let's I have From Let's I have taken this one or this one's array, we will taken this one or this one's array, we will increase one or two elements in it increase one or two elements in it so that it becomes easier for us, 10 20 and 30, so that it becomes easier for us, 10 20 and 30, after that, from Let's 5 10 50, we have after that, from Let's 5 10 50, we have taken one more element, here taken one more element, here P0 is ok, we have given this P0 is ok, we have given this P0 is ok, we have given this so that we can understand the approach better. Okay, so we write its indices. First of all, zero, four, f and si. Now look at one more thing in this, note that sub-array of size one is If there is a subray then that is If there is a subray then that is If there is a subray then that is also ascending. Okay, so this thing also ascending. Okay, so this thing we know that size one means atlist we know that size one means atlist one element has to be returned. one element has to be returned. Okay, so first of all we will Okay, so first of all we will create two variables, why will we create them in create two variables, why will we create them in front of you? front of you? front of you? sum current sum which will be current sum and one is our answer maximum sum no in both initially what will I do sum no in both initially what will I do store our first 10 this because store our first 10 this because at least one element of atlist is making even at least one element of atlist is making even and I will check from here and I will check from here from here from here from here I will keep my pointer here, okay, I have placed the index here, now what should I check, I want ascending sub-array, if I want ascending sub, if the previous element is smaller than the current element, the previous element is smaller than the I have to have one previous element I have to have one previous element I have to have one previous element smaller then I have to add that number to the current sum. smaller then I have to add that number to the current sum. So now let's see if it So now let's see if it is making it so, what did I do? I did 10 x 20. is making it so, what did I do? I did 10 x 20. Now I reached this Now I reached this index. I added the previous element. What is the previous element? index. I added the previous element. What is the previous element? index. I added the previous element. What is the previous element? is small, he is checking because he is in an ascending fear. Meaning of being small is small. Yes brother, he is small. He said yes, he is small, so 30 p. What happened? Now I reached here, here he checked the index behind and removed it. Now let me check the one behind, the one behind is the bigger one, so it means here my ascending order is broken. My ascending order is broken, which means now a new subre will start from here. Okay, the previous subre is finished, so whenever I have such What will I do if something happens, I will look at my sum, what is the sum which I had now, which is bigger than the previous sum, if it is bigger, then update 60 updates, now I have further updated from here, what should I put in the current sum, the same element I had talked to Sabre because he I had talked to Sabre because he I had talked to Sabre because he could become a part of the next Sabre. could become a part of the next Sabre. Maybe I will get a bigger element in the future. Maybe I will get a bigger element in the future. Now he came to Aa and asked if the previous Now he came to Aa and asked if the previous element is smaller than what element is smaller than what he is doing now. If so, what should I do? Just one. he is doing now. If so, what should I do? Just one. he is doing now. If so, what should I do? Just one. now I again Again asked whether 40 is smaller than 40, is 40 Again asked whether 40 is smaller than 40, is 40 bigger than 50, if it was not so then bigger than 50, if it was not so then what would we have done? We would have compared both of them, the what would we have done? We would have compared both of them, the previous sum which had come out till now, we had the same sum previous sum which had come out till now, we had the same sum in the current sum of the previous one. in the current sum of the previous one. It is not bigger than the maximum. It is It is not bigger than the maximum. It is bigger than the maximum. It is 65. So after 65 bigger than the maximum. It is 65. So after 65 I will update the answer. 40 Now it could have been I will update the answer. 40 Now it could have been that there would have been that there would have been a bigger element here. What would have happened here would have been a bigger element. Let's a bigger element here. What would have happened here would have been a bigger element. Let's mean here 40. mean here 40. mean here 40. element which is bigger than the sum, then we will have to check once after the loop that the current sum is not bigger than our max sum, so we will check that thing in the last, If we code then you will If we code then you will If we code then you will understand better, so let's code directly on the screen, that's understand better, so let's code directly on the screen, that's enough, so first of all enough, so first of all I took the max element, which was our current I took the max element, which was our current max, which was our answer max, in it I max, which was our answer max, in it I put the number of zero, I put zero element, put the number of zero, I put zero element, then I then I then I num of zero the first element is fine and I have run the loop from k to k run from i i iv to this lesson nam last I have to go to nums dot length and opps ps y thing I have e if my names of a I have e if my names of a I have e if my names of a my means if the previous element is smaller my means if the previous element is smaller than what names of a if it is smaller then it means than what names of a if it is smaller then it means now it is a part of the sub array, it is a part of whatever sub array is running now it is a part of the sub array, it is a part of whatever sub array is running then I will sort it then I will sort it current max current current max current current max current plus current max plus numbers of a aa only we have to do plus why do we have to do it because we have already done plus in the numbers of aa my means we have already added zeros in case of n also ok so I have added it else if So first I have to check the So first I have to check the So first I have to check the current math which was given in the previous section to see if current math which was given in the previous section to see if it is big then what will I check for it. it is big then what will I check for it. In maths, the one among us In maths, the one among us who will have the maximum value is math dot max who will have the maximum value is math dot max of max comma current of max comma current sorry current. sorry current. sorry current. what should I put in Current Max? The Current Max will be starting a new collaboration, so I will put Nums of I in it, I will also put Nums of I, then my work will be done in this way, but this code is No, why not because it is No, why not because it is No, why not because it is possible that after the loop ends in Current Max, the possible that after the loop ends in Current Max, the last condition of Current Max comes here and the last last condition of Current Max comes here and the last element of Current Max is not updated yet, element of Current Max is not updated yet, so I have to so I have to write this line once outside the loop as well. write this line once outside the loop as well. write this line once outside the loop as well. that the value of the last element of the current mix is big, if the current is higher then we will have to do more up and return because we seeing that everything is working fine by submitting it and seeing that everything is working fine by submitting it and seeing that it has been submitted. seeing that it has been submitted. seeing that it has been submitted. try to understand each case, so I have brought my array to Y and will make it a little bigger, now I take one of our A from late, I took 10 20 30 and 40 50 sorry don't take 40 from taking your ascending If it doesn't happen, here we took If it doesn't happen, here we took If it doesn't happen, here we took 10 15 and 18. Okay, I wrote y so that I can 10 15 and 18. Okay, I wrote y so that I can explain the last one to you. Once I explain the last one to you. Once I write that down, we have our index 0 1 2 3 4 and write that down, we have our index 0 1 2 3 4 and f. Okay, now first of all we took the current f. Okay, now first of all we took the current max. max. What value did we put in zero and max also? What value did we put? Off G 10. We have put this. What value did we put in zero and max also? What value did we put? Off G 10. We have put this. Now I have started ours. Now I have started ours. Start it from here. Come, the Start it from here. Come, the value is here. value is here. value is here. My one index. Now I checked whether the previous element is smaller than me. The element P is smaller than me. Being small means the current max mend to me is 10 P 20 30. Now I again moved ahead. After checking again, is 30 smaller, it asked, yes, yes, so going into it, Ra came to the current mess, 60, now it came here, I asked, are you smaller than me, there is no previous element, if not, then it After going in, the first thing that will be After going in, the first thing that will be After going in, the first thing that will be checked is Max, the value of Max was 10, checked is Max, the value of Max was 10, 10, mine is 16, which of the two is bigger, the one 10, mine is 16, which of the two is bigger, the one who is bigger will come in it, come in Max, come in who is bigger will come in it, come in Max, come in my 60, what will be the current after coming in 60, come my 60, what will be the current after coming in 60, come in Max, come in in Max, come in in Max, come in What is the If If possible then let's see what happened now, what will happen now is that now first of all what will grow next is our aa moved forward aa aa forward b aa after moving forward asked what aa the index on which he stood asks the previous index are If If If it is small then what to do is just it is small then what to do is just go to the current max and add it 10 + 50 60 60 go to the current max and add it 10 + 50 60 60 Okay now come again go ahead and Okay now come again go ahead and ask the previous index What did you ask from the previous index ask the previous index What did you ask from the previous index that you are smaller than me Yes I am so 80 that you are smaller than me Yes I am so 80 + 60 140 + 60 140 + 60 140 now look, our loop has ended, now what happened after our loop ended, this loop has ended, current max, so in current max, maximum is still read, maximum is all read, We found that this is We found that this is We found that this is why the last condition in max was 60 why the last condition in max was 60 comma 140 so 140 and which is the maximum out of 60 comma 140 so 140 and which is the maximum out of 60 140 so what came in max is 140 so what came in max is 140 so that's why the answer here is I I I hope you have understood very well hope you have understood very well how we have solved this question. Okay, let's how we have solved this question. Okay, let's meet tomorrow where we will be meet tomorrow where we will be solving the next question. Hope so you have liked the video. solving the next question. Hope so you have liked the video. If you like the video If you like the video then watch the video. then watch the video. then watch the video. subscribe the channel. If you have any doubt then | 2024-03-22 14:57:58 | 1,800 | LeetCode 1800 | Maximum Ascending Subarray Sum| Day19 | 100 Days_LeetCode_Challenge | DSAwithedSlash |
|
P8c7S15mc5g | hey everyone today we are going to solve the little question find the eventual the little question find the eventual safe States so there is a directed graph safe States so there is a directed graph of nodes with each node leveraged from 0 of nodes with each node leveraged from 0 to n minus 1. the graph is represented to n minus 1. the graph is represented by a zero index to the integer array by a zero index to the integer array graph where graph I is integer array of graph where graph I is integer array of nodes are adjacent to node I meaning nodes are adjacent to node I meaning these are H from node I to each node in these are H from node I to each node in graph I a node is terminal node if there graph I a node is terminal node if there are no outgoing edges a node is a safe are no outgoing edges a node is a safe node if every possible path starting node if every possible path starting from that node these two terminal node from that node these two terminal node or another safe node return array or another safe node return array containing all the safe nodes of graph containing all the safe nodes of graph the answer should be sorted in ascending the answer should be sorted in ascending order order okay so let me explain with this example okay so let me explain with this example zero one two three four five six nodes zero one two three four five six nodes and then each node has this pass so for and then each node has this pass so for example node 0 has 2 paths to node one example node 0 has 2 paths to node one and the two in order two and another one and the two in order two and another one has also two nodes two paths and two has also two nodes two paths and two node two and a two node three node two and a two node three and they're basically we iterates and they're basically we iterates through all nodes one by one through all nodes one by one and as simultaneously and as simultaneously um we keep track of like a current um we keep track of like a current status for each node so there are three status for each node so there are three status so zero is a bit DT node and the status so zero is a bit DT node and the one is a visiting node now and that two one is a visiting node now and that two is a like a terminal node so that means is a like a terminal node so that means if we reach the timer which is 2 so that if we reach the timer which is 2 so that node is one of answers node is one of answers so let's begin so first of all we start so let's begin so first of all we start from node zero and uh from node zero and uh so tick node 0 here so so tick node 0 here so now I'm I'm visited so that's why now I'm I'm visited so that's why um up to date node um up to date node so zero to now visiting right so that's so zero to now visiting right so that's why one why one and then uh check adjacent node and and then uh check adjacent node and which means one two so like this one which means one two so like this one and two and uh okay so let's go to node one so node one is um not unvisited in order yeah I right so that's why updated like a visiting so and then uh check other Json node and and then uh check other Json node and two and three so two two and three so two and three and three so let's move on to another two so node so let's move on to another two so node two is also unvisited two is also unvisited um um node right so that's why in our visiting node right so that's why in our visiting so so output database one output database one and then node 2 has only one pass to and then node 2 has only one pass to node five like this node five like this so let's move on to node 5. so node 5 is so let's move on to node 5. so node 5 is unvisited unvisited model right so that's why update model right so that's why update to one to one and take like adjacent and take like adjacent node but as there is no out going pass node but as there is no out going pass so that means so that means um this is a one of a um this is a one of a terminal nodes right so that's why in terminal nodes right so that's why in this case update this case update um um this status to two this status to two and then I'll return to and then I'll return to so this us is looks good okay so let's so this us is looks good okay so let's go back from node 5 to 2 and then in go back from node 5 to 2 and then in order to is uh definitely order to is uh definitely um one of a safe nodes right um one of a safe nodes right uh because uh there is only one pass and uh because uh there is only one pass and to another five and the Note 5 is to another five and the Note 5 is terminal node so that that's why update terminal node so that that's why update um status of node 2. to like a two so that means if we reach the node two so we can reach the like a terminal node that means five so that's why uh almost uh it's same as like a node two is a like a terminal node so that's why update the status of node 2 2. and then um so there's no only one pass so let's move back to one but one has another pass to normalcy right so let's take to this bus so now we visiting the no Z so that's why I play the status to one visiting and then all the three has and so let's move on to another zero and so let's move on to another zero but um here is the important thing so we but um here is the important thing so we start from another zero right so that's start from another zero right so that's why no status of node 0 is now visiting why no status of node 0 is now visiting so it's kind of uh like a circle so it's kind of uh like a circle so in that case so that means uh we so in that case so that means uh we can't say um can't say um node 0 is node 0 is um safe node so definitely another is um safe node so definitely another is not answer because there is a circle not answer because there is a circle and also um so in the circle and also um so in the circle um so there are there are a few nodes um so there are there are a few nodes like a node one like a node one and a node three right like this zero and a node three right like this zero one three zero one three zero so that's one three zero one three zero so that's why node zero and then all the one and why node zero and then all the one and then over three is definitely then over three is definitely um not safe node so this is not answer um not safe node so this is not answer this is not answer this is not answer yeah um that's why um so far we should know the two to like an answer variable so is that variable so and then um so we know that node one is and then um so we know that node one is not safe no C is not safe and node 2 is not safe no C is not safe and node 2 is a safe node and uh how about a four so a safe node and uh how about a four so now we are visiting four so up to date now we are visiting four so up to date status of node four to one and there is status of node four to one and there is only one pass only one pass no to notify no to notify so we know that node 5 is a terminal so we know that node 5 is a terminal node so that's why um node 4 is also node so that's why um node 4 is also safe node so that's why safe node so that's why um as a notable to these are the um as a notable to these are the variable and then so now we are notify but there's no pass right so that's why move back to four in the case um update the status of node 222 so that means again it really is the number four that means that is a um like a Safeway safe node and then um let's start from node five so node 5 itself is and there is no pass right so that's why node 5 is a random answers right so that's why add five and then move next and then how about six so now visiting six so update status to one and then there's a there's no pass so that's why six is also terminal node so that's why R6 to answer variable and then update status to two and then there's no um status uh pass and there's no node here so that's why we finish iteration and then in the end we create like a two four five six so that's why in this case output is like this yeah so that is a basic idea to solve discussion without being said let's get into the code okay so let's write Circle first of all um calculate the ranks of graph so graph and visit it kind of Interest with zero multiply and so zero is um visited and the one is visiting and the 2 is I got time you know and then result variable with empty list and so basically we did it through all nodes one by one so for pi in range and a node length of node and if let's say is safe and current mode if this function be done through so append the dot null to result variable so result dot append and I and then after that return result variable so let's create a is fun easy save function So Def is safe in the first of all check the visited in the first of all check the visited list if visit it and the null is greater list if visit it and the null is greater than zero so that means we already visit than zero so that means we already visit that node that node and then later and then later visit it node visit it node equal to so if that node is a terminal equal to so if that node is a terminal node so we should return true if like a node so we should return true if like a visiting visiting um return false um return false and then if not the case that means and then if not the case that means current node is unvisited so now we are current node is unvisited so now we are like visiting that node so update the like visiting that node so update the visited visited node equal one node equal one and check neighbor in graph in the node and if not is safe in the case we should be down pause in the case we should be down pause if not the case that means current node if not the case that means current node is terminal so visited BC did node yeah I think that's it so rain is yeah I think that's it so rain is updated let's get in a very efficient updated let's get in a very efficient algorithm algorithm so time complexity of this solution so time complexity of this solution should be order of V plus e so V is the should be order of V plus e so V is the number of nodes and vertices in the number of nodes and vertices in the graph and the E is the number of edges graph and the E is the number of edges in the graph so this solution called in the graph so this solution called performs like this first search and performs like this first search and starting from each node and the based in starting from each node and the based in each node and the edge once so in the each node and the edge once so in the last case all nodes and the edges are last case all nodes and the edges are visited so result in the time complexity visited so result in the time complexity of Mega order of V plus e space complexity is order of V so V is the number of nodes and the vertices in the graph so the space complexity is determined by the like a visited list which was a visitation status of each node so in the worst case the visited list will store the status of all nodes so resulting in space complexity of order of V yeah so that's all I have for you today if you like it please subscribe this channel hit the like button or leave a comment I'll see you in the next | 2024-03-22 14:00:52 | 802 | Find Eventual Safe States | Python, JavaScript, Java, C++ | LeetCode #802 |
|
g1R3yEtHT8E | okay so uh need code practice time so in this video there are two goals this video there are two goals the first goal is to see how to solve the first goal is to see how to solve this problem and then we are going to do this problem and then we are going to do some coding work some coding work and the second goal is to see how we and the second goal is to see how we should behave in a real interview should behave in a real interview so let's get started so remember the so let's get started so remember the first step in the real interview is to first step in the real interview is to always always try to understand the problem if there try to understand the problem if there is anything unclear please bring up the is anything unclear please bring up the question question and at the same time think about some and at the same time think about some ash cases ash cases so let's take a look at this question so so let's take a look at this question so all the nodes all the nodes distance k in the binary tree so we are distance k in the binary tree so we are given a binary tree given a binary tree a target node and an integer value k a target node and an integer value k so we want to return a list of the so we want to return a list of the values of values of arnolds that have a distance k from the arnolds that have a distance k from the target node target node so the answer can be returned in any so the answer can be returned in any other other so let's see example as so let's see example as root so this is the root root so this is the root which is which represents a tree which is which represents a tree something like this something like this and the target is equal to 5 and k is and the target is equal to 5 and k is equal to 2 equal to 2 so the output is going is going to be 7 so the output is going is going to be 7 4 1 because 4 1 because the nodes with distance as 2 the nodes with distance as 2 from 5 is uh 7 4 and 1. from 5 is uh 7 4 and 1. okay that makes sense so let's see some okay that makes sense so let's see some constraints constraints so the given tree is not empty so the given tree is not empty so it's not an empty tree and each node so it's not an empty tree and each node in the tree has a unique value in the tree has a unique value between 0 to 500 so the target node is between 0 to 500 so the target node is the node the node in the tree okay in the tree okay and the k is between zero to and the k is between zero to one thousand so first of all we know one thousand so first of all we know that the tree is not that the tree is not empty and it's it's for sure that the empty and it's it's for sure that the target is one of the notes within the target is one of the notes within the tree tree uh but we don't know whether the kai uh but we don't know whether the kai uh is actually valid or not because uh is actually valid or not because if it is because if there's no um if it is because if there's no um no nose within the root within the tree no nose within the root within the tree that has distance that has distance of k from this target then we are going of k from this target then we are going to return to return empty but i think that should be covered empty but i think that should be covered uh uh by a by the general algorithm by a by the general algorithm so let's see how to solve this problem so let's see how to solve this problem so the next part about finding solutions so the next part about finding solutions so this part is mostly about you so this part is mostly about you communicate with your interior and words communicate with your interior and words or draw something whatever so use any or draw something whatever so use any technique technique any way to explain how you're going to any way to explain how you're going to solve this problem and do some run time solve this problem and do some run time space space analysis so let's see analysis so let's see for this i will say first of all we need for this i will say first of all we need to at least find to at least find the node from the tree and then the node from the tree and then to find the distance from k it makes me to find the distance from k it makes me feel feel for to find all the nodes with distance for to find all the nodes with distance k from this node k from this node it makes me feel like it is a bfs it makes me feel like it is a bfs function function it's a bfs problem but the thing it's a bfs problem but the thing the thing um it's very it's a little bit the thing um it's very it's a little bit different from the regular different from the regular bfs it's because bfs it's because except for the children knows except for the children knows we also need to find the we also need to we also need to find the we also need to extend extend to its parent node so for example for to its parent node so for example for this um this um node 5 the first layer we are going to node 5 the first layer we are going to try to extend try to extend include the left child the red child and include the left child the red child and this parent this parent and for the second layer um and for the second layer um we are going to extend the the we are going to extend the the children's children's and the corresponding parent so since and the corresponding parent so since this note doesn't have a parent this note doesn't have a parent you're just going to expand to its uh you're just going to expand to its uh it's right child so it's right child so i would say first of all um you could i would say first of all um you could use either bfs or use either bfs or uh uh i think we should uh uh i think we should it should we could we could either use it should we could we could either use bfs or dfs bfs or dfs to find the parent relationship to find the parent relationship uh for each node for example we find the uh for each node for example we find the parent of five as parent of five as three we find the parent of six as five three we find the parent of six as five so and so forth so first of all we need so and so forth so first of all we need to run either bfs or dfs to run either bfs or dfs to find the parent relationship and add to find the parent relationship and add it into it into a separate map a separate map and uh the next thing we will do a bfs and uh the next thing we will do a bfs to extend from the target node to extend from the target node layer by layer to try to find uh all the layer by layer to try to find uh all the nodes nodes that has distance k from the current that has distance k from the current target node so having said that the target node so having said that the runtime is going to be 11 runtime is going to be 11 because we just need to almost look at all the nodes within the tree twice and uh so runtime is all events space wise it's also olefin because we need to record the parent relationship uh and potentially we also need to record uh what which notes has been visited in our bfs uh part b or bfs part so having said that uh let's do some coding work so in the coding part we care about the correctness of the code the readability of the code and also the so uh let's take a look so it's not an empty tree and target is for sure uh to exist in this for sure to exist in the in the in the tree so first of all let's define a helper function call it bfs so the dfs is going to have so the dfs is going to have you're going to have two things the you're going to have two things the first one is the node and the first one is the node and the second one is the parent second one is the parent all right so we are going to first of all define a map with tree node shino so the sec the first one is the node and the second one is his parent per node so i will say parents all right then we will run the advanced all right then we will run the advanced dfs on top of it dfs on top of it so it will be root and then none pointer uh and i actually at the same time you need to pass in the this is not parent so now apparent this is not parent so now apparent all right so um if node is equal to none uh if node is equal to none they just and otherwise and otherwise so otherwise we will need to have so otherwise we will need to have node parent dot node parent dot added let's put added let's put the put node and the the put node and the parent then we are going to say dfs on parent then we are going to say dfs on top of top of no node.left and paren sorry node no node.left and paren sorry node and dfs no dot right and dfs no dot right dot node dot node so yeah so that's it so yeah so that's it and also we may not really want to have and also we may not really want to have the pair which is the root and the pair which is the root and the the nun pointer put into it so i the the nun pointer put into it so i will just put will just put a if parent is not equal to a a if parent is not equal to a num pointer then we are just going to put the node and parent into it to have the parent node to have the parent node yes um and then yes um and then the next part is about um the next part is about um bfs so for bfs we essentially need to bfs so for bfs we essentially need to have a queue have a queue of the tree node so the tree node of the tree node so the tree node uh let's say so q uh let's say so q use linked list as the underlying use linked list as the underlying implementation implementation so first of all you put it's so first of all you put it's add you add the target node into it so well q is not empty then we are going to keep continue so in this in this case we actually need to keep track of one is the distance starting with k and the other one i would need to keep track of is the because because we need for for example for 5 the first layer is 6 two and three um we don't really want to visit five again because we have we don't really want to visit the nodes we have already visited again uh so we need to have pretty much have a set of the notes let's call it visited so first of all we will have so first of all we will have inch size as inch size as the cutout size the cutout size and then you're going to say and then you're going to say i 0 is smaller in size and plus plus i i 0 is smaller in size and plus plus i so if uh so first of all we need to put pop the thing so tree node the node as equal to q dot pop okay it's full all right so yeah we actually need to define the thing we are going to return finally so let's define the list of the integers um this is nose with distance okay new so if um so if um so if the distance is equal to so if the distance is equal to k then we need to k then we need to have nodes with distance have nodes with distance k is dot adder k is dot adder uh dot add uh it will be dot at the node. value okay and then for how to extend it so we would for how to extend it so we would need to make sure that so if need to make sure that so if node dot node dot so if node dot lot so if node dot lot is not equal to a none then so if node the left is not equal to then you're going to add it into the queue but first of all we need to make sure that the node doesn't exist so if um visited dots contains if visit doesn't contain dots contains if visit doesn't contain node.left node.left then we are going to have visited the no doubt left and we are going to add the q uh no that left all right so this is the left branch and uh the next thing is about right branch right is not equal to a none uh not visited so uh not visited so actually uh we could define another actually uh we could define another helper function let's say void uh add a let's stop calling add a node to a q so essentially we have several different things the first thing is the tree node to be added and the second one is a q and the third one is the so the thing is if the so the thing is if the node is equal to a node is equal to a none then we just return none then we just return and if visited and if visited dot contains the dot contains the node then we are going to return node then we are going to return and if the node is not none we haven't and if the node is not none we haven't visited visited then we are going to have q dot add then we are going to have q dot add the node so you could the node so you could use this helper function actually use this helper function actually to have node.left to have node.left and the queue and visit it and the queue and visit it so similarly we have a node to queue so similarly we have a node to queue snow dots right q snow dots right q and visited and similarly we will have the okay so it's no i know to okay so it's no i know to kill i will say if if the if know the parent dot intense key which is the note then we will call the add the note dot get or maybe you just dot get or maybe you just call it get or default call it get or default or default uh so this is the node and the non-pointer all right so if the parent is not none and it's not in the visited and you're going to add a parent into it so yeah i think that's pretty much it about how to extend this layer and about how to add the node and finally uh you're just going to return um what is that we're going to return node where's distance good all right so uh having said that um i think we are mostly co-complete uh but i think there is a bug here actually we should plus plus the distance here um because we just finished finished uh visited one layer which we need to plus plus the distance and um after we plus plus the distance if the distance is larger than if it is larger than k they pretty much just need to break this so um after you're done with code so um after you're done with code we are done with coding it's not done uh we are done with coding it's not done uh with the interview we need to do some with the interview we need to do some testing testing so the way we do testing is first of all so the way we do testing is first of all we do some sanity check we do some sanity check by going through our example to see how by going through our example to see how it is going to work at the same time we it is going to work at the same time we are going to explain how this piece of are going to explain how this piece of code is going to work to the interviewer code is going to work to the interviewer and after that we will introduce some and after that we will introduce some different task cases to make sure we different task cases to make sure we have good enough test coverage about have good enough test coverage about different branches in the code so let's different branches in the code so let's see let's take see let's take the exact as an example we find the the exact as an example we find the target as 5 target as 5 ks distance s2 within the tree ks distance s2 within the tree so first of all we have the node parent so first of all we have the node parent thing and thing and we have a dfs on top of it we have a dfs on top of it and uh if parent is not equal to and uh if parent is not equal to none then we just put the node and parent relationship or and if node is equal to a none then you just simply return so first of all you're going to put you're not going to put anything when it's true because we call the root none then we go to the left and right child uh yeah so i think similarly we could and then we are going to deeper and deeper as we do that we keep adding the parallel relationship into uh the node parent map so i think after that we should be mostly good about it and uh after that after the dfs it's the bfs part so we have the q we have the distance we have the visited so while the queue is not empty so first of all you have the size of the queue which is the so we are going to say okay node is so we are going to say okay node is equal to none sorry node equals to equal to none sorry node equals to the for we are going to pull the node the for we are going to pull the node from the queue from the queue and if the distance is equal to k and if the distance is equal to k then you're going to put it into it so then you're going to put it into it so first of all first of all we pull the 5 from it which is the first we pull the 5 from it which is the first layer layer um and currently distance is equal to 0 um and currently distance is equal to 0 which is not equal to k so we are going which is not equal to k so we are going to add to add the left right hand parent into the left right hand parent into it so when we try to add it so when we try to add we need to actually we need to actually i didn't update the visited i didn't update the visited so you should have the wizard dot so you should have the wizard dot add the node add the node when we try to add node to the queue so um so okay so we update the visited yeah and we also update the queue so currently we have the queue that has three nodes in it the plus what's the distance because this layer is finished and next time uh next time when we step into the while loop again so the distance is one and then uh we are going to try to extend the this node this we first of all we try to extend six so six we see that the left child both left and right are none then we are not going to add into the queue and we see that the the node file is already visited so we are not going to add into the queue so for two similarly we are going to add seven four but we are not going to add five into it for three we are not going to add five and we are not going to add its parent because the parent is a 9 pointer and also we are going to add the 1 into it and we are going to plus plus the distance not distance is equal to 2. so the next time we have three seven four and one in the queue we add the values and these ten after you extend the distance is larger than two so you're going to simply break so i think mostly it should work uh from what i can see let's give it a shot by run this piece of code all right so what uh what is this it's node oh okay so i think i should some typo here you okay so it's wrong answer let's see why okay so it's wrong answer let's see why it is it is wrong so we got set five wrong so we got set five seven four and one into it seven four and one into it but uh should we do it but uh should we do it so i think the thing is we didn't add so i think the thing is we didn't add let me try to add the first stuff into let me try to add the first stuff into the visited the visited then we didn't actually update the then we didn't actually update the visited visited with the first node this is with the first node this is essentially where the bug is essentially where the bug is so i think this should fix the book so so i think this should fix the book so visited visited oh so we have we should define it here uh should add a queue while we update yep so this should fix a bug let's give yep so this should fix a bug let's give it a submission it a submission all right so now everything looks good all right so now everything looks good um um so regarding the test case setup i would so regarding the test case setup i would say say um i think the having this task case is um i think the having this task case is pretty good enough but if you want to pretty good enough but if you want to keep keep some other test cases for example when k some other test cases for example when k 0 0 0 0 or when k is larger than or when k is larger than 1 k 1k setup as a value that we will 1 k 1k setup as a value that we will return nothing from the return nothing from the from the tree uh so that should be from the tree uh so that should be that would be great but uh if you just that would be great but uh if you just set up this example i would say set up this example i would say that's perfectly fine so that's it for that's perfectly fine so that's it for uh this uh this coding question if you have any coding question if you have any questions about the puzzle or about the questions about the puzzle or about the solution feel free to leave some solution feel free to leave some comments below comments below and if you like this video please give and if you like this video please give me a thumb up me a thumb up and i'll see you next time thanks for and i'll see you next time thanks for watching | 2024-03-22 16:30:17 | 863 | Google Coding Interview Question | Leetcode 863 | All Nodes Distance K in Binary Tree |
|
0XCq29SOhNQ | hello everyone let's take a look at this new core problem new core problem it's a um the second problem in the it's a um the second problem in the weekly context weekly context although it's the second problem but i although it's the second problem but i think it's a little bit think it's a little bit hard since it's kind of like a knapsack hard since it's kind of like a knapsack problem so it's a dp problem also you problem so it's a dp problem also you can solve it can solve it unlike by dfs and since the constraint unlike by dfs and since the constraint is not set strict okay let's take a look is not set strict okay let's take a look at at like how to solve this problem if you like how to solve this problem if you haven't used the problem you can take haven't used the problem you can take some time to read some time to read the description is quite long so the description is quite long so we need to create like ice cream we need to create like ice cream so some um this flavor and we have to so some um this flavor and we have to choose exactly one piece flavor and choose exactly one piece flavor and there are some toppings there are some toppings and we can choose any toppings and for and we can choose any toppings and for each topping there are at most two each topping there are at most two like so for example like so for example like for chocolate we can only choose like for chocolate we can only choose two chocolate toppings two chocolate toppings but we can choose any types of tokens so but we can choose any types of tokens so given target asks us to compute a cost given target asks us to compute a cost which is the closest to the target which is the closest to the target okay let's take a look at this example okay let's take a look at this example so we can choose this flavor 7 and so we can choose this flavor 7 and choose one top in 3 choose one top in 3 so we have cos 10 which is closer to so we have cos 10 which is closer to target target and let's take a look at like how to use and let's take a look at like how to use dp dp to solve this problem to solve this problem so we have a dimensional dp array it's so we have a dimensional dp array it's boolean array to indicate boolean array to indicate that if i have um cos 11 or if i have that if i have um cos 11 or if i have cost cost 12 at first the default value is force 12 at first the default value is force first we can just follow on the base first we can just follow on the base costs and set costs and set value to true so we have one and seven value to true so we have one and seven so one seven so one seven is true since uh for example i can is true since uh for example i can choose choose base seven and i don't need to choose base seven and i don't need to choose any toppings so seven is okay any toppings so seven is okay okay next i can use um okay next i can use um the first topping three so the first topping three so four and ten is two since ten can come four and ten is two since ten can come from seven four can come from one from seven four can come from one next i can use second topic 3. so 13 is next i can use second topic 3. so 13 is true since 13 can come from true since 13 can come from 10. so for each topping we can just 10. so for each topping we can just follow follow my array and for each value i can just my array and for each value i can just if it can come from previous if it can come from previous number for example 3. i number for example 3. i need to check if 13 is true or not need to check if 13 is true or not so count top on top is 3 so i need to so count top on top is 3 so i need to check check and table 13 minus 3 which is table 10 and table 13 minus 3 which is table 10 table 10 is 2 so table 10 is 2 so table 13 is true okay next we can use table 13 is true okay next we can use topping four topping four so 17 is true since 17 can come from 13 so 17 is true since 17 can come from 13 14 is true which comes from 10 11 is 14 is true which comes from 10 11 is true which comes from seven true which comes from seven eight is true which comes from four five eight is true which comes from four five is true which comes from one is true which comes from one okay next we can do second typing form okay next we can do second typing form but i didn't draw here since we but i didn't draw here since we already figured out how to solve it so already figured out how to solve it so this is implementation this is implementation let's take a look at constraint so the let's take a look at constraint so the base cost is between one to base cost is between one to like ten thousand so we can choose a like ten thousand so we can choose a base cost base cost and target is also between one to one and target is also between one to one thousand thousand so to only choose one base cost and for so to only choose one base cost and for targets targets we know the diff is smaller than one we know the diff is smaller than one thousand thousand so for my table i can just use a so for my table i can just use a constant number constant number like twenty thousand since we don't need like twenty thousand since we don't need to calculate to calculate thirty thousand forty thousand since we thirty thousand forty thousand since we already know as long as i choose any already know as long as i choose any base cost base cost so optimal div is like the div is so optimal div is like the div is already smaller than one thousand already smaller than one thousand so ten thousand okay so i just for loop so ten thousand okay so i just for loop base cost and set the table base to true base cost and set the table base to true then we just for loop each topping then we just for loop each topping and for each topping we can use at most and for each topping we can use at most twice so there's also enough for loop twice so there's also enough for loop here here then i just track each value to see if then i just track each value to see if they can come from a perfect they can come from a perfect previous value if it can comes off come from previous value then table current value is true then i just check my table and depicts the best number finally just returns this number so it's a very typical um db problem and it com it's in the second problem in the weekly contest uh since the constraint is not that um bad since an amnes and smaller or equal center there are some other solutions okay listen | 2024-03-22 14:29:28 | 1,774 | LeetCode 1774. Closest Dessert Cost |
|
R-JYLKJzRqU | this is one of the frequently Asked question in interviews like Google mang question in interviews like Google mang Facebook companies and the question is Facebook companies and the question is like remove and node from each of the like remove and node from each of the list means you have to remove the list means you have to remove the specific node you will be giving a head specific node you will be giving a head of that linked list and removing which of that linked list and removing which node you have to remove so here I have node you have to remove so here I have given a link links and I have given n is given a link links and I have given n is equal to 2 so basically 0 1 2 so this equal to 2 so basically 0 1 2 so this from here I have to cut down and I have from here I have to cut down and I have to link this to five and here's the code to link this to five and here's the code for this you can pause the video and get for this you can pause the video and get the code and do subscribe to code for the code and do subscribe to code for placement we will be making more such placement we will be making more such videos and in near future so do videos and in near future so do subscribe our Channel and be with us subscribe our Channel and be with us here you can see the Beats is hundred here you can see the Beats is hundred percent and within 0 Ms so this is the percent and within 0 Ms so this is the code guys do subscribe | 2024-03-19 16:14:29 | 19 | Leetcode 19. Remove Nth Node From End of List #interview |
|
wsTcByj8QbI | hello friends today nests of continuous sub Arisa will give a list of sub Arisa will give a list of non-negative numbers and their target non-negative numbers and their target integer K we need to write a function to integer K we need to write a function to check if the array has a continuous sub check if the array has a continuous sub array of size illicit you there are some array of size illicit you there are some sub your multiple of K actually this sub your multiple of K actually this problem is a classic sub arrays on problem is a classic sub arrays on problem we can use an idea of prefix sub problem we can use an idea of prefix sub the reason is that it's very easy to the reason is that it's very easy to catch the sum between index 0 to index I catch the sum between index 0 to index I is the index of the you know the rest of is the index of the you know the rest of the on other words other index in the the on other words other index in the array so it can be 0 0 0 1 0 2 so on so array so it can be 0 0 0 1 0 2 so on so forth it's very easy because we can get forth it's very easy because we can get that sum by iterate from left to right that sum by iterate from left to right and we accumulate as a Sun but folder and we accumulate as a Sun but folder index from like fronds 3 to 5 it can be index from like fronds 3 to 5 it can be harder but we can use the same idea to harder but we can use the same idea to get as a sample in this sub array we can get as a sample in this sub array we can use index 0 to index 5 - index 0 to use index 0 to index 5 - index 0 to index 2 is that correct we can use the index 2 is that correct we can use the subtraction to get the sum of the subtraction to get the sum of the continuous sub array so not a starter continuous sub array so not a starter from the index 0 so in this question we from the index 0 so in this question we can also use this idea let's see we have can also use this idea let's see we have some one some two which are both start some one some two which are both start from index 0 and if they're subtraction from index 0 and if they're subtraction mojo k equal to zero that means this mojo k equal to zero that means this sub-array is the multiple of K right sub-array is the multiple of K right so we then we can get someone mojo okay so we then we can get someone mojo okay you go through some to module K so that you go through some to module K so that means we can just do a normal iteration means we can just do a normal iteration from left to right and we get the from left to right and we get the accumulated or some and if the K is not accumulated or some and if the K is not equal to zero we use the same module K equal to zero we use the same module K and if this thing we already seemed and if this thing we already seemed before that means we find a sub array before that means we find a sub array that's some equal to the multiple of K that's some equal to the multiple of K the last thing we needed to check it the last thing we needed to check it whether the size is great or you whether the size is great or you couldn't - so the the algorithm ate it couldn't - so the the algorithm ate it but there is some minor details we but there is some minor details we needed to take care one thing is how needed to take care one thing is how about if the someone is the whole array about if the someone is the whole array and actually the sum to is does not and actually the sum to is does not exist so that's the reason we should exist so that's the reason we should take care of the special case 0 because take care of the special case 0 because when is someone is a whole array the sum when is someone is a whole array the sum to actually is 0 like if this array is to actually is 0 like if this array is sum equal to 6 and 6 is multiple of 6 we sum equal to 6 and 6 is multiple of 6 we need like you have the sum - so we need need like you have the sum - so we need use the 6 - 0 and we know there's use the 6 - 0 and we know there's multiple 6 and how to check whether this multiple 6 and how to check whether this is some module K we have seen before is some module K we have seen before we can use a hash set or hash map but we we can use a hash set or hash map but we also need to check whether the size is also need to check whether the size is great or equation - so we need the that great or equation - so we need the that is the way is to use the index so we can is the way is to use the index so we can use the current index minus the previous use the current index minus the previous index so in the end we will use a hash map and the key is the some mojo K and the value is the index in that case for the 0 we should at first I put as a 0 minus 1 because in this case the current the index is 3 and a 3 minus negative 1 we care for just exactly the size of this someone write exactly the size of the separate is 4 okay so now let's write the code we will use a map integer integer and we will call it map and to not forget to put as a special case which is 0 negative 1 actually in every sub array some problem we need to take care of the 0 but sometimes we need to put a 0 if it's a code sometimes we needed to put an active one it depends on the specific case you need to think about this special case and then we use a sum to accumulate then we iterator this array from 0 I less than number stalin's I plus plus the sum will accumulate a current value and the only window K not equal to 0 we let some equal to some module K otherwise it cannot be done right ok so if the map contains key so we already did before then we'll check the size if I - map get some great oh you couldn't you if yes we return true otherwise we put the some I threw the map and finally we return force okay we finished and turn complexity is linear b : okay I don't know why it's so slow but the same code is permitted 80 hours you know it's a nice piece the data so you know it's a nice piece the data so it's quite fast but but at least you it's quite fast but but at least you know the time capacity is big ole and know the time capacity is big ole and that's enough that's enough maybe that's the way have some problem maybe that's the way have some problem okay thank you for watching see you next okay thank you for watching see you next time | 2024-03-18 12:19:54 | 523 | LeetCode 523. Continuous Subarray Sum Explanation and Solution |
|
rhPoFzpKXWA | hey hey everybody this is larry this is me going with q2 of the recent me going with q2 of the recent contest juvenile trees uh hit the like contest juvenile trees uh hit the like button to subscribe and join me in button to subscribe and join me in discord and let me know what you think discord and let me know what you think so this one is a relatively straight so this one is a relatively straight application of either pre-order or in application of either pre-order or in order it doesn't order it doesn't or shouldn't really matter as long as or shouldn't really matter as long as you do it from left to right you do it from left to right um or even post order as long as you do um or even post order as long as you do it from left to right it from left to right then you know then it's good uh and then then you know then it's good uh and then after that after that um so what i did is i just run a depth um so what i did is i just run a depth first search first search uh i go through each node i keep track uh i go through each node i keep track of the level of the level i you know for each level i append it to i you know for each level i append it to a list a list and then i do the the and then i do the the traversal and then after that i just traversal and then after that i just have a for loop for each level have a for loop for each level for each level we just check whether the for each level we just check whether the condition is true condition is true um which is the conditions that you have um which is the conditions that you have here here uh so it's pretty straightforward um uh so it's pretty straightforward um it's a little bit more in the it's a little bit more in the implementation side so implementation side so let me know what you think i don't want let me know what you think i don't want to get it's linear time here to get it's linear time here and it's linear time here because we and it's linear time here because we look at each element at most once look at each element at most once one time so you know you're not one time so you know you're not it's linear time uh and space is going it's linear time uh and space is going to be over n because we put to be over n because we put every element inside this levels thing every element inside this levels thing right right so oh it's a linear time linear space uh so oh it's a linear time linear space uh let me know what you think let me know what you think i know the description isn't that um i know the description isn't that um you know if you're having trouble you know if you're having trouble finding this uh explanation finding this uh explanation i would recommend just starting up on i would recommend just starting up on three algorithms three algorithms i think this is a pretty straightforward i think this is a pretty straightforward application of it and there are application of it and there are way much similar problems on the code way much similar problems on the code with this problem with this problem it's just that they have different it's just that they have different criteria and in this case uh the only criteria and in this case uh the only thing that changes is just thing that changes is just the criteria whether this is a force or the criteria whether this is a force or true and you just have to keep track of true and you just have to keep track of them them uh let me know what you think uh uh let me know what you think uh i am you know going to learn from how to i am you know going to learn from how to explain these so definitely hit the like explain these so definitely hit the like button hit the subscribe button button hit the subscribe button uh and yeah and hit you know and you can uh and yeah and hit you know and you can watch me watch me live now or solve it live during the live now or solve it live during the contest now oops you hmm that's not good okay um this is okay what a real problem uh that was kind of what a real problem uh that was kind of a wealth contest uh mostly on the q4 a wealth contest uh mostly on the q4 uh let me know what you think about me uh let me know what you think about me solving this problem and i will see you solving this problem and i will see you next contest bye | 2024-03-15 18:13:41 | 1,609 | 1609. Even Odd Tree (Leetcode Medium) |
|
Li7Dt_N-ouY | everyone i'm back again with an interesting video this is an interesting interesting video this is an interesting problem that we will look at and i would problem that we will look at and i would share the solution that i developed to share the solution that i developed to solve this problem solve this problem this problem uh this problem uh says the string paypal is hiring is says the string paypal is hiring is written in a zigzag pattern on a given written in a zigzag pattern on a given number of rows like this number of rows like this uh uh paypal is hiring so zigzag pattern p a y paypal is hiring so zigzag pattern p a y then p a l i s then p a l i s high high ring ring so this is the pattern that so this is the pattern that we have to assume that you know if a we have to assume that you know if a string is in a zigzag pattern string is in a zigzag pattern uh uh spread on number of rows which will be spread on number of rows which will be input to the function input to the function and the output should read like p h n a and the output should read like p h n a p l s i i g p l s i i g y i r y i r so so given a string given a string and number of rows and number of rows you we have to assume that you know it you we have to assume that you know it is in zigzag pattern is in zigzag pattern spread across the number of rows spread across the number of rows and then the output is reading it in and then the output is reading it in like straight line like straight line okay okay i hope that makes sense it this problem i hope that makes sense it this problem uh uh it takes some time for you to you know it takes some time for you to you know understand but once understood it is understand but once understood it is actually a very simple problem to solve actually a very simple problem to solve so the intuition for solving this so the intuition for solving this program is that program is that what we would do is that we will have what we would do is that we will have a list of number of string buffers like a list of number of string buffers like equal to the number of rows so in this equal to the number of rows so in this case we will have a list which will have case we will have a list which will have three string buffers three string buffers and what we are going to do and what we are going to do is that is that say you know we'll have to look through say you know we'll have to look through the string the string and in the first iteration and in the first iteration up to like three characters or number of up to like three characters or number of rows we would add one to the rows we would add one to the first string buffer and the second to first string buffer and the second to the second string buffer and third one the second string buffer and third one to the third string buffer to the third string buffer now on the way up now on the way up we will not add anything in the third we will not add anything in the third string buffer but we will add an element string buffer but we will add an element to the second one and to the first one to the second one and to the first one on the way down we will not add anything on the way down we will not add anything to the first one we will add to the first one we will add one character to the second string one character to the second string buffer and second character to the buffer and second character to the third string buffer third string buffer and so on so forth and so on so forth until uh that outer loop reaches to the until uh that outer loop reaches to the end of the string so that's what we are end of the string so that's what we are going to do first up if is equal to 1 is equal to 1 there isn't much that we have to do there isn't much that we have to do we'll just return as and then um i i will declare a few variables and the you know the toggle one is the one that i will use to know whether uh i'm going down in in the zip zag pattern or i'm going up so i'm assuming minus one like there is no zigzag pattern so the first one will be going down and i need bunch of other integers through the arrays and here i am declaring a string builder result because in the end you know i will have to concrete concatenate that list as well the list of string builders so i will use and then this is my list new arraylist and i will have to initialize this list of string builders so i will do a for a and what i'm doing here so i'm initializing the list by you know adding string builders at each row so in this case if num rows say is three then this list will have uh three string builders and let's initialize i as zero i will do a while and what do i have so i have in this one what i would do i would set toggle as 1 that means that the next iteration and and once once this exact pattern for going up is this exact pattern for going up is complete then the next one is that it complete then the next one is that it will come down if toggle if toggle is equal to equal to 0 and i will is equal to equal to 0 and i will explain in a bit that you know why we explain in a bit that you know why we have to look at have to look at the the toggle parameters so when so what is happening is that when the so what is happening is that when the total is -1 total is -1 what i want to do is that i want to run what i want to do is that i want to run a loop till the number of rows that we a loop till the number of rows that we have to worry about have to worry about and then and then respective string builder respective string builder in the respective string builder i would in the respective string builder i would append that character like in the case append that character like in the case of paypal is hiring of paypal is hiring so toggle is -1 for the first iteration so toggle is -1 for the first iteration of this while loop of this while loop and i would get the first string builder and i would get the first string builder append append the character the character at index i at index i and then it and then it increment i and j increment i and j before uh getting into the loop though i before uh getting into the loop though i would have to set j as zero would have to set j as zero so the first element or the first string so the first element or the first string builder will get p the striking string builder will get p the striking string builder will get a and the third string builder will get a and the third string builder will get y in this loop builder will get y in this loop and then what i'm doing is that i'm and then what i'm doing is that i'm setting the toggle to one now why we need to know the toggle position is that in the second iteration of the outer for loop we do not want to assign anything to the last string builder so the j in that case would be j rows minus 2 in this case you know because j is starting from 0 so we have to factor in that and that is why we need to subtract it by 2. essentially what what it does is that you know for example if num rows is 3 so you are subtracting 3 minus 2 1 and what you have is that we will loop it from the back in this case so we will set the first l first string builder with the character and then the second string builder so in this case we are setting up string builder one and string builder zero so that's why we have to start from uh from the n minus one for uh when toggle is equal to one so let me just copy paste it certain things all set so you have to do and then on the way down and then on the way down what we want to do is that we do not what we want to do is that we do not want to want to assign anything to the assign anything to the to the first element so that means to the first element so that means whatever assignment that we would do whatever assignment that we would do would be from the second string builder would be from the second string builder in this case it would be in this case it would be uh j1 that's a second string builder okay so i think this looks good okay so i think this looks good so we will have our string builders so we will have our string builders updated updated with all of this toggling and looking at with all of this toggling and looking at certain restrictions certain restrictions so once all of this is done so once all of this is done and we are out of our and we are out of our outer while loop outer while loop now we we are ready now we we are ready to to concatenate the results into the result concatenate the results into the result string builder that we have since it is a string builder we have to convert or get the two string value so i think we are good to go now so i think we are good to go now let's run the code great so we're getting the results back let me just so this one also goes fine so this one also goes fine in terms of the time complexity it is uh in terms of the time complexity it is uh big o n big o n you might argue that you know there are you might argue that you know there are internal while loops as well but those internal while loops as well but those while loops are going to run while loops are going to run for certain number of rows and number of for certain number of rows and number of rows rows going by the test cases you we can going by the test cases you we can assume that you know it will be some assume that you know it will be some constant value only constant value only but but yeah so that's what the time complexity yeah so that's what the time complexity is in terms of space complexity is in terms of space complexity it will be it will be of the order number of rows of the order number of rows uh uh yeah so in this case uh yeah the time yeah so in this case uh yeah the time complicity i think uh complicity i think uh getting back to my initial comment so getting back to my initial comment so it would be of the order n it would be of the order n into into [Music] [Music] the number of rows now if number of rows the number of rows now if number of rows is a constant value like like i is a constant value like like i mentioned you know going by the examples mentioned you know going by the examples then we are looking at time complexity then we are looking at time complexity of o at n and similarly the space of o at n and similarly the space complexity would be also or num rows and complexity would be also or num rows and if num nodes is a smaller value if num nodes is a smaller value then it is constant okay so this goes fine uh okay so this goes fine uh runtime is 11 millisecond faster than runtime is 11 millisecond faster than this this now now thinking about you know the thinking about you know the optimizations optimizations now one very good optimization now one very good optimization is that if you look into the solution is that if you look into the solution and i can copy paste it to here and i can copy paste it to here to do a better comparison so one optimization that the solution from lead code does is that you know there are no internal while loops which is fantastic because if the number of rows is higher then you're looking at and into number of rows uh let's first submit this solution to see that you know if this solution gives runtime and you know lower than the one that we had from previous solution it does not and it may just be the test cases that we have for behind the scenes for this particular problem does not expose part from the previous solution part from the previous solution but but intuitively if number of rows is high intuitively if number of rows is high then you're looking at then you're looking at high high time complicity in the previous solution time complicity in the previous solution in this one it is in this one it is doing all of that toggling untoggling doing all of that toggling untoggling just in the one loop itself so what it just in the one loop itself so what it does does current row is zero and it has going current row is zero and it has going down as a flag to say down as a flag to say whether it is going down or going up so whether it is going down or going up so going down is false here going down is false here and then you come here in the first and then you come here in the first iteration you would add iteration you would add to our example it you would add b to our example it you would add b to the first uh to the first uh string builder string builder and then you would check whether you're and then you would check whether you're going down or not so you're looking at going down or not so you're looking at curve is equal to zero it is zero curve is equal to zero it is zero and then you would and then you would make going down as true make going down as true and in the and in the last statement in the loop you're last statement in the loop you're checking checking whether going down is true or not if whether going down is true or not if going down was true you would update car going down was true you would update car row to row to next one so car row would become one next one so car row would become one and for the next character and for the next character the second string builder will get the the second string builder will get the character character now now when you are to the uh when you are to the uh end of car rows like if you said that in end of car rows like if you said that in our example we were our example we were looking at num rows as three looking at num rows as three so after two assignment to the string so after two assignment to the string builders car row would become two builders car row would become two and curve would become when curve and curve would become when curve becomes 2 going downward become becomes 2 going downward become false again false again that means now you're going up that means now you're going up so when it becomes false so when it becomes false then you then you decrement the current row so current row decrement the current row so current row would become would become one one and in the next iteration and in the next iteration when the zigzag is going up when the zigzag is going up the second one the second one second or third string builder will not second or third string builder will not get the value get the value but the first thing will will get the but the first thing will will get the value value while going while going up up and likewise you know so that toggling and likewise you know so that toggling that we had in the previous solution that we had in the previous solution that is maintained through that is maintained through this sophisticated mechanism so this is this sophisticated mechanism so this is a better solution a better solution and and if asked you can go with both the if asked you can go with both the options options and talk about the differences between and talk about the differences between the two the two although the test cases for this although the test cases for this solution solution in lead code did not expose the high in lead code did not expose the high time complexity of the previous solution time complexity of the previous solution it is just at par it is just at par thanks for watching let me know if you thanks for watching let me know if you have any questions for me | 2024-03-18 11:33:59 | 6 | ZigZag Conversion String, a Leetcode problem solved in Java |
|
qqIA4_bmpzk | welcome back to other Jess today's question is leak code1091 shortest path question is leak code1091 shortest path and binary Matrix so given an M by m and binary Matrix so given an M by m binary Matrix grid return the length of binary Matrix grid return the length of the shortest clear path in The Matrix if the shortest clear path in The Matrix if there is no clear path return -1 so a there is no clear path return -1 so a clear path and a binary Matrix is a path clear path and a binary Matrix is a path from the top left cell to bottom right from the top left cell to bottom right cell such that all the visited cells of cell such that all the visited cells of the path are zero all the adjacent cells the path are zero all the adjacent cells of path are eight directionally of path are eight directionally connected the length of a clear path is connected the length of a clear path is the number of visited cells of this path the number of visited cells of this path so in example one we have this Grid or so in example one we have this Grid or this Matrix and we want to get from top this Matrix and we want to get from top left to bottom right and we have eight left to bottom right and we have eight possible directions to go from with this possible directions to go from with this initial point so we can go up down left initial point so we can go up down left and right and all the diagonals so we and right and all the diagonals so we first visit this cell which will equal first visit this cell which will equal one and then we move diagonally to visit one and then we move diagonally to visit the bottom right cell which will equal the bottom right cell which will equal one as well so adding those together one as well so adding those together will give us the output of two so this will give us the output of two so this question is asking for the shortest path question is asking for the shortest path so we're going to be using reference so we're going to be using reference search for the solution now we know the search for the solution now we know the starting point is always going to be at starting point is always going to be at index 0 0 and we know the end point is index 0 0 and we know the end point is always going to be the bottom right so always going to be the bottom right so we know the starting point and we know we know the starting point and we know the ending point now with breakfast the ending point now with breakfast search we're going to be using a Q and search we're going to be using a Q and this queue is going to restrict the this queue is going to restrict the process in order to First in first out process in order to First in first out so we'll always have to shift off of the so we'll always have to shift off of the queue So within the queue what we're queue So within the queue what we're going to add is we're going to add this going to add is we're going to add this starting point so we're going to add the starting point so we're going to add the starting indices as well as the count starting indices as well as the count right so we can initialize this with a right so we can initialize this with a count of one to say that we've visited count of one to say that we've visited this value right here okay so this has this value right here okay so this has been visited within each Loop of the BFS been visited within each Loop of the BFS we're going to have to make a check to we're going to have to make a check to see whether these indices are equal to see whether these indices are equal to these indices as you can see Zero Zero these indices as you can see Zero Zero is not equal to the bottom right so next is not equal to the bottom right so next thing to do is to check in each thing to do is to check in each Direction so we're going to go up down Direction so we're going to go up down left and right as well as all diagonals left and right as well as all diagonals so as you can see so as you can see all of these are out of bound this one all of these are out of bound this one we can't go here and we also can't go we can't go here and we also can't go here because they're pointing to ones so here because they're pointing to ones so we'll make that check if the next value we'll make that check if the next value is equal to a one don't go there if it's is equal to a one don't go there if it's equal to a zero we'll go there so this equal to a zero we'll go there so this is the only arrow we care about the only is the only arrow we care about the only direction we care about direction we care about so we'll add this into our queue so zero so we'll add this into our queue so zero one we're going to add the indices and one we're going to add the indices and we're also going to update the count so we're also going to update the count so one goes to two yeah so we've seen this one goes to two yeah so we've seen this we make the check we check to see where we make the check we check to see where this is at the end it's not so we check this is at the end it's not so we check the eight directions the issue we have the eight directions the issue we have here is that one of the directions goes here is that one of the directions goes back to the previous zero so before we back to the previous zero so before we even start making checks in here even start making checks in here we need to go back a step we need to go back a step and we need to update this at the end to and we need to update this at the end to one that way when we make the eight one that way when we make the eight Direction check we're going to go back Direction check we're going to go back here we're going to see that this is a here we're going to see that this is a one and we're going to back out a bit one and we're going to back out a bit because we're only looking for zeros because we're only looking for zeros within this prefer search so we're at within this prefer search so we're at this point the only directions we really this point the only directions we really care about are this one and this one so care about are this one and this one so we can add the indices of this plus is we can add the indices of this plus is count to the queue so one two we'll count to the queue so one two we'll update the count to three this one zero update the count to three this one zero two update the count to three and before two update the count to three and before we move on to checking this one we're we move on to checking this one we're going to remove this and add one so now going to remove this and add one so now we're here we check if this is at the we're here we check if this is at the end point it's not so we check the end point it's not so we check the directions so the only two that we directions so the only two that we really care about is down here and up really care about is down here and up here here so again we can add these into our queue so again we can add these into our queue and we've seen this one and we've seen this one we're currently looking at this one so we're currently looking at this one so we can add two to four in here and also we can add two to four in here and also zero two and four in here now we update zero two and four in here now we update this to one we can remove that the next this to one we can remove that the next in the queue is zero two three so we in the queue is zero two three so we shift off of Q to look at these zero two shift off of Q to look at these zero two three so this one is going to check all three so this one is going to check all of its directions right of its directions right and as you can see none of the and as you can see none of the directions are valid right because we've directions are valid right because we've updated this to one because there's a updated this to one because there's a shorter path down here that means that shorter path down here that means that we cannot go anywhere from this point so we cannot go anywhere from this point so we can back out of this go back to here we can back out of this go back to here we've seen this now and we can shift off we've seen this now and we can shift off of Q and go to 224 so when we reach 224 of Q and go to 224 so when we reach 224 we check to see whether the indices is we check to see whether the indices is equal to the end and it is so we can equal to the end and it is so we can just return this count time complexity just return this count time complexity of this one is going to be oven because of this one is going to be oven because it's a bog standard breath as such and it's a bog standard breath as such and space complexity is also going to be space complexity is also going to be oven so let's write this out so the oven so let's write this out so the first we need to make a check so if Grid first we need to make a check so if Grid at at zero zero zero zero is equal to one then we just return is equal to one then we just return minus one because there is no path going minus one because there is no path going from top left to bottom right where the from top left to bottom right where the only values we visit are zeros then we only values we visit are zeros then we need to make our directions array so I'm going to speed this up so these are all the eight directions that we're going to be going in and we're going to be using these to make the BFS a lot easier to implement with the Q we're going to initialize it and pass in the initial starting point and also a count of one then it's a case of carrying out BFS so what a q dot length we can extract the current X current Y and count so that current X count Y and count so that current X count Y and count equal Q dot shift equal Q dot shift now within JavaScript there isn't a now within JavaScript there isn't a fancy way of Shifting off the queue but fancy way of Shifting off the queue but we can consider this as like a linked we can consider this as like a linked list DQ which is a one-time capacity list DQ which is a one-time capacity if current X if current X is equal to grid dot length minus one is equal to grid dot length minus one and current Y is equal to grid and current Y is equal to grid zero dot length minus one we can return count right so if we're at the bottom right position we can just return the count then we need to Loop through the directions and the way we do this is extract X and Y from the directions array and then we create the new X and New Y and we do this by adding current x and x and we do this by adding current x and x together and current y together and current y and Y together and Y together so this is just shorthand so this is just shorthand for writing that next X for writing that next X equal current X Plus X equal current X Plus X and let next y equal current y plus y and let next y equal current y plus y just cleans up the code and makes it just cleans up the code and makes it more concise more concise now we need to make a check to see now we need to make a check to see whether the next position is inbound and whether the next position is inbound and if it's equal to zero so if next X if it's equal to zero so if next X is less than zero or is less than zero or next X is greater than grid.length minus next X is greater than grid.length minus one so two for up or too far down one so two for up or too far down or next Y is less than zero so too far or next Y is less than zero so too far left or next y left or next y is greater than grid zero dot length is greater than grid zero dot length minus one so too far to the right we minus one so too far to the right we also need to make a check if the next also need to make a check if the next value we go to is equal to one if it is then we don't want to go there so we just continue from this otherwise the position we're going to be on at this point is going to be zero so we need to push into Q that position so next X next Y and also we need to update the count here so count plus one and to stop us from carrying out repeated calculations we need to update next X next y voice we just return minus one let's run voice we just return minus one let's run that and submit it | 2024-03-25 17:10:31 | 1,091 | Shortest Path in Binary Matrix - LeetCode 1091 - JavaScript |